agentleFS
dcbzdcbz/exploit_skillz/heap-exploit/SKILL.md

heap-exploit

Skill3 starsChanged 8 months agoMITView on GitHub

Use when developing heap overflow exploits for ptmalloc2, jemalloc, or libmalloc, crafting heap grooming strategies, building ROP chains, or analyzing heap state for binary exploitation and CTF challenges

  • Installs packages

The file

We split this skill into the rules it gives an agent

8 rules. About 0 are common, 6 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈6

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Follow the 8-step process (Steps 0-7) defined in prompt.md.

    line 41
  2. Distinctive:

    Always try this first: Follow Steps 1-5 of the prompt methodology.

    line 91
  3. Distinctive:

    Only load this when Stage 1 is exhausted: When application objects don't yield viable primitives:

    line 97
  4. Distinctive:

    When you reach Step 5/6 and need a ROP chain or JOP chain:

    line 107
  5. Very specific:

    Read the source — especially ropgadget/gadgets.py and ropgadget/core.py — to understand exactly how gadgets are found, classified, and …

    line 113
  6. Distinctive:

    Before starting the prompt methodology, gather this context:

    line 126
  7. Distinctive:

    When writing the exploit script:

    line 167
  8. Very specific:

    TEST mode: Run grooming N times (args.TEST=100) to measure success rate

    line 275

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Heap Exploit

Systematic heap overflow exploitation using staged reasoning, live heap inspection, and automated gadget discovery. Supports ptmalloc2 (glibc), jemalloc, and libmalloc (macOS) allocators.

Methodology

CRITICAL FIRST STEP: Identify the heap allocator

# Check which allocator is used
strings <binary> | grep -i malloc
ldd <binary>  # Linux
otool -L <binary>  # macOS
file <binary>

# Common indicators:
# - ptmalloc2: glibc-based Linux binaries (most common)
# - jemalloc: FreeBSD, Firefox, Redis, some custom builds
# - libmalloc: macOS/iOS native binaries (Darwin)

Load the appropriate methodology:

For general approach (works for all):

@prompt.md

For allocator-specific techniques:

@ptmalloc2.md   # For glibc/ptmalloc2 (most Linux binaries)
@jemalloc.md    # For jemalloc (FreeBSD, Firefox, Redis, etc.)
@libmalloc.md   # For libmalloc (macOS/iOS native binaries)

Follow the 8-step process (Steps 0-7) defined in prompt.md. This is the primary methodology. Do not skip steps or jump ahead.

KEY DIFFERENCES:

  • ptmalloc2: Inline metadata (chunk headers between allocations) - target metadata corruption
  • jemalloc: Separate metadata (no headers between same-size allocations) - target adjacent application objects
  • libmalloc: Magazine allocator, separate metadata, per-CPU magazines - target adjacent objects with heavy spray

Available Tools

heapinspect.py - Live Heap Inspection (ptmalloc2 only)

NOTE: This tool is for ptmalloc2/glibc only. For jemalloc, use GDB with allocator-specific commands (see jemalloc.md section 8). For libmalloc, use LLDB and macOS heap tools (see libmalloc.md section 8).

Copy heapinspect.py from this skill directory into the working directory (or run directly). Reads /proc/pid/mem — no GDB required. JSON output by default for structured analysis.

# Core commands
python3 heapinspect.py <pid> info              # Heap/libc/arena summary
python3 heapinspect.py <pid> chunks             # Walk all heap chunks
python3 heapinspect.py <pid> tcache             # Dump tcache state
python3 heapinspect.py <pid> bins               # All bin contents
python3 heapinspect.py <pid> fastbins           # Fastbin freelists
python3 heapinspect.py <pid> topchunk           # Top chunk state
python3 heapinspect.py <pid> overlap <addr> <sz> # What chunks an overflow hits
python3 heapinspect.py <pid> leaks <addr> <sz>  # Find libc/heap pointers in range
python3 heapinspect.py <pid> search <value>     # Search heap for pointer/value
python3 heapinspect.py <pid> hexdump <addr> <sz> # Raw memory dump
python3 heapinspect.py <pid> binfor <size>      # Which bin a request size maps to
python3 heapinspect.py <pid> freelist <addr>    # Walk freelist (handles safe-linking)

