Metasploit Quick Reference

Modules


Metasploit modules are prepared scripts with a specific purpose and corresponding functions that have already been developed and tested in the wild. The exploit category consists of so-called proof-of-concept (POCs) that can be used to exploit existing vulnerabilities in a largely automated manner. Many people often think that the failure of the 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 our manual skills.

Once we are in the msfconsole, we can select from an extensive list containing all the available Metasploit modules. Each of them is structured into folders, which will look like this:

Syntax

Modules

Example

Modules

Index No.

The No. tag will be displayed to select the exploit we want afterward during our searches. We will see how helpful the No. tag can be to select specific Metasploit modules later.

Type

The Type tag is the first level of segregation between the Metasploit modules. Looking at this field, we can tell what the piece of code for this module will accomplish. Some of these types are not directly usable as an exploit module would be, for example. However, they are set to introduce the structure alongside the interactable ones for better modularization. To explain better, here are the possible types that could appear in this field:

Type

Description

Auxiliary

Scanning, fuzzing, sniffing, and admin capabilities. Offer extra assistance and functionality.

Encoders

Ensure that payloads are intact to their destination.

Exploits

Defined as modules that exploit a vulnerability that will allow for the payload delivery.

NOPs

(No Operation code) Keep the payload sizes consistent across exploit attempts.

Payloads

Code runs remotely and calls back to the attacker machine to establish a connection (or shell).

Plugins

Additional scripts can be integrated within an assessment with msfconsole and coexist.

Post

Wide array of modules to gather information, pivot deeper, etc.

Note that when selecting a module to use for payload delivery, the use <no.> command can only be used with the following modules that can be used as initiators (or interactable modules):

Type

Description

Auxiliary

Scanning, fuzzing, sniffing, and admin capabilities. Offer extra assistance and functionality.

Exploits

Defined as modules that exploit a vulnerability that will allow for the payload delivery.

Post

Wide array of modules to gather information, pivot deeper, etc.

OS

The OS tag specifies which operating system and architecture the module was created for. Naturally, different operating systems require different code to be run to get the desired results.

Service

The Service tag refers to the vulnerable service that is running on the target machine. For some modules, such as the auxiliary or post ones, this tag can refer to a more general activity such as gather, referring to the gathering of credentials, for example.

Name

Finally, the Name tag explains the actual action that can be performed using this module created for a specific purpose.


Searching for Modules

Metasploit also offers a well-developed search function for the existing modules. With the help of this function, we can quickly search through all the modules using specific tags to find a suitable one for our target.

MSF - Search Function

Modules

For example, we can try to find the EternalRomance exploit for older Windows operating systems. This could look something like this:


MSF - Searching for EternalRomance

Modules

We can also make our search a bit more coarse and reduce it to one category of services. For example, for the CVE, we could specify the year (cve:<year>), the platform Windows (platform:<os>), the type of module we want to find (type:<auxiliary/exploit/post>), the reliability rank (rank:<rank>), and the search name (<pattern>). This would reduce our results to only those that match all of the above.

MSF - Specific Search

Modules


Module Selection

To select our first module, we first need to find one. Let's suppose that we have a target running a version of SMB vulnerable to EternalRomance (MS17_010) exploits. We have found that SMB server port 445 is open upon scanning the target.

Modules

We would boot up msfconsole and search for this exact exploit name.

MSF - Search for MS17_010

Modules

Next, we want to select the appropriate module for this scenario. From the Nmap scan, we have detected the SMB service running on version Microsoft Windows 7 - 10. With some additional OS scanning, we can guess that this is a Windows 7 running a vulnerable instance of SMB. We then proceed to select the module with the index no. 2 to test if the target is vulnerable.


Using Modules

Within the interactive modules, there are several options that we can specify. These are used to adapt the Metasploit module to the given environment. Because in most cases, we always need to scan or attack different IP addresses. Therefore, we require this kind of functionality to allow us to set our targets and fine-tune them. To check which options are needed to be set before the exploit can be sent to the target host, we can use the show options command. Everything required to be set before the exploitation can occur will have a Yes under the Required column.

MSF - Select Module

Modules

Here we see how helpful the No. tags can be. Because now, we do not have to type the whole path but only the number assigned to the Metasploit module in our search. We can use the command info after selecting the module if we want to know something more about the module. This will give us a series of information that can be important for us.

MSF - Module Information

Modules

