The Metasploit Framework (MSF)

⚡ Prerequisites

  • Basic familiarity with Linux & Windows

  • Basic familiarity with TCP & UDP protocols

📕 Learning Objectives

  • Understand, install, configure and use Metasploit Framework

  • Perform info-gathering, enumeration, exploitation, post exploitation with Metasploit

🔬 Training list - PentesterAcademy/INE Labs

subscription required

MSF Introduction

🗒️ The Metasploit Framework (MSF) is an open-source pentesting and exploit development platform, used to write, test and execute exploit code.

  • Provides automation of the penetration testing life cycle (specially exploitation and post-exploitation)

  • Used to develop and test exploits

  • Has a world database and public tested exploits

  • It is modular, new modules can be added and integrated

  • Founded by H.D. Moore in 2003 (developed in Perl), Written in Ruby in 2007, acquired by Rapid7 in 2009, released as Metasploit v6.0 in 2020

  • Metasploit Framework is the Community Edition

  • Metasploit Pro & Express are Commercial versions

📌 Check the Metasploit Unleashed – Free Ethical Hacking Course by OffSec

Terminology

Term
Description

Interface

Methods of interacting with the Metasploit Framework (msfconsole, Metasploit cmd)

Module

Pieces of code that perform a particular task (an exploit)

Vulnerability

Exploitable flaw or weakness in a computer system or network

Exploit

Code/Module used to take advantage of a vulnerability

Payload

Piece of code delivered to the target by an exploit (execute arbitrary commands or provide remote access)

Listener

Utility that listens for an incoming connection from a target

📌 Exploit is launched (takes advantage of the vulnerability) ➡️ Payload dropped (executes a reverse shell command) ➡️ Connects back to the Listener

Interfaces

🗒️ Metasploit Framework Console (MSFconsole) - an all in one interface that provides with access to all the functionality of the MSF.

msfconsole

🗒️ Metasploit Framework Command Line Interface (MSFcli) - a command line utility used to facilitate the creation of automation scripts that utilize Metasploit modules.

  • Discontinued in 2015, MSFconsole can be used with the same functionality of redirecting output from other tools into msfcli and vice versa.

🗒️ Metasploit Community Edition GUI - a web based GUI front-end of the MSF.

🗒️ Armitage - a free Java based GUI front-end cyber attack management tool for the MSF.

  • Visualizes targets and simplifies network discovery

  • Recommends exploits

  • Exposes the advanced capabilities of the MSF

Metasploit Framework Architecture - oreilly.com

🗒️ A module is the piece of code that can be utilized and executed by the MSF.

The MSF libraries (Rex, Core, Base) allow to extend and initiate functionality, facilitating the execution of modules without having to write additional code.

MSF Module
Description

Exploit

Used to take advantage of a vulnerability, usually paired with a payload

Payload

Code delivered and remotely executed on the target after successful exploitation - e.g. a reverse shell that initiates a connection

Encoder

Used to encode payloads in order to avoid Anti Virus detection - e.g. shikata_ga_nai encoding scheme

NOPS

Keep the payload sizes consistent across exploit attempts and ensure the stability of a payload on the target system

Auxiliary

Is not paired with a payload, used to perform additional functionality - e.g. port scanners, fuzzers, sniffers, etc

Payloads are created at runtime from various components. Depending on the target system and infrastructure, there are two types of payloads that can be used:

  • Non-Staged Payload - sent to the target system as is, along with the exploit

  • Staged Payload - sent to the target in two parts:

    • the stager (first part) establish a stable communication channel between the attacker and target. It contains a payload, the stage, that initiates a reverse connection back to the attacker

    • the stage (second part) is downloaded by the stager and executed

      • executes arbitrary commands on the target

      • provides a reverse shell or Meterpreter session

🗒️ The Meterpreter is an advanced multi-functional payload executed by in memory DLL injection stagers on the target system.

  • Communicates over the stager socket

  • Provides an interactive command interpreter on the target system

ls /usr/share/metasploit-framework
  • MSF filesystem is intuitive and organized by directories.

  • Modules are stored under:

    • /usr/share/metasploit-framework/modules/

    • ~/.msf4/modules - user specified modules


Pentesting with MSF

🗒️ PTES (Penetration Testing Execution Standard) is a methodology that contains 7 main sections, defined by the standard as a comprehensive basis for penetration testing execution.

  • can be adopted as a roadmap for Metasploit integration and understanding of the phases of a penetration test.

The various phases involved in a typical pentest should be:

📌 Pre-Engagement Interactions

⬇️

📌 Information Gathering

⬇️

