> 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/00-master-cheatsheet.md).

# Binary Exploitation CTF — Master Cheatsheet

## ─── QUICK RECON ──────────────────────────────────────────────────────────────

```bash
file ./vuln                          # architecture, stripped, static/dynamic
checksec --file=./vuln               # all protections at once
strings ./vuln | grep -E 'sh|flag|win|pass|system|exec'
nm ./vuln 2>/dev/null | grep -E 'win|flag|system|shell'
objdump -d ./vuln | grep -E 'call|jmp' | head -40
ldd ./vuln                           # linked libraries + their addresses
readelf -s ./vuln                    # symbol table
readelf -r ./vuln                    # relocation table (GOT entries)
readelf -S ./vuln                    # section headers
ltrace ./vuln                        # library calls trace
strace ./vuln                        # syscall trace
```

## ─── PROTECTIONS QUICK REFERENCE ─────────────────────────────────────────────

| Protection    | Check          | Bypass                         |
| ------------- | -------------- | ------------------------------ |
| NX/DEP        | NX enabled     | ROP / ret2libc / ret2syscall   |
| Stack Canary  | Canary found   | Leak via format string / brute |
| ASLR          | kernel setting | Leak libc/binary addr          |
| PIE           | PIE enabled    | Leak binary base addr          |
| Full RELRO    | Full RELRO     | Can't overwrite GOT            |
| Partial RELRO | Partial RELRO  | GOT overwrite possible         |
| No RELRO      | No RELRO       | GOT + .init\_array writable    |

## ─── OFFSETS & OVERFLOW ───────────────────────────────────────────────────────

```bash
# Find crash offset with cyclic pattern
python3 -c "from pwn import *; print(cyclic(200))"
python3 -c "from pwn import *; print(cyclic_find(0x6161616c))"  # from crash RIP

# GDB pwndbg
cyclic 200
cyclic -l <crashed_rsp_value>

# Manual: buf + saved_rbp + saved_rip
# 64-bit: offset = buf_size + 8 (rbp)
# 32-bit: offset = buf_size + 4 (ebp)
```

## ─── GADGET HUNTING ───────────────────────────────────────────────────────────

```bash
ROPgadget --binary ./vuln                          # all gadgets
ROPgadget --binary ./vuln | grep "pop rdi"
ROPgadget --binary ./vuln | grep "pop rsi"
ROPgadget --binary ./vuln | grep "pop rdx"
ROPgadget --binary ./vuln | grep ": ret$"          # just ret (alignment)
ROPgadget --binary ./vuln | grep "syscall"
ROPgadget --binary ./vuln | grep "leave"
ROPgadget --binary ./vuln | grep "xchg rsp"
ROPgadget --binary ./vuln --ropchain               # auto ROP chain

ropper -f ./vuln --search "pop rdi"
ropper -f /lib/x86_64-linux-gnu/libc.so.6 --search "pop rdi"

# In libc
one_gadget /lib/x86_64-linux-gnu/libc.so.6        # magic gadgets → shell
one_gadget -r 5 ./libc.so.6                        # relax constraints
```

## ─── PWNTOOLS QUICK API ───────────────────────────────────────────────────────

```python
from pwn import *

# Setup
context.arch = 'amd64'       # or 'i386'
context.os   = 'linux'
context.log_level = 'debug'  # verbose

# Binary/Library
elf  = ELF('./vuln')
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')

# Process / Remote
p = process('./vuln')
p = remote('host', port)
p = gdb.debug('./vuln', 'break main')

# Send/Receive
p.send(payload)                    # raw send
p.sendline(payload)                # send + newline
p.sendafter(b'prompt', payload)    # wait for prompt, then send
p.sendlineafter(b'prompt', payload)
p.recv(n)                          # receive n bytes
p.recvline()                       # receive until \n
p.recvuntil(b'marker')             # receive until marker
p.recvall()                        # receive until EOF
p.interactive()                    # manual interaction

# Packing
p64(0xdeadbeef)   # little-endian 8-byte
p32(0xdeadbeef)   # little-endian 4-byte
u64(b'\x...')     # unpack 8 bytes to int
u32(b'\x...')     # unpack 4 bytes to int
flat([addr1, addr2, ...])  # pack list of values

# ELF helpers
elf.sym['main']       # address of main
elf.plt['puts']       # puts@plt
elf.got['puts']       # puts@got
elf.bss()             # .bss start
elf.search(b'/bin/sh') # search for bytes → iterator

# After libc leak
libc.address = leaked_addr - libc.sym['puts']  # set base
libc.sym['system']     # now absolute
next(libc.search(b'/bin/sh'))
```