After we are satisfied that the selected module is the right one for our purpose, we need to set some specifications to customize the module to use it successfully against our target host, such as setting the target (RHOST or RHOSTS).

MSF - Target Specification

Modules

In addition, there is the option setg, which specifies options selected by us as permanent until the program is restarted. Therefore, if we are working on a particular target host, we can use this command to set the IP address once and not change it again until we change our focus to a different IP address.

MSF - Permanent Target Specification

Modules

Finally, since we are about to use a TCP-based reverse shell (/windows/meterpreter/reverse_tcp) we need to specify to which IP address it needs to connect to in order to establish a connection. Therefore, we need to set LHOST to our own IP address like following:

MSF - LHOST Specification

Modules

Once everything is set and ready to go, we can proceed to launch the attack. Note that the payload was not set here, as the default one is sufficient for this demonstration.

MSF - Exploit Execution

Modules

We now have a shell on the target machine, and we can interact with it.

MSF - Target Interaction

Modules

This has been a quick and dirty example of how msfconsole can help out quickly but serves as an excellent example of how the framework works. Only one module was needed without any payload selection, encoding or pivoting between sessions or jobs.

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. The show targets command issued within an exploit module view will display all available vulnerable targets for that specific exploit, while issuing the same command in the root menu, outside of any selected exploit module, will let us know that we need to select an exploit module first.

MSF - Show Targets

Targets

When looking at our previous exploit module, this would be what we see:

Targets


Selecting a Target

We can see that there is only one general type of target set for this type of exploit. What if we change the exploit module to something that needs more specific target ranges? The following exploit is aimed at:

  • MS12-063 Microsoft Internet Explorer execCommand Use-After-Free Vulnerability.

If we want to find out more about this specific module and what the vulnerability behind it does, we can use the info command. This command can help us out whenever we are unsure about the origins or functionality of different exploits or auxiliary modules. Keeping in mind that it is always considered best practice to audit our code for any artifact generation or 'additional features', the info command should be one of the first steps we take when using a new module. This way, we can familiarize ourselves with the exploit functionality while assuring a safe, clean working environment for both our clients and us.

MSF - Target Selection

Targets

Looking at the description, we can get a general idea of what this exploit will accomplish for us. Keeping this in mind, we would next want to check which versions are vulnerable to this exploit.

Targets

We see options for both different versions of Internet Explorer and various Windows versions. Leaving the selection to Automatic will let msfconsole know that it needs to perform service detection on the given target before launching a successful attack.

If we, however, know what versions are running on our target, we can use the set target <index no.> command to pick a target from the list.

Targets


Target Types

There is a large variety of target types. Every target can vary from another by service pack, OS version, and even language version. It all depends on the return address and other parameters in the target or within the exploit module.

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. It is all determined by the type of return address required to identify the target. This address can be jmp esp, a jump to a specific register that identifies the target, or a pop/pop/ret. For more on the topic of return addresses, see the Stack-Based Buffer Overflows on Windows x86 module. Comments in the exploit module's code can help us determine what the target is defined by.

To identify a target correctly, we will need to:

  • Obtain a copy of the target binaries

  • Use msfpescan to locate a suitable return address

Later in the module, we will be delving deeper into exploit development, payload generation, and target identification.