📌 Enumeration

  • Threat Modeling

  • Vulnerability Analysis

⬇️

📌 Exploitation

  • Identify Vulnerable Services

  • Prepare Exploit Code

  • Gaining Access

  • Bypass AV detection

  • Pivoting

⬇️

📌 Post Exploitation

  • Privilege Escalation

  • Maintaining Persistent Access

  • Clearing Tracks

⬇️

📌 Reporting

Pentesting Phase
MSF Implementation

Information Gathering & Enumeration

Auxiliary Modules, nmap reports

Vulnerability Scanning

Auxiliary Modules, nessus reports

Exploitation

Exploit Modules & Payloads

Post Exploitation

Meterpreter

Privilege Escalation

Post Exploitation Modules, Meterpreter

Maintaining Persistent Access

Post Exploitation Modules, Persistence

PTES - infopulse.com

Metasploit Fundamentals

🗒️ The Metasploit Framework Database (msfdb) contains all the data used with MSF like assessments and scans data, etc.

  • Uses PostgreSQL as the primary database - postgresql service must be running

  • Facilitates the import and storage of scan results (from Nmap, Nessus, other tools)

  • Use APT package manager on Kali Linux (or on Debian-based distros)

  • Enable postgresql at boot, start the service and initialize MSF database

  • Run msfconsole to start the Metasploit Framework Console

  • Check the db connection is on in the msfconsole

📌 Check this article by StationX ➡️ How to Use Metasploit in Kali Linux + Metasploitable3 which will cover:

  • Deploying a Kali Linux virtual machine with Metasploit pre-installed

  • Setting up a target in a virtual lab, Metasploitable3, with Vagrant

  • A sample walkthrough against a vulnerable MySQL Server

  • Frequently Asked Questions (FAQ)

🗒️ The Metasploit Framework Console (msfconsole) is an all-in-one interface and centralized console that allows access to all of the MSF options and features.

  • It is launched by running the msfconsole command

  • Run it in quiet mode without the banner with

Module Variables

An MSF module requires additional information that can be configured through the use of MSF variables, both local or global variables, called options inside the msfconsole.

Variables e.g. (they are based on the selected module):

  • LHOST - attacker's IP address

  • LPORT - attacker's port number (receive reverse connection)

  • RHOST - target's IP address

  • RHOSTS - multiple targets/networks IP addresses

  • RPORT - target port number

Useful Commands

  • Run msfconsole and check these useful commands:

Port Scan Example

CVE Exploits Example

search cve:2017 type:exploit platform:window

Payload Options Example

🗒️ Metasploit Workspaces allows to manage and organize the hosts, data, scans and activities stored in the msfdb.

  • Import, manipulate, export data

  • Create, manage, switch between workspaces

  • Sort and organize the assessments of the penetration test

📌 It's recommended to create a new workspace for each engagement.

workspace -h
  • Create a new workspace

  • Change workspace

  • Delete a workspace

Information Gathering & Enumeration with MSF

  • The Metasploit Framework allows to import nmap results.

Nmap Enumeration

nmap enumeration results (service versions, operating systems, etc) can be exported into a file that can be imported into MSF and used for further detection and exploitation.

🔬 Check the full nmap information gathering lab in this Nmap Host Discovery Lab (at the end of the page).

Some commands:

  • Output the nmap scan results into an .XML format file that can be imported into MSF

  • In the same lab environment from above, use msfconsole to import the results into MSF with the db_import command

  • Inside msfconsole

  • Perform an nmap scan within the MSF Console and import the results in a dedicated workspace

MSF Auxiliary modules are used during the information gathering (similar to nmap) and the post exploitation phases of the pentest.

  • perform TCP/UDP port scanning

  • enumerate services

  • discover hosts on different network subnets (post-exploitation phase)

Lab Network Service Scanning

🔬 Lab T1046 : Network Service Scanning

  • Exploitation

  • Perform a network scan on the second target

  • Add the route within meterpreter and background the meterpreter session

  • Upload and run nmap against the second target, from the first target machine

📌 There are 3 running services on the second target machine.

UDP Scan

  • Into msfconsole

📌🔬 Check the Enumeration Section labs here for basic nmap enumeration.

Next, there are some MSF commands and modules for service enumeration on the same labs from the Enumeration Section.

  • Auxiliary modules can be used for enumeration, brute-force attacks, etc

❗📝 On every attacker machine, run this command to start msfconsole:

  • Setup a global variable. This will set the RHOSTS option for all the modules utilized:

auxiliary/scanner/ftp/ftp_version

auxiliary/scanner/ftp/ftp_login