# Add --human for readable output instead of JSON
python3 heapinspect.py <pid> chunks --human

When to use: At every step where heap state matters — during grooming design (Step 4), validating adjacency, confirming bin contents, finding leak candidates, verifying overflow reach.

gadget_search.py - ROP/JOP Gadget Discovery

Copy from this skill directory. Requires capstone (pip install capstone).

python3 gadget_search.py <binary> [--max-gap N]

Finds multi-instruction JOP chains: register loads from controlled memory followed by indirect calls/jumps. Edit CONTROLLED_REGS dict at top of script to match your exploit's register state at the hijack point.

Escalation Stages

Stage 1: Application Object Corruption (DEFAULT)

Always try this first. Follow Steps 1-5 of the prompt methodology. Target application-level objects adjacent to the vulnerable chunk: function pointers, length fields, vtables, buffer pointers.

Most heap exploits are solved here without touching allocator metadata.

Stage 2: Allocator Metadata Techniques (FALLBACK)

Only load this when Stage 1 is exhausted. When application objects don't yield viable primitives:

@ptmalloc2.md

This contains the full House of * catalogue, tcache poisoning, safe-linking bypass, largebin attacks, FSOP chains, and glibc version constraints. Use the reasoning protocol in Section 7 of that document.

Stage 3: ROP Chain Construction

When you reach Step 5/6 and need a ROP chain or JOP chain:

  1. Clone ROPgadget source for deep understanding of gadget semantics:
    git clone https://github.com/jonathansalwan/ROPgadget /tmp/ROPgadget
    Read the source — especially ropgadget/gadgets.py and ropgadget/core.py — to understand exactly how gadgets are found, classified, and chained. This builds the mental model needed to construct reliable chains.
  2. Run ROPgadget against the target binary:
    python3 /tmp/ROPgadget/ROPgadget.py --binary <target> --ropchain
    python3 /tmp/ROPgadget/ROPgadget.py --binary <target> --only "pop|ret|mov|xchg"
    python3 /tmp/ROPgadget/ROPgadget.py --binary <target> --string "/bin/sh"
  3. Use gadget_search.py for complex indirect-call chains where ROPgadget's linear search is insufficient. Configure CONTROLLED_REGS to match your exploit state.

Initial Recon Checklist

Before starting the prompt methodology, gather this context:

# Binary protections
checksec --file=<binary>

# Identify allocator and version
## For Linux (ptmalloc2):
strings <binary> | grep -i glibc
ldd <binary>
strings libc.so.6 | grep "GNU C Library"

## For macOS (libmalloc):
sw_vers  # macOS version
otool -L <binary> | grep libsystem
strings <binary> | grep -i malloc

# Binary type
file <binary>

# If source is available, find the vulnerable allocation
grep -rn 'malloc\|calloc\|realloc\|free' <source_dir>/

Map the allocator version to active mitigations:

ptmalloc2 (glibc):

  • < 2.26: No tcache
  • 2.26-2.28: tcache, no key, hooks present
  • 2.29+: tcache key, top-chunk size check
  • 2.32+: safe-linking (fd pointer mangling)
  • 2.34+: hooks removed, need FSOP/Apple/Banana endgame

libmalloc (macOS):

  • < 10.14: Nano disabled by default
  • 10.14-13.x: Nano enabled, 5 zones (Nano/Tiny/Small/Large)
  • 14+ (Sonoma): Medium zone added, 6 zones total
  • Current: Checksums, cookies, quantum restrictions

Pwntools Exploit Skeleton

When writing the exploit script:

#!/usr/bin/env python3
from pwn import *

context.binary = elf = ELF('./<binary>')
libc = ELF('./<libc>', checksec=False)

def conn():
    if args.REMOTE:
        return remote('<host>', <port>)
    if args.GDB:
        return gdb.debug(elf.path, gdbscript='''
            b *main
            c
        ''')
    return process(elf.path)

# === Process management helpers ===
def restart_fresh():
    """Restart process to get clean heap state. May involve intentional crash."""
    # Implement server restart logic here
    # For CTF: may just return new process
    # For network service: may need to trigger crash first, then reconnect
    return conn()

# === Heap interaction helpers ===
def alloc(idx, size, data=b''):
    """Wrap the binary's allocation primitive."""
    pass

