Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Practice library / Exploit development and reversing

Lab · Hard · 2.5 hoursFree account

Format String Vulnerabilities

Read stack memory, leak canaries, and perform arbitrary writes with %n.

  • format-string
  • memory-corruption
  • stack-canary
  • libc
  • linux
On this page 7 sections
  1. ·Build the target
  2. ·Topics Covered
  3. ·The Vulnerability
  4. Locked: Reading the Stack
  5. Locked: Arbitrary Read with %s
  6. Locked: Arbitrary Write with %n
  7. Locked: pwntools fmtstr\_payload

Before you start

A format string bug happens when user input reaches a printf-family function as the format argument. The attacker then reads stack memory with %x, dereferences any address with %s, and writes to any address with %n. Real incidents turn these primitives into stack canary leaks and GOT overwrites for full code execution. This lab walks you through each primitive on a vulnerable C program and ends with a redirect of execution through the GOT.

Lab Objectives

  • Identify format string vulnerabilities in C source code
  • Use %x/%p to read values off the stack
  • Find the offset of your own input on the stack
  • Leak canaries and libc addresses using %s
  • Perform an arbitrary write using %n
  • Overwrite a GOT entry to redirect execution

Build the target

KaliRange hosts no target. Compile the vulnerable program yourself and run every command below against it.

cat > vuln.c <<'EOF'
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void shell(void) { system("/bin/sh"); }   // the target of the GOT overwrite in the last section
int main(void) {
    char buf[256] = {0};
    read(0, buf, sizeof(buf) - 1);
    printf(buf);     // FORMAT STRING BUG — user controls the format string
    exit(0);
}
EOF
gcc -m32 -fno-stack-protector -no-pie -o vuln vuln.c
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space

Disabling ASLR keeps the stack offsets you find the same between runs. The offset 7 in the examples is an example: find the offset of your own build as shown in "Reading the Stack".

Topics Covered

  • Printf format specifiers and the stack layout
  • %x/%p for sequential stack reads
  • %s for arbitrary address dereference
  • %n for arbitrary writes (bytes written counter)
  • GOT overwrite technique
  • fmtstr_payload automation with pwntools

The Vulnerability

// Vulnerable code pattern
char buf[256];
read(0, buf, 256);
printf(buf);     // FORMAT STRING BUG — user controls the format string
// Correct usage: printf("%s", buf)

When the format string is attacker-controlled, every %x, %s, or %n reads from or writes to the stack at the attacker's direction.

Sign in to continue

4 more sections are for signed-in members. It is free: sign in with Google.

Related