auxiliary/scanner/ftp/anonymous

auxiliary/scanner/smb/smb_version

auxiliary/scanner/smb/smb_enumusers

auxiliary/scanner/smb/smb_enumshares

auxiliary/scanner/smb/smb_login

🔬 Metasploit - Apache Enumeration Lab

  • Remember to specify the correct port and if targeting a web server with SSL enabled, in the options.

auxiliary/scanner/http/apache_userdir_enum

auxiliary/scanner/http/brute_dirs

auxiliary/scanner/http/dir_scanner

auxiliary/scanner/http/dir_listing

auxiliary/scanner/http/http_put

auxiliary/scanner/http/files_dir

auxiliary/scanner/http/http_login

auxiliary/scanner/http/http_header

auxiliary/scanner/http/http_version

auxiliary/scanner/http/robots_txt

🔬 Metasploit - MySQL Enumeration Lab

auxiliary/admin/mysql/mysql_enum

auxiliary/admin/mysql/mysql_sql

auxiliary/scanner/mysql/mysql_file_enum

auxiliary/scanner/mysql/mysql_hashdump

auxiliary/scanner/mysql/mysql_login

auxiliary/scanner/mysql/mysql_schemadump

auxiliary/scanner/mysql/mysql_version

auxiliary/scanner/mysql/mysql_writable_dirs

  • Check the MySQL Enumerated data within MSF:

🔬 Metasploit - SSH Login

auxiliary/scanner/ssh/ssh_version

auxiliary/scanner/ssh/ssh_login

  • This module sets up SSH sessions

auxiliary/scanner/ssh/ssh_enumusers

🔬 SMTP - Postfix Recon: Basics

auxiliary/scanner/smtp/smtp_enum

auxiliary/scanner/smtp/smtp_version

Vulnerability Scanning With MSF

MSF Auxiliary and exploit modules can be utilized to identify inherent vulnerabilities in services, O.S. and web apps.

  • Useful in the Exploitation phase of the pentest

🔬 Metasploitable3 lab environment will be used for the vulnerability scanning demonstration.

  • Metasploitable3 is a vulnerable virtual machine developed by Rapid7, intended to be used as a vulnerable target for testing exploits with Metasploit.

🔬 You can find my lab installation & configuration with Vagrant at this page, set up for educational purposes.

  • Kali Linux attacker machine must be configured with the same local network of the Metasploitable3 VMs.

Detect active hosts on the local network, from the Kali VM:

  • Run Metasploit:

  • Service version is a key piece of information for the vulnerabilities scanning. Use the db_nmap command inside the MSF

db_nmap
  • Manually search for a specific exploit

    • Check if there are any exploits for a particular version of a service

search type:exploit name:iis
  • Check if a module will work on the specific version of the service

  • Use searchsploit tool from the Kali terminal, instead of search MSF command, by displaying only the Metasploit exploit modules

  • Back in msfconsole, check if the server is vulnerable to MS17-010

metasploit-autopwn - a Metasploit plugin for easy exploit & vulnerability attack.

  • takes a look at the Metasploit database and provides a list of exploit modules to use for the already enumerated services

  • On a Kali terminal

  • On msfconsole

db_autopwn -p -t -PI 445
  • On msfconsole use the analyze command to auto analyze the contents of the MSFdb (hosts & services)

analyze
vulns

VA with Nessus

🔬 You can find my Nessus Essentials install tutorial here.

  • A vulnerability scan with Nessus result can be imported into the MSF for analysis and exploitation.

  • Nessus Essentials free version allows to scan up to 16 IPs.

Start Nessus Essentials on the Kali VM, login and create a New Basic Network Scan and run it.

Wait for the scan conclusion and export the results with the Export/Nessus button.

Nessus Essentials - Metasploitable3
  • Open the msfconsole terminal and import the Nessus results

    • Check the information from the scan results with the hosts, services, vulns commands

VA with WMAP

🗒️ WMAP is a web application vulnerability scanner that allows to conduct and automate web server enumeration and scanning from within the Metasploit Framework.

  • Available as a fully integrated MSF plugin

  • Utilizes the in-built MSF auxiliary modules

🔬 The lab is the same one from the HTTP Metasploit Enumeration section above - Metasploit - Apache Enumeration Lab

  • Load WMAP extension within msfconsole

load wmap
  • Add WMAP site

  • Specify the target URL

  • Show only the MSF modules that will be able to be run against target

  • Run the web app vulnerability scan

    • this will run all enabled modules against the target web server

  • Analyze the results produced by WMAP.