Payloads


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 (exploits job) and then run on the target OS to typically return a reverse connection to the attacker and establish a foothold (payload's job).

There are three different types of payload modules in the Metasploit Framework: Singles, Stagers, and Stages. Using three typologies of payload interaction will prove beneficial to the pentester. It can offer the flexibility we need to perform certain types of tasks. Whether or not a payload is staged is represented by / in the payload name.

For example, windows/shell_bind_tcp is a single payload with no stage, whereas windows/shell/bind_tcp consists of a stager (bind_tcp) and a 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. They are the sole object sent and executed on the target system, getting us a result 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, simply put, an exploitation process that is modularized and functionally separated to help segregate the different functions it accomplishes into different code blocks, each completing its objective individually but working on chaining the attack together. This will ultimately grant an attacker remote access to the target machine if all the stages work correctly.

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

Stage0 of a staged payload represents the initial shellcode sent over the network to the target machine's vulnerable service, which has the sole purpose of initializing a connection back to the attacker machine. This is what is known as a reverse connection. As a Metasploit user, we will meet these under the common names reverse_tcp, reverse_https, and bind_tcp. For example, under the show payloads command, you can look for the payloads that look like the following:

MSF - Staged Payloads

Payloads

Reverse connections are less likely to trigger prevention systems like the one initializing the connection is the victim host, which most of the time resides in what is known as a security trust zone. However, of course, this trust policy is not blindly followed by the security devices and personnel of a network, so the attacker must tread carefully even with this step.

Stage0 code also aims to read a larger, subsequent payload into memory once it arrives. After the stable communication channel is established between the attacker and the victim, the attacker machine will most likely send an even bigger payload stage which should grant them shell access. This larger payload would be the Stage1 payload. We will go into more detail in the later sections.

Meterpreter Payload

The Meterpreter payload is a specific type of multi-faceted payload that uses DLL injection to ensure the connection to the victim host is stable, hard to detect by simple checks, and persistent across reboots or system changes. Meterpreter resides completely in the memory of the remote host and leaves no traces on the hard drive, making it very difficult to detect with conventional forensic techniques. In addition, scripts and plugins can be loaded and unloaded dynamically as required.

Once the Meterpreter payload is executed, a new session is created, which spawns up the Meterpreter interface. It is very similar to the msfconsole interface, but all available commands are aimed at the target system, which the payload has "infected." It offers us a plethora of useful commands, varying from keystroke capture, password hash collection, microphone tapping, and screenshotting to impersonating process security tokens. We will delve into more detail about Meterpreter in a later section.

Using Meterpreter, we can also load in different Plugins to assist us with our assessment. We will talk more about these in the Plugins section of this module.


Searching for Payloads

To select our first payload, we need to know what we want to do on the target machine. For example, if we are going for access persistence, we will probably want to select a Meterpreter payload.

As mentioned above, Meterpreter payloads offer us a significant amount of flexibility. Their base functionality is already vast and influential. We can automate and quickly deliver combined with plugins such as GentilKiwi's Mimikatz Plugin parts of the pentest while keeping an organized, time-effective assessment. To see all of the available payloads, use the show payloads command in msfconsole.

MSF - List Payloads

Payloads

As seen above, there are a lot of available payloads to choose from. Not only that, but we can create our payloads using msfvenom, but we will dive into that a little bit later. We will use the same target as before, and instead of using the default payload, which is a simple reverse_tcp_shell, we will be using a Meterpreter Payload for Windows 7(x64).

Scrolling through the list above, we find the section containing Meterpreter Payloads for Windows(x64).

Payloads

As we can see, it can be pretty time-consuming to find the desired payload with such an extensive list. We can also use grep in msfconsole to filter out specific terms. This would speed up the search and, therefore, our selection.

We have to enter the grep command with the corresponding parameter at the beginning and then the command in which the filtering should happen. For example, let us assume that we want to have a TCP based reverse shell handled by Meterpreter for our exploit. Accordingly, we can first search for all results that contain the word Meterpreter in the payloads.

MSF - Searching for Specific Payload

Payloads

This gives us a total of 14 results. Now we can add another grep command after the first one and search for reverse_tcp.

Payloads

With the help of grep, we reduced the list of payloads we wanted down to fewer. Of course, the grep command can be used for all other commands. All we need to know is what we are looking for.


Selecting Payloads

Same as with the module, we need the index number of the entry we would like to use. To set the payload for the currently selected module, we use set payload <no.> only after selecting an Exploit module to begin with.

MSF - Select Payload

Payloads

After selecting a payload, we will have more options available to us.

Payloads

As we can see, by running the show payloads command within the Exploit module itself, msfconsole has detected that the target is a Windows machine, and such only displayed the payloads aimed at Windows operating systems.

We can also see that a new option field has appeared, directly related to what the payload parameters will contain. We will be focusing on LHOST and LPORT (our attacker IP and the desired port for reverse connection initialization). Of course, if the attack fails, we can always use a different port and relaunch the attack.


Using Payloads

Time to set our parameters for both the Exploit module and the payload module. For the Exploit part, we will need to set the following:

Parameter

Description

RHOSTS

The IP address of the remote host, the target machine.

RPORT

Does not require a change, just a check that we are on port 445, where SMB is running.

For the payload part, we will need to set the following:

Parameter

Description

LHOST

The host's IP address, the attacker's machine.

LPORT

Does not require a change, just a check that the port is not already in use.

If we want to check our LHOST IP address quickly, we can always call the ifconfig command directly from the msfconsole menu.

MSF - Exploit and Payload Configuration

Payloads

Then, we can run the exploit and see what it returns. Check out the differences in the output below:

Payloads

The prompt is not a Windows command-line one but a Meterpreter prompt. The whoami command, typically used for Windows, does not work here. Instead, we can use the Linux equivalent of getuid. Exploring the help menu gives us further insight into what Meterpreter payloads are capable of.

MSF - Meterpreter Commands

Payloads

Pretty nifty. From extracting user hashes from SAM to taking screenshots and activating webcams. All of this is done from the comfort of a Linux-style command line. Exploring further, we also see the option to open a shell channel. This will place us in the actual Windows command-line interface.

MSF - Meterpreter Navigation

Payloads

Channel 1 has been created, and we are automatically placed into the CLI for this machine. The channel here represents the connection between our device and the target host, which has been established in a reverse TCP connection (from the target host to us) using a Meterpreter Stager and Stage. The stager was activated on our machine to await a connection request initialized by the Stage payload on the target machine.

Moving into a standard shell on the target is helpful in some cases, but Meterpreter can also navigate and perform actions on the victim machine. So we see that the commands have changed, but we have the same privilege level within the system.

MSF - Windows CMD

Payloads

Let's see what other types of payloads we can use. We will be looking at the most common ones related to Windows operating systems.


Payload Types

The table below contains the most common payloads used for Windows machines and their respective descriptions.

Payload

Description

generic/custom

Generic listener, multi-use

generic/shell_bind_tcp

Generic listener, multi-use, normal shell, TCP connection binding

generic/shell_reverse_tcp

Generic listener, multi-use, normal shell, reverse TCP connection

windows/x64/exec

Executes an arbitrary command (Windows x64)

windows/x64/loadlibrary

Loads an arbitrary x64 library path

windows/x64/messagebox

Spawns a dialog via MessageBox using a customizable title, text & icon

windows/x64/shell_reverse_tcp

Normal shell, single payload, reverse TCP connection

windows/x64/shell/reverse_tcp

Normal shell, stager + stage, reverse TCP connection

windows/x64/shell/bind_ipv6_tcp

Normal shell, stager + stage, IPv6 Bind TCP stager

windows/x64/meterpreter/$

Meterpreter payload + varieties above

windows/x64/powershell/$

Interactive PowerShell sessions + varieties above

windows/x64/vncinject/$

VNC Server (Reflective Injection) + varieties above

Other critical payloads that are heavily used by penetration testers during security assessments are Empire and Cobalt Strike payloads. These are not in the scope of this course, but feel free to research them in our free time as they can provide a significant amount of insight into how professional penetration testers perform their assessments on high-value targets.

Besides these, of course, there are a plethora of other payloads out there. Some are for specific device vendors, such as Cisco, Apple, or PLCs. Some we can generate ourselves using msfvenom. However, next up, we will look at Encoders and how they can be used to influence the attack outcome.

Encoders


Over the 15 years of existence of the Metasploit Framework, Encoders have assisted with making payloads compatible with different processor architectures while at the same time helping with antivirus evasion. Encoders come into play with the role of changing the payload to run on different operating systems and architectures. These architectures include:

x64

x86

sparc

ppc

mips

They are also needed to remove hexadecimal opcodes known as bad characters from the payload. Not only that but encoding the payload in different formats could help with the AV detection as mentioned above. However, the use of encoders strictly for AV evasion has diminished over time, as IPS/IDS manufacturers have improved how their protection software deals with signatures in malware and viruses.

Shikata Ga Nai (SGN) was one of the most utilized encoding schemes back in the day because it was very hard to detect payloads encoded through its mechanism. However nowadays, modern detection methods have caught up, and these encoded payloads are far from being universally undetectable anymore. The name (仕方がない) means It cannot be helped or Nothing can be done about it, and rightfully so if we were reading this a few years ago. However, there are other methodologies we will explore to evade protection systems. This article from FireEye details the why and the how of Shikata Ga Nai's previous rule over the other encoders.


Selecting an Encoder

Before 2015, the Metasploit Framework had different submodules that took care of payloads and encoders. They were packed separately from the msfconsole script and were called msfpayload and msfencode. These two tools are located in /usr/share/framework2/.

If we wanted to create our custom payload, we could do so through msfpayload, but we would have to encode it according to the target OS architecture using msfencode afterward. A pipe would take the output from one command and feed it into the next, which would generate an encoded payload, ready to be sent and run on the target machine.

Encoders

After 2015, updates to these scripts have combined them within the msfvenom tool, which takes care of payload generation and Encoding. We will be talking about msfvenom in detail later on. Below is an example of what payload generation would look like with today's msfvenom:

Generating Payload - Without Encoding

Encoders

We should now look at the first line of the $buf and see how it changes when applying an encoder like shikata_ga_nai.

Generating Payload - With Encoding

Encoders

Shikata Ga Nai Encoding

GIF showcasing the Shikata Ga Nai encoding with various XOR keys.

Source: https://hatching.io/blog/metasploit-payloads2/

If we want to look at the functioning of the shikata_ga_nai encoder, we can look at an excellent post here.

Suppose we want to select an Encoder for an existing payload. Then, we can use the show encoders command within the msfconsole to see which encoders are available for our current Exploit module + Payload combination.

Encoders

In the previous example, we only see a few encoders fit for x64 systems. Like the available payloads, these are automatically filtered according to the Exploit module only to display the compatible ones. For example, let us try the MS09-050 Microsoft SRV2.SYS SMB Negotiate ProcessID Function Table Dereference Exploit.

Encoders

Take the above example just as that—a hypothetical example. If we were to encode an executable payload only once with SGN, it would most likely be detected by most antiviruses today. Let's delve into that for a moment. Picking up msfvenom, the subscript of the Framework that deals with payload generation and Encoding schemes, we have the following input:

Encoders

This will generate a payload with the exe format, called TeamViewerInstall.exe, which is meant to work on x86 architecture processors for the Windows platform, with a hidden Meterpreter reverse_tcp shell payload, encoded once with the Shikata Ga Nai scheme. Let us take the result and upload it to VirusTotal.

VirusTotal report showing 54 out of 69 engines detected TeamViewerInstall.exe as malicious, listing various trojans and suspicious detections by different antivirus engines.

One better option would be to try running it through multiple iterations of the same Encoding scheme:

Encoders

VirusTotal report showing 52 out of 65 engines detected TeamViewerInstall.exe as malicious, listing various trojans and suspicious detections by different antivirus engines.

As we can see, it is still not enough for AV evasion. There is a high number of products that still detect the payload. Alternatively, Metasploit offers a tool called msf-virustotal that we can use with an API key to analyze our payloads. However, this requires free registration on VirusTotal.

MSF - VirusTotal

Encoders

As expected, most anti-virus products that we will encounter in the wild would still detect this payload so we would have to use other methods for AV evasion that are outside the scope of this module.

Plugins


Plugins are readily available software that has already been released by third parties and have given approval to the creators of Metasploit to integrate their software inside the framework. These can represent commercial products that have a Community Edition for free use but with limited functionality, or they can be individual projects developed by individual people.

The use of plugins makes a pentester's life even easier, bringing the functionality of well-known software into the msfconsole or Metasploit Pro environments. Whereas before, we needed to cycle between different software to import and export results, setting options and parameters over and over again, now, with the use of plugins, everything is automatically documented by msfconsole into the database we are using and hosts, services and vulnerabilities are made available at-a-glance for the user. Plugins work directly with the API and can be used to manipulate the entire framework. They can be useful for automating repetitive tasks, adding new commands to the msfconsole, and extending the already powerful framework.


Using Plugins

To start using a plugin, we will need to ensure it is installed in the correct directory on our machine. Navigating to /usr/share/metasploit-framework/plugins, which is the default directory for every new installation of msfconsole, should show us which plugins we have to our availability:

Plugins

If the plugin is found here, we can fire it up inside msfconsole and will be met with the greeting output for that specific plugin, signaling that it was successfully loaded in and is now ready to use:

MSF - Load Nessus

Plugins

If the plugin is not installed correctly, we will receive the following error upon trying to load it.

Plugins

To start using the plugin, start issuing the commands available to us in the help menu of that specific plugin. Each cross-platform integration offers us a unique set of interactions that we can use during our assessments, so it is helpful to read up on each of these before employing them to get the most out of having them at our fingertips.


Installing new Plugins

New, more popular plugins are installed with each update of the Parrot OS distro as they are pushed out towards the public by their makers, collected in the Parrot update repo. To install new custom plugins not included in new updates of the distro, we can take the .rb file provided on the maker's page and place it in the folder at /usr/share/metasploit-framework/plugins with the proper permissions.

For example, let us try installing DarkOperator's Metasploit-Plugins. Then, following the link above, we get a couple of Ruby (.rb) files which we can directly place in the folder mentioned above.

Downloading MSF Plugins

Plugins

Here we can take the plugin pentest.rb as an example and copy it to /usr/share/metasploit-framework/plugins.

MSF - Copying Plugin to MSF

Plugins

Afterward, launch msfconsole and check the plugin's installation by running the load command. After the plugin has been loaded, the help menu at the msfconsole is automatically extended by additional functions.

MSF - Load Plugin

Plugins

Many people write many different plugins for the Metasploit framework. They all have a specific purpose and can be an excellent help to save time after familiarizing ourselves with them. Check out the list of popular plugins below:


Mixins

The Metasploit Framework is written in Ruby, an object-oriented programming language. This plays a big part in what makes msfconsole excellent to use. Mixins are one of those features that, when implemented, offer a large amount of flexibility to both the creator of the script and the user.

Mixins are classes that act as methods for use by other classes without having to be the parent class of those other classes. Thus, it would be deemed inappropriate to call it inheritance but rather inclusion. They are mainly used when we:

  1. Want to provide a lot of optional features for a class.

  2. Want to use one particular feature for a multitude of classes.

Most of the Ruby programming language revolves around Mixins as Modules. The concept of Mixins is implemented using the word include, to which we pass the name of the module as a parameter. We can read more about mixins here.

If we are just starting with Metasploit, we should not worry about the use of Mixins or their impact on our assessment. However, they are mentioned here as a note of how complex the customization of Metasploit can become.

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. Note that 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.


Using 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 pressing the [CTRL] + [Z] key combination or by typing the background command in the case of Meterpreter stages. This will prompt us with a confirmation message. After accepting the prompt, we will be taken back to the msfconsole prompt (msf6 >) and will immediately be able to launch a different module.

Listing Active Sessions

We can use the sessions command to view our currently active sessions.

Sessions

Interacting with a Session

You can use the sessions -i [no.] command to open up a specific session.

Sessions

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

This can be done by backgrounding our current session, which is formed due to the success of the first exploit, searching for the second module we wish to run, and, if made possible by the type of module selected, selecting the session number on which the module should be run. This can be done from the second module's show options menu.

Usually, these modules can be found in the post category, referring to Post-Exploitation modules. The main archetypes of modules in this category consist of credential gatherers, local exploit suggesters, and internal network scanners.


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. So instead, we would 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.

Viewing the Jobs Command Help Menu

We can view the help menu for this command, like others, by typing jobs -h.

Sessions

Viewing the Exploit Command Help Menu

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

Sessions

Running an Exploit as a Background Job

Sessions

Listing Running Jobs

To list all running jobs, we can use the jobs -l command. To kill a specific job, look at the index no. of the job and use the kill [index no.] command. Use the jobs -K command to kill all running jobs.

Sessions

Next up, we'll work with the extremely powerful Meterpreter payload.

Firewall and IDS/IPS Evasion - msfvenom


To better learn how we can efficiently and quietly attack a target, we first need to understand better how that target is defended. We are introduced to two new terms:

  • Endpoint protection

  • Perimeter protection


Endpoint Protection

Endpoint protection refers to any localized device or service whose sole purpose is to protect a single host on the network. The host can be a personal computer, a corporate workstation, or a server in a network's De-Militarized Zone (DMZ).

Endpoint protection usually comes in the form of software packs which include Antivirus Protection, Antimalware Protection (this includes bloatware, spyware, adware, scareware, ransomware), Firewall, and Anti-DDOS all in one, under the same software package. We are better familiarized with this form than the latter, as most of us are running endpoint protection software on our PCs at home or the workstations at our workplace. Avast, Nod32, Malwarebytes, and BitDefender are just some current names.


Perimeter Protection

Perimeter protection usually comes in physical or virtualized devices on the network perimeter edge. These edge devices themselves provide access inside of the network from the outside, in other terms, from public to private.

Between these two zones, on some occasions, we will also find a third one, called the De-Militarized Zone (DMZ), which was mentioned previously. This is a lower-security policy level zone than the inside networks' one, but with a higher trust level than the outside zone, which is the vast Internet. This is the virtual space where public-facing servers are housed, which push and pull data for public clients from the Internet but are also managed from the inside and updated with patches, information, and other data to keep the served information up to date and satisfy the customers of the servers.


Security Policies

Security policies are the drive behind every well-maintained security posture of any network. They function the same way as ACL (Access Control Lists) do for anyone familiar with the Cisco CCNA educational material. They are essentially a list of allow and deny statements that dictate how traffic or files can exist within a network boundary. Multiple lists can act upon multiple network parts, allowing for flexibility within a configuration. These lists can also target different features of the network and hosts, depending on where they reside:

  • Network Traffic Policies

  • Application Policies

  • User Access Control Policies

  • File Management Policies

  • DDoS Protection Policies

  • Others

While not all of these categories above might have the words "Security Policy" attached to them, all of the security mechanisms around them operate on the same basic principle, the allow and deny entries. The only difference is the object target they refer to and apply to. So the question remains, how do we match events in the network with these rules so that the actions mentioned earlier can be taken?

There are multiple ways to match an event or object with a security policy entry:

Security Policy

Description

Signature-based Detection

The operation of packets in the network and comparison with pre-built and pre-ordained attack patterns known as signatures. Any 100% match against these signatures will generate alarms.

Heuristic / Statistical Anomaly Detection

Behavioral comparison against an established baseline included modus-operandi signatures for known APTs (Advanced Persistent Threats). The baseline will identify the norm for the network and what protocols are commonly used. Any deviation from the maximum threshold will generate alarms.

Stateful Protocol Analysis Detection

Recognizing the divergence of protocols stated by event comparison using pre-built profiles of generally accepted definitions of non-malicious activity.

Live-monitoring and Alerting (SOC-based)

A team of analysts in a dedicated, in-house, or leased SOC (Security Operations Center) use live-feed software to monitor network activity and intermediate alarming systems for any potential threats, either deciding themselves if the threat should be actioned upon or letting the automated mechanisms take action instead.


Evasion Techniques

Most host-based anti-virus software nowadays relies mainly on Signature-based Detection to identify aspects of malicious code present in a software sample. These signatures are placed inside the Antivirus Engine, where they are subsequently used to scan storage space and running processes for any matches. When a piece of unknown software lands on a partition and is matched by the Antivirus software, most Anti-viruses quarantine the malicious program and kill the running process.

How do we circumvent all this heat? We play along with it. The examples shown in the Encoders section show that simply encoding payloads using different encoding schemes with multiple iterations is not enough for all AV products. Moreover, merely establishing a channel of communication between the attacker and the victim can raise some alarms with the current capabilities of IDS/IPS products out there.

However, with the MSF6 release, msfconsole can tunnel AES-encrypted communication from any Meterpreter shell back to the attacker host, successfully encrypting the traffic as the payload is sent to the victim host. This mostly takes care of the network-based IDS/IPS. In some rare cases, we might be met with very strict traffic rulesets that flag our connection based on the sender's IP address. The only way to circumvent this is to find the services being let through. An excellent example of this would be the Equifax hack of 2017, where malicious hackers have abused the Apache Struts vulnerability to access a network of critical data servers. DNS exfiltration techniques were used to slowly siphon data out of the network and into the hackers' domain without being noticed for months. To learn more about this attack, visit the links below:

Returning to msfconsole, its capability to now sustain AES-encrypted tunnels, together with Meterpreter's feature of running in memory, raises our capability by a margin. However, we still have the issue of what happens to a payload once it reaches its destination, before it is run and placed into memory. This file could be fingerprinted for its signature, matched against the database, and blocked, together with our chances of accessing the target. We can also be sure that AV software developers are looking at msfconsole modules and capabilities to add the resulting code and files to their signature database, resulting in most if not all of the default payloads being immediately shut down by AV software nowadays.

We are in luck because msfvenom offers the option of using executable templates. This allows us to use some pre-set templates for executable files, inject our payload into them (no pun intended), and use any executable as a platform from which we can launch our attack. We can embed the shellcode into any installer, package, or program that we have at hand, hiding the payload shellcode deep within the legitimate code of the actual product. This greatly obfuscates our malicious code and, more importantly, lowers our detection chances. There are many valid combinations between actual, legitimate executable files, our different encoding schemes (and their iterations), and our different payload shellcode variants. This generates what is called a backdoored executable.

Take a look at the snippet below to understand how msfvenom can embed payloads into any executable file:

Firewall and IDS/IPS Evasion

Firewall and IDS/IPS Evasion

For the most part, when a target launches a backdoored executable, nothing will appear to happen, which can raise suspicions in some cases. To improve our chances, we need to trigger the continuation of the normal execution of the launched application while pulling the payload in a separate thread from the main application. We do so with the -k flag as it appears above. However, even with the -k flag running, the target will only notice the running backdoor if they launch the backdoored executable template from a CLI environment. If they do so, a separate window will pop up with the payload, which will not close until we finish running the payload session interaction on the target.


Archives

Archiving a piece of information such as a file, folder, script, executable, picture, or document and placing a password on the archive bypasses a lot of common anti-virus signatures today. However, the downside of this process is that they will be raised as notifications in the AV alarm dashboard as being unable to be scanned due to being locked with a password. An administrator can choose to manually inspect these archives to determine if they are malicious or not.

Generating Payload

Firewall and IDS/IPS Evasion

Firewall and IDS/IPS Evasion

If we check against VirusTotal to get a detection baseline from the payload we generated, the results will be the following.

VirusTotal

Firewall and IDS/IPS Evasion

Now, try archiving it two times, passwording both archives upon creation, and removing the .rar/.zip/.7z extension from their names. For this purpose, we can install the RAR utility from RARLabs, which works precisely like WinRAR on Windows.

Archiving the Payload

Firewall and IDS/IPS Evasion

Firewall and IDS/IPS Evasion

Removing the .RAR Extension

Firewall and IDS/IPS Evasion

Archiving the Payload Again

Firewall and IDS/IPS Evasion

Removing the .RAR Extension

Firewall and IDS/IPS Evasion

The test2 file is the final .rar archive with the extension (.rar) deleted from the name. After that, we can proceed to upload it on VirusTotal for another check.

VirusTotal

Firewall and IDS/IPS Evasion

As we can see from the above, this is an excellent way to transfer data both to and from the target host.


Packers

The term Packer refers to the result of an executable compression process where the payload is packed together with an executable program and with the decompression code in one single file. When run, the decompression code returns the backdoored executable to its original state, allowing for yet another layer of protection against file scanning mechanisms on target hosts. This process takes place transparently for the compressed executable to be run the same way as the original executable while retaining all of the original functionality. In addition, msfvenom provides the ability to compress and change the file structure of a backdoored executable and encrypt the underlying process structure.

A list of popular packer software:

Alternate EXE Packer

ExeStealth

Morphine

MEW

Themida

If we want to learn more about packers, please check out the PolyPack project.


Exploit Coding

When coding our exploit or porting a pre-existing one over to the Framework, it is good to ensure that the exploit code is not easily identifiable by security measures implemented on the target system.

For example, a typical Buffer Overflow exploit might be easily distinguished from regular traffic traveling over the network due to its hexadecimal buffer patterns. IDS / IPS placements can check the traffic towards the target machine and notice specific overused patterns for exploiting code.

When assembling our exploit code, randomization can help add some variation to those patterns, which will break the IPS / IDS database signatures for well-known exploit buffers. This can be done by inputting an Offset switch inside the code for the msfconsole module:

Code: ruby

Besides the BoF code, one should always avoid using obvious NOP sleds where the shellcode should land after the overflow is completed. Please note that the BoF code's purpose is to crash the service running on the target machine, while the NOP sled is the allocated memory where our shellcode (the payload) is inserted. IPS/IDS entities regularly check both of these, so it is good to test our custom exploit code against a sandbox environment before deploying it on the client network. Of course, we might only have one chance to do this correctly during an assessment.

For more information about exploit coding, we recommend checking out the Metasploit - The Penetration Tester's Guide book from No Starch Press. They delve into quite some detail about creating our exploits for the Framework.


Intrusion Prevention Systems and Antivirus Engines are the most common defender tools that can shoot down an initial foothold on the target. These mainly function on signatures of the whole malicious file or the stub stage.


A Note on Evasion

This section covers evasion at a high level. Be on the lookout for later modules that will dig deeper into the theory and practical knowledge needed to perform evasion more effectively. It is worth trying some of these techniques out on older HTB machines or installing a VM with older versions of Windows Defender or free AV engines, and practicing evasion skills. This is a vast topic that cannot be covered adequately in a single section.

Last updated

Was this helpful?