## ─── FORMAT STRING QUICK REFERENCE ───────────────────────────────────────────

```
%p      → print pointer (hex)
%s      → dereference and print string  ← arbitrary read
%n      → write byte count to pointer  ← arbitrary write
%hn     → write 2-byte value
%hhn    → write 1-byte value
%Nc     → print N characters (controls value for %n)
%N$p    → print Nth argument (direct access)
%N$s    → read Nth argument as pointer
%N$n    → write to address in Nth argument

Find offset: send "AAAA.%1$p.%2$p..." and look for 0x41414141
Pwntools:   fmtstr_payload(offset, {addr: value})
```

## ─── SYSCALL TABLE (x86-64) ──────────────────────────────────────────────────

```
rax   name      args (rdi, rsi, rdx)
0     read      fd, buf, count
1     write     fd, buf, count
2     open      path, flags, mode
3     close     fd
59    execve    filename, argv, envp   ← SHELL
60    exit      status
231   exit_group status
```

## ─── HEAP QUICK REFERENCE ────────────────────────────────────────────────────

```bash
# GDB commands (pwndbg)
heap                      # all chunks
bins                      # bin contents
tcache                    # tcache state
vis_heap_chunks           # visual layout
malloc_chunk <addr>       # inspect chunk

# Chunk header (64-bit)
[prev_size 8B][size 8B | flags][user_data...]
# Freed tcache chunk:
[prev_size 8B][size 8B][fd 8B][key 8B][...]
```

| Attack        | Requirement          | Result                    |
| ------------- | -------------------- | ------------------------- |
| UAF           | Write after free     | Tcache fd corruption      |
| Double Free   | Free twice           | Same as UAF               |
| Heap Overflow | Write past chunk end | Corrupt next chunk header |
| Tcache Poison | Corrupt fd           | malloc returns any addr   |

## ─── COMMON EXPLOIT PATTERNS ─────────────────────────────────────────────────

```
ret2win:     overflow → ret to win()
ret2libc:    overflow → pop rdi; /bin/sh → system()
ret2plt:     overflow → puts(got_puts) → leak libc → system()
ret2syscall: overflow → set regs → syscall execve
SROP:        overflow → rax=15, syscall → fake sigframe → execve
stack pivot: overflow → leave;ret → pivot rsp to BSS ROP chain
FSV read:    printf(buf) → %N$s → leak libc/canary
FSV write:   printf(buf) → fmtstr_payload → GOT overwrite
UAF/DFree:   free → write fd → malloc → arb write → __free_hook
```

## ─── LIBC VERSION DETECTION ──────────────────────────────────────────────────

```bash
strings ./libc.so.6 | grep "GNU C"
ldd ./vuln
# Use https://libc.blukat.me/ to identify from leaked addresses
# Or: libc-database lookup
```

## ─── GDB / PWNDBG COMMANDS ───────────────────────────────────────────────────

```
r                       run
b *address              breakpoint at address
b function              breakpoint at function
ni / si                 next/step instruction
c                       continue
x/gx $rsp               examine 8-byte hex at rsp
x/20gx $rsp             examine 20 qwords at rsp
x/s 0x601040            examine as string
p $rax                  print register
info registers          all registers
disas function          disassemble function
stack 20                show 20 stack entries
vmmap                   memory map
got                     GOT table
plt                     PLT table
canary                  show canary value
rop                     ROP gadgets
search -x "/bin/sh"     search memory for bytes
```


---

# 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/00-master-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.