wmap_run -t
wmap_run -e
  • List WMAP found vulnerabilities

  • Since the allowed methods are POST, OPTIONS, GET, HEAD, exploit the vulnerability with the use of auxiliary/scanner/http/http_put module to upload a file into the /data directory

    • 📌 A reverse shell payload can be uploaded and run on the target.

Metasploit - auxiliary/scanner/http/http_put
  • Test if the file has been uploaded correctly

A client-side attack is a security breach that happens on the client side.

  • Social engineering techniques take advantage of human vulnerabilities

  • Require user-interaction to open malicious documents or portable executables (PEs)

  • The payload is stored on the client's system

  • Attackers have to pay attention to Anti Virus detection

Advanced modern antivirus solutions detects and blocks this type of payloads very easily.

Msfvenom Payloads

msfvenom - a Metasploit standalone payload generator and encoder

  • e.g. - generate a malicious meterpreter payload, transfer it to a client target; once executed it will connect back to the payload handler and provides with remote access

  • List available payloads

  • When generating a payload the exact name of the payload must be specified

    • target operating system

    • target O.S. architecture (x64, x86 ...)

    • payload type

    • protocol used to connect back (depends on requirements)

e.g. of Staged payload

  • windows/x64/meterpreter/reverse_tcp

e.g. of Non-Staged payload

  • windows/x64/meterpreter_reverse_https

  • Generate a Windows payload with msfvenom

32bit payload:

64bit payload:

  • List the output formats available

  • Generate a Linux payload with msfvenom

32bit payload:

64bit payload:

  • 📌 Platform and architecture are auto selected if not specified, based on the selected payload

The transferring method onto the target system depends on the type of the social engineering technique.

  • e.g. A simple web server can be set up on the attacker system to serve the payload files and a handler to receive the connection back from the target system

  • To deal with a meterpreter payload, an appropriate listener is necessary to handle the reverse connection, the multi/handler Metasploit module in this case

  • Download the payload on the Windows 2008 system (in this case my home lab VM) from this link

    • http://192.168.31.128:8080

    • Run the payloadx86.exe payload on the target

  • The meterpreter session on the attacker machine should be opened

Same example with the linux/x86/meterpreter/reverse_tcp Linux payload executed on the Kali VM.

Encoding Payloads

Signature based Antivirus solutions can detect malicious files or executables. Older AV solutions can be evaded by encoding the payloads.

  • This kind of attack vector is outdated and hardly used today.

  • May work on legacy old O.S. like Windows 7 or older.

🗒️ Payload Encoding involves changing the payload shellcode with the aim of changing the payload signature.

🗒️ Shellcode is the code typically used as a payload for exploitation, that provides with a remote command shell on the target system.

msfvenom --list encoders
  • Excellent encoders are cmd/powershell_base64 and x86/shikata_ga_nai

Windows Payload

  • Generate a Win x86 payload and encode it with shikata_ga_nai:

msfvenom shikata_ga_nai Win
  • The payload can be encoded as often as desired by increasing the number of iterations.

  • The more iterations, the better chances to bypass an Antivirus. Use -i option.

Linux Payload

msfvenom shikata_ga_nai Linux
  • Test each of the above generated payloads, like before

📌 Modern antivirus detects and blocks the encoded payload as soon as the download is started:

Injecting Payloads into PEs

🗒️ Windows Portable Executable (PE) is a file format for executables, object code, DLLs and others, used in 32-bit and 64-bit Windows O.S.

  • Download a portable executable, e.g. WinRAR

  • Payloads can be injected into PEs with msfvenom with the -x and -k options

  • Transfer and run the winrar.exe file to the target O.S.

  • File description is kept, but not its functionality.

  • Proceed with the Post Exploitation module to migrate the process into another one, in the meterpreter session

Automation with Resource Scripts

Repetitive tasks and commands can be automated using MSF resource scripts (same as batch scripts).

  • Almost every MSF command can be automated.

/usr/share/metasploit-framework/scripts/resource

e.g. 1

  • Automate the process of setting up a handler for the generated payloads, by creating a new handler.rc file

  • Load and run the recourse script in msfconsole

msfconsole -q -r handler.rc

e.g. 2

msfconsole -q -r portscan.rc

e.g. 3

  • 📌 Load up a resource script from within the msfconsole with the resource command

  • Typed in commands in a new msfconsole session, can be exported in a new resource script

Exploitation with MSF

HFS (HTTP File Server)

A HFS (HTTP File Server) is a file and documents sharing web server.

  • Rejetto HFS - free open source HTTP file server

🔬 HFS - MSF Exploit

SMB - MS17-010 EternalBlue