def free(idx):
    """Wrap the binary's free primitive."""
    pass

def show(idx):
    """Wrap the binary's read/print primitive."""
    pass

# === Leak primitive ===
def trigger_leak_safe(io):
    """Trigger information leak WITHOUT crashing. Returns leaked addresses."""
    # Implement leak trigger here
    # This should be callable repeatedly for testing
    pass

# === Heap grooming ===
def groom_heap(io):
    """Execute heap grooming sequence to achieve deterministic layout."""
    # Clear free lists
    # Create contiguous allocations
    # Free specific chunks
    # Replace with exploit objects
    # This is the sequence you'll iterate on to improve determinism
    pass

def validate_layout(pid):
    """Use heapinspect.py or debugger to verify heap layout."""
    # Optional: automated heap inspection to verify adjacency
    # Useful for scientific iteration on grooming strategy
    pass

# === Exploit ===
def exploit():
    io = restart_fresh()
    
    # Step 1: Trigger leak without crashing
    leak_data = trigger_leak_safe(io)
    log.success(f"Leaked addresses: {leak_data}")
    
    # Step 2: Heap grooming (the critical step)
    groom_heap(io)
    
    # Optional: validate layout if testing
    if args.VALIDATE:
        validate_layout(io.pid)
    
    # Step 3: Trigger overflow
    # Step 4: Compute offsets
    # Step 5: Write primitive / hijack control flow
    
    io.interactive()

# === Scientific testing mode ===
if args.TEST:
    # Run grooming N times, measure success rate
    successes = 0
    attempts = int(args.TEST)
    for i in range(attempts):
        io = restart_fresh()
        leak_data = trigger_leak_safe(io)
        groom_heap(io)
        # Check if layout is correct (via heapinspect or known indicator)
        if validate_layout(io.pid):
            successes += 1
        io.close()
    log.info(f"Success rate: {successes}/{attempts} ({100*successes/attempts:.1f}%)")
else:
    exploit()

Key structure elements:

  1. restart_fresh(): Clean heap state, essential for reproducibility
  2. trigger_leak_safe(): Non-crashing leak, can be called repeatedly
  3. groom_heap(): The function you'll iterate on scientifically
  4. validate_layout(): Debugger-based verification of heap state
  5. TEST mode: Run grooming N times (args.TEST=100) to measure success rate

Fill in the interaction helpers first. Every allocation, free, and read the binary exposes should have a clean wrapper.

Scientific iteration workflow:

# Test current grooming strategy
python3 exploit.py TEST=100

# Debug single run with GDB
python3 exploit.py GDB

# Run actual exploit
python3 exploit.py

Common Mistakes

MistakeFix
Jumping straight to metadata attacksAlways try app-object corruption first
Freeing 7 same-size chunks to drain tcache first (ptmalloc2)Free 7 same-size chunks to drain tcache first
Wrong size class calculationptmalloc2: round to 16-byte + 0x10 header; libmalloc: quantum-based
Ignoring safe-linking on glibc 2.32+Need heap base leak to mangle/demangle fd pointers
Not verifying adjacency before overflowUse heapinspect.py overlap (ptmalloc2) or memory dump to confirm
Building ROP without understanding gadget semanticsRead ROPgadget source first, don't just grep output
Hardcoding offsets without leakAlways compute: target = leak + (known_offset)
Assuming deterministic layout on libmallocPer-CPU magazines require heavy spray (1000+ allocs)
Forgetting quantum alignment on libmallocAll sizes round to quantum: Nano/Tiny=16, Small=512, Medium=32K
Ignoring zone-specific protections on libmallocNano has cookies, Small/Medium have checksums
Not scripting heap grooming experimentsCRITICAL: Script restart, leak, grooming, and validation. Run 100+ iterations to measure success rate. Iterate scientifically by changing ONE variable at a time and measuring impact on determinism.
Testing grooming only onceA single successful layout doesn't prove reliability. Always test grooming strategy with repeated runs (50-100+) to measure actual success rate. Aim for >95% determinism.
Modifying multiple grooming parameters at onceChange ONE variable per experiment (e.g., number of fillers, free pattern, allocation order). Otherwise you can't identify which change improved reliability.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.