🔬 Check the Lab 2 - Eternal Blue here

  • Some MSF useful commands from my Home Lab (Kali VM + Win 2008_R2 Server)

WinRM

  • Identify WinRM users with MSF and exploit WinRM by obtaining access credentials.

  • Default WinRM HTTP port is 5985 and HTTPS 5986

🔬 WinRM Attack lab

Apache Tomcat

Apache Tomcat is a free open source Java servlet web server, build to host dynamic websites and web apps developed in Java.

  • Tomcat default TCP port is 8080

  • Apache web server host HTML/PHP web apps, instead

  • Apache Tomcat < v.8.5.23 is vulnerable to a JSP Upload Bypass / RCE

🔬 Tomcat - MSF Exploit

FTP

vsftpd is an Unix FTP server.

  • vsftpd v.2.3.4 is vulnerable to a command execution vulnerability

🔬 FTP - MSF Exploit

SAMBA

Samba is the Linux implementation of SMB.

  • Samaba v.3.5.0 is vulnerable to a RCE vulnerability

🔬 Samba - MSF Exploit

SSH

libssh is a C library that implements the SSHv2 protocol

  • SSH default TCP port is 22

  • libssh v.0.6.0 - 0.8.0 is vulnerable to an authentication bypass vulnerability

🔬 SSH - MSF Exploit

SMTP

Haraka is an open source high performance SMTP server developed in Node.js

  • SMTP default TCP port is 25

    • other TCP ports are 465 and 587

  • Haraka prior to v.2.8.9 is vulnerable to command injection

🔬 SMTP - MSF Exploit

🗒️ Post Exploitation is the process of gaining further information or access to the target's internal network, after the initial exploitation phase, using various techniques like:

There are many post exploitation modules provided by the MSF.

🗒️ Persistence consists of techniques used by adversaries to maintain access to systems across restarts, changed credentials, or other interruptions.

🗒️ Keylogging is the action of (secretly) recording/capturing the keystrokes entered on a target system.

🗒️ Pivoting is a post exploitation technique of using a compromised host, a foothold / plant, to attack other systems on its private internal network.

Fundamentals - Meterpreter

  • Facilitates the execution of system commands, file system navigation, keylogging

  • Load custom scripts and plugins dynamically

  • 📌 MSF has various types of Meterpreter payloads based on the target environment

🔬 Check the Meterpreter Labs for various Meterpreter commands and techniques examples and how to upgrade shells to Meterpreter sessions.

Windows PE Modules

Windows post exploitation MSF modules can be used to:

  • Enumerate user privileges, logged-on users, installed programs, antiviruses, computers connected to a domain, installed patches and shares

  • VM check

🗒️ Windows Event Logs, accessed via the Event Viewer on Windows, are categorized into:

  • Application logs - apps startups, crashes, etc

  • System logs - system startups, reboots, etc

  • Security logs - password changes, authentication failures/success, etc

Clearing event logs is an important part of the system assessment.

🔬 Check out the Windows Post Exploitation with MSF Labs with post-exploitation techniques for various Windows services.

Linux PE Modules

Linux post exploitation MSF modules can be used to:

  • Enumerate system configuration, environment variables, network configuration, user's history

  • VM check

🔬 Check out the Linux Post Exploitation with MSF Labs with post-exploitation techniques for various Unix services.

Armitage - MSF GUI

🗒️ Armitage is a Java-based GUI front-end for the MSF.

  • Automate port scanning, exploitation, post exploitation

  • Visualize targets

  • Requires MSFdb and services to be running

  • Pre-packed with Kali Linux

🔬 Port Scanning & Enumeration With Armitage - lab by INE

  • Victim Machine 1: 10.2.21.86

  • Victim Machine 2: 10.2.25.150

Armitage
  • Hosts - Add Hosts

    • Add victim 1 IP

    • Set the lab as Victim 1

  • Right-click the target and Scan it

  • Check Services

  • Perform an Nmap Scan from the Hosts menu

  • Check Services

Exploitation

  • Search for rejetto and launch the exploit module

  • Try Dump Hashes via the registry method

Metasploit - post/windows/gather/smart_hashdump
  • Saved hashes can be found under the View - Loot menu

  • Browse Files

  • Show Processes

Pivoting

  • Setup Pivoting

  • Add, Enumerate and Exploit Victim 2

  • Port forward the port 80 and use nmap

  • Remove the created localhost 127.0.0.1

  • Search for BadBlue and use the badblue_passthru exploit on Victim 2

  • Migrate to an x64 from the Processes tab

  • Dump hashes with the lsass method

Armitage Kali Linux Install


Last updated

Was this helpful?