Monday, 9 October 2017

Blind SQL injection using file upload option

I faced an unusual form of SQL injection that fortunately (for me!) let me gain access to sensitive data in the backend database. I would like to share how I found this and exploited it with you. After doing the typical information gathering phase of the penetration test, I noticed that “dirb” (a command line alternative to DirBuster) had flagged a couple of interesting files as accessible (view Table 1). These files seemed to belong to the admin panel of the website, and thus they should not be accessible unless you had the right privileges.

http://victim/manager/do.php http://victim/manager/do2.php
Table 1 - File found by dirb. I double checked that both files were actually accessible by directly browsing to the given URL, and to my surprise I found what looked like an uploading form
Uploading Form
Image 1 – Uploading form. As shown in Image 1, the application seemed to only accept Excel files. It didn’t seem possible to upload script files and get a remote shell, not through lack of trying, so I decided to put all my efforts in finding what kind of Excel file the application was expecting and see if I could take advantage of it. I tried creating a very basic Excel file, with just one row and a few cells with some random content in it, but it didn’t work. I thought that if it was expecting an Excel file it should be parsing it and then inserting it in the database, so it may be some sort of bulk import functionality. Usually when dealing with bulk import, the application uses a standard format like CSV (Comma -separated Values) or some sort of variation. The common thing about all this formats is that most of them use the first row as a header, where they indicate the name of the fields to be read in the rows below it. An example is shown in the following table.
Piece IDPriceDescription
12345625RAM - 2Mb
12345789Graphic Card
Table 2 – Example of CSV-like format In the example we can see how the file contains a first row with three columns, each of one is used to identify the fields that will later be read. And below that first row, we can see the actual values that will be parsed and inserted in the database. With this in mind, I thought it would be worth trying a similar structure for my Excel file, and… it worked!
Valid Upload Image 2 – Message after successful Excel file upload. After some testing I came to the conclusion that the application just needed an Excel file with a header row with two fields (it did not actually matter the name of each field as long as they were there), and then a number of rows with the actual values to be parsed and inserted to the database.
Field 1Field 2
Value 1Value 2
Table 3 – Example of accepted Excel file. Curiously enough, if I tried to upload exactly the same file, without modifying any of the fields (not the header but the values), I got a different message, shown in the image below. Although at that moment I didn’t give it the importance it deserved, this would be a key factor, but I’ll come back to it in a minute.
Duplicate Upload
Image 3 – Message after duplicated Excel file upload. After playing for a while with the upload form, I was kind of stuck. I had credentials for the admin panel, but I did not want to use them, I wanted to keep it as real as possible. A real attacker would not have access to the admin panel, so I wouldn’t either. While thinking what I could possibly do with this, I thought it could be worth entering a harmless single quote in one of the values, for example in the second field, something like: “Value2’”. And to my surprise this returned the same error message as the one shown in Image 3. interestingly, it looked like the single quote was breaking the SQL query used in the back-end to insert new values. A SQL injection through an Excel Spread Sheet used to import data in bulk, this was going to be different! Once my initial happiness was gone I was ready to get my hands dirty, so I started thinking about a valid approach to exploit this specific SQL injection. A very important nuance is that the values read from the Excel file were used in an INSERT statement, cutting down the exploitation methods. And to make things even worse, I was probably injecting in the last parameter of the INSERT clause, reducing even more my chances of exploitation. Let me explain you why:
INSERT INTO Table_name (Field1, Field2) VALUES ('+ Value1_from_XLS +','+ Value2_from_XLS +');
In the piece of code above we can see my idea of what the SQL query they were using looked like. As mentioned before, I was injecting in the last part of that query, more concretely where it says “Value2_from_XLS”. That meant that apart from having to exploit the SQL injection in an INSERT clause (not as usual and not as easy as in a SELECT statement), I had to do it by crafting a request that didn’t break the syntax of the INSERT clause but doing something useful for me at the same time, and the fact that the injection point was at the last parameter did not help at all! But hold on, why don’t you use the first parameter (Value1), so you can close it with a single quote and then use the second field of the clause to insert something useful that hopefully you can later retrieve?. Well, I wondered the same thing, so I proceeded to use the first value to carry on with the exploitation, but... it did not work! Yeah, you are reading right, it did NOT work! I was not able to craft a single request that injected my own SQL code and that at the same time did not break the original query. After giving it some thought, going for a walk, doing some push ups, asking to my colleagues and listening to Justin Bieber to get some inspiration… something crossed my mind. I told to myself “Why is it giving me a different message if I use the same exact values in two following uploads?” And I answered to myself something like “Well, maybe it is because it is doing some sort of verification to ensure that there are no duplicate entries in the database, it sounds reasonable after all, right?” So with this in mind, I drafted a quick pseudo-code with what in theory the application was doing in the back-end: q1 =
SELECT * FROM Table_name WHERE Field1='+ Value1_from_XLS +'; if (q1 > 0) already exists else q2 = INSERT INTO Table_name (Field1, Field2) VALUES ('+ Value1_from_XLS +','+ Value2_from_XLS +');
If my theory was correct I could use the first field as the injection point in a SELECT statement and take advantage of the two different messages shown back by the application to perform a strange form of Blind SQL injection. To prove my theory I crafted two different Excel files, one that would force the overall SELECT clause to evaluate as true, and one that would do the opposite. To do this all I had to do is use a value that did not exist in the database, and combine it with an OR statement that I could modify to my need:
Field 1Field 2
invalidValue’ OR 1=1NotImportant
Table 4 – Overall evaluation of TRUE
Field 1Field 2
invalidValue’ OR 1=2NotImportant
Table 5 – Overall evaluation of FALSE I crossed my fingers, tested both Excel files, and… it worked!. After all my efforts and almost the whole day gone I had a shiny working SQL injection. The next morning, with a fresh mind, I successfully retrieved some sample data to show the client in the report (I won’t go through the details of it as it is out of the scope of this post). Note that although the XLS format is somehow encoded and has tons of clutter, you can still see the raw strings of your data, so with the help of Burp Intruder the process was not too painful. To conclude, while carrying out a penetration test, and as shown in this post, you can find vulnerabilities anywhere. 

Saturday, 7 October 2017

Basic about SQL injection using SQLMAP

# Scenario

1.1 Detect and exploit a SQL injection:

Let's say that you are auditing a web application and found a web page that accepts dynamic user-provided
values on GET or POST parameters or HTTP Cookie values or HTTP User-Agent header value. You now
want to test if these are afefcected by a SQL injection vulnerability, and if so, exploit them to retrieve as much
information as possible out of the web application's back-end database management system or even be able
to access the underlying 1e system and operating system.
In a simple world, consider that the target url is:
Assume that:
is the same page as the original one and:
diers from the original one, it means that you are in front of a SQL injection vulnerability in the id
GET parameter of the index.php web application page which means that potentially no IDS/IPS, no web
application rewall, no parameters' value sanitization is performed on the server-side before sending the SQL
statement to the back-end database management system the web application relies on.
This is a quite common aw in dynamic content web applications and it does not depend upon the back-
end database management system nor on the web application programming language: it is a programmer

code's security aw. The Open Web Application Security Project rated on 2010 in their OWASP Top Ten
survey this vulnerability as the most common and important web application vulnerability along with other
injection Laws.
Back to the scenario, probably the SQL SELECT statement into get_int.php has a syntax similar to the
following SQL query, in pseudo PHP code:
$query = "SELECT [column(s) name] FROM [table name] WHERE id=" . $_REQUEST['id'];
As you can see, appending any other syntatically valid SQL condition after a value for id such condition
will take place when the web application passes the query to the back-end database management system
that executes it, that is why the condition id=1 AND 1=1 is valid (True) and returns the same page as the
original one, with the same content. This is the case of a boolean-based blind SQL injection vulnerability.
However, sqlmap is able to detect any type of SQL injection and adapt its work-ow accordingly. Read
below for further details.
Moreover, in this simple and easy to inject scenario it would be also possible to append, not just one or more
valid SQL condition(s), but also stacked SQL queries, for instance something like [...]&id=1; ANOTHER
SQL QUERY# if the web application technology supports stacked queries , also known as multiple statements .
Now that you found this SQL injection vulnerable parameter, you can exploit it by manipulating the id
parameter value in the HTTP request.
There exist many resources on the Net explaining in depth how to prevent, detect and exploit SQL injection
vulnerabilities in web application and it is recommended to read them if you are not familiar with the issue
before going ahead with sqlmap.
Passing the original address, to sqlmap, the
tool will automatically:
 Identify the vulnerable parameter(s) (id in this example);
 Identify which SQL injection techniques can be used to exploit the vulnerable parameter(s);
 Fingerprint the back-end database management system;
 Depending on the user's options, it will extensively ngerprint, enumerate data or takeover the database
server as a whole.
1.2. Direct connection to the database management system
Up until sqlmap version 0.8, the tool has been yet another SQL injection tool , used by web application
penetration testers/newbies/curious teens/computer addicted/punks and so on. Things move on and as
they evolve, we do as well. Now it supports this new switch, -d, that allows you to connect from your
machine to the database server's TCP port where the database management system daemon is listening on
and perform any operation you would do while using it to attack a database via a SQL injection vulnerability.
1.3 Techniques
sqlmap is able to detect and exploit  SQL injection types:
 Boolean-based blind SQL injection, also known as inferential SQL injection: sqlmap replaces
or appends to the aected parameter in the HTTP request, a syntatically valid SQL statement string
containing a SELECT sub-statement, or any other SQL statement whose the user want to retrieve the
output. For each HTTP response, by making a comparison between the HTTP response headers/body
with the original request, the tool inference the output of the injected statement character by character.
Alternatively, the user can provide a string or regular expression to match on True pages. The bisection
algorithm implemented in sqlmap to perform this technique is able to fetch each character of the output
with a maximum of seven HTTP requests. Where the output is not within the clear-text plain charset,
sqlmap will adapt the algorithm with bigger ranges to detect the output.
 Time-based blind SQL injection, also known as full blind SQL injection: sqlmap replaces or
appends to the affected parameter in the HTTP request, a syntatically valid SQL statement string
containing a query which put on hold the back-end DBMS to return for a certain number of seconds.
For each HTTP response, by making a comparison between the HTTP response time with the original
request, the tool inference the output of the injected statement character by character. Like for
boolean-based technique, the bisection algorithm is applied.
 Error-based SQL injection: sqlmap replaces or append to the aected parameter a database-spec.
syntatically wrong statement and parses the HTTP response headers and body in search of DBMS
error messages containing the injected pre-dened chain of characters and the statement output within.
This technique works when the web application has been congured to disclose back-end database
management system error messages only.
 UNION query SQL injection, also known as inband SQL injection: sqlmap appends to the
 parameter a syntatically valid SQL statement string starting with a UNION ALL SELECT. This
techique works when the web application page passes the output of the SELECT statement within a forcycle, or similar, so that each line of the query output is printed on the page content. sqlmap is also
able to exploit partial (single entry) UNION query SQL injection vulnerabilities which occur
when the output of the statement is not cycled in a for construct whereas only the rst entry of the
query output is displayed.
 Stacked queries SQL injection, also known as multiple statements SQL injection: sqlmap tests
if the web application supports stacked queries then, in case it does support, it appends to the aected
parameter in the HTTP request, a semi-colon (;) followed by the SQL statement to be executed.
This technique is useful to run SQL statements other than SELECT like, for instance, data denition
or data manipulation statements possibly leading to le system read and write access and operating
system command execution depending on the underlying back-end database management system and
the session user privileges.

Monday, 31 July 2017

XSS in Referer Header

Exploiting cross-site scripting in Referer header

The application that echoes the Referer header is vulnerable to cross-site scripting. And it is perfectly exploitable. Here is how:
Suppose we have an application that generates a "Back" link from Referer header (let's call it vulnerable.php):
echo '<a href="';
echo '">Back</a>\n';
We can inject HTML and JavaScript if we can set the Referer header. This can be done if we first get the victim to visit a page created by the attacker. Consider the following page (let's call it exploit.html):
<form   id="xss"
If the victim is tricked into visiting<script>alert(1);</script> he will end up on the vulnerable page with the Referer header containing XSS attack.
This attack works in Internet Explorer, but does not work in Firefox, because Firefox will URL-encode the naughty characters after the question mark. It may still be possible to exploit this with Firefox, but some trickery with mod_rewrite will be needed to have XSS data in the path, instead of in the query.

Tuesday, 11 April 2017

How hacker hacked your unverified facebook accounts !

Here’s a little write-up on how hacker (annoymous)was able to delete any unverified account in facebook. By unverified, I mean those accounts who didnot yet verify their email address linked to facebook.
All (or most) of my bugs have been authentication related to many vendors, this was no different.
It was found in 2014 by one great hacker (one of my friend). i am reposting that blog again.

Here is how hacker did it:

The sign up function lets you create a new Facebook account but the response was different when the email was verified vs. when the email for the account was unverified. If you use a Facebook account that already has an account in Facebook (with its email unverified), the response you get is :
When clicked on the “Insert the confirmation code instead” it lets you enter 5-digit number only code.

Lets generate a dictionary from 00000 to 99999.
  1. for i in range(0,99999):
  2. print '{0:05d}'.format(i)

Now, straightforward stuff! I fired up Burp Suite, “Swiss army knife” for me.

Notice something peculiar in the last request?
Yep, the response length changes to show that you’ve made the correct guess. (AJAX response in burp response says that).
There was no rate limit on the number of requests you could make.
Some math work :
possible password = 100,000
If  number of requests = 100/sec.
Time taken to figure out the code (worst case scenario) = 15 minutes

The impact?

I could permanently delete any unverified Facebook accounts within 15 minutes. You would try to recover using “password recover” feature but all your friends, PM’s would be gone. You would have to create entirely new account.
All I had to do was squander my bandwidth and keep brute forcing (and sit back and relax).

How did I find out if an account was unverified?

Well, one way was to sign up using that email and see the response (if you are asked to enter confirmation code or not).

For a large number of emails, the other way was to enumerate facebook users first, to find out if the email had a facebook account and then use “Change email address field” to sort out which accounts have facebook associated with it and are still unverified.
A fix was deployed after 8 hours of submission.
and after 3 days, a handsome bounty followed up:

Thanks for the read!

Tuesday, 28 March 2017

THICK client application Security research

What are thick client applications?
A thick client, also known as Fat Client is a client in client–server architecture or network and typically provides rich functionality, independent of the server. In these types of applications, the major processing is done at the client side and involves only aperiodic connection to the server.
Thick Client vs Thin Client applications:
The thick clients are heavy applications which normally involve the installation of application on the client side (user computer). These application take up memory and run completely on the computers resources. This means that the security of the application is dependent on the local computer.
Thick clients are often not well-suited for public environments. To maintain a thick client, IT needs to maintain all systems for software deployment and upgrades, rather than just maintaining the applications on the server. Additionally, thick clients often require specific applications, again posing more work and limitations for deployment.
Typical examples of thick clients are G-Talk, Yahoo Messenger, Microsoft Outlook,online trading portals,etc…
The thin client applications are web-based application which can be accessed on the internet using a browser. These types of applications do not require any installation of software on the client side. The complete processing is carried out on the server. Also, these are light weight and do not occupy any space on the client side (user computer). In addition,thin client apps can be accessed by any computer or mobile device that has internet access, making them very portable. With that said, thin client apps are only as fast and reliable as the user’s internet connection and the server’s bandwidth.
Examples of thin client application are web-sites like or
The thick client applications are made of two types:
Two tier thick client application:
The two tier thick client application consists of the user computer and the server. In this type, the application is installed on the client side, which directly communicates with the database on the server. These usually involve legacy applications. (E.g. – The VB.NET application directly communicating with the database using Open Database Connectivity)
Three tier thick client application:
These kinds of thick client applications involve three tiers, wherein the client talks to the application server, which in turn talks to the database. The communication in these applications is carried out using HTTP/HTTPS. Examples of these applications involve G-Talk or Yahoo Messenger.
Security Assessment of Thick client applications:
Application security assessments of thin client applications are comparatively easier than thick client application, as these are web based applications which can be intercepted easily and major processing takes place at the server side.
Since the thick client applications include both local and server side processing, it requires a different approach for security assessment.
The table below distinguishes the vulnerabilities faced by a web based and a thick client application:
Web based vulnerabilities
Thick Client based vulnerabilities
Improper error handling
SQL Injection
Cross Site Scripting
Not applicable – browser based vulnerability
Clickjacking attacks
Not applicable – browser based vulnerability
Parameter Tampering
Insecure Storage
Denial of Service
Reverse engineering
Not Applicable
Broken access control
Session management
Refer for more details on the vulnerabilities listed above.
List of tools that can used intercepting thick client applications:
  1. Echo Mirage:
    Echo Mirage is a network proxy tool that uses DLL injection and function hooking techniques to intercept the traffic transmitted and received by the local applications. Traffic can be intercepted in real-time or manipulated with regular expressions and a number of action directives.
    Echo Mirage can be run in two different modes:
  • By launching an executable from Echo Mirage
  • Injecting into a currently running process
By launching an executable from Echo Mirage
In this option, the path of the application is provided into the Echo Mirage tool and it launches the selected application. The data sent and received by the application is intercepted by Echo Mirage.
The screenshot below shows the Gtalk traffic intercepted by the Echo Mirage tool.
Injecting into a currently running process:
In this, the Echo Mirage tool injects into the process by hooking into the socket calls.
Select the thick client application from the list of running processes, and inject Echo Mirage using the “inject into a running process” option from the tool.
Echo Mirage can also be useful in capturing data from JAVAApplets. For capturing data from a JAVA applet, inject Echo Mirage into the process “java.exe”.
  1. BURP Proxy invisible proxy mode:
    BURPProxy is an intercepting proxy server for security testing of web applications.
    The BURP proxy tool can be used in invisible proxy mode to intercept the request from non-proxy-aware thick client applications (HTTP/HTTPS traffic only).
    More Details can be found here:
  1. Mallory: Transparent TCP and UDP proxy
    Mallory is a proxy tool that can intercept TCP and UDP traffic and can be used to capture network traffic or thick client applications using both HTTP(S) and non-HTTP(S) traffic.
    In manycases, the above mentioned tools like Echo Mirage get hanged due to heavy network traffic and become difficult to test. Mallory comes to the rescue in such cases.
    The ideal setup for Mallory is to have a “LAN” or “Victim” network that Mallory acts as the gateway for. This can be configured within a virtual machine environment using only network interfaces. The victim virtual machine then configures the Mallory machine as the gateway by manually setting its gateway. The gateway machine will have at least one WAN interface that grants Internet access. The victim network then uses the Mallory gateway to route traffic.
    More details can be found here:
  2. Ethereal/Wireshark:
    Wireshark is a network protocol analyzer tool that can be used to analyze the network traffic. This tool can be used to study the non-encrypted traffic sent by the thick client application.
    More details can be found here:
  3. Interactive TCP Relay:
    It allows for intercepting the traffic for thick client applications. ITR serves as a TCP tunnel between the client and the server. By instructing the client to open its connection to the ITR instead of the server, the entire connection is shifted to work through the ITR, without the client or the server noticing a difference.
    More details can be found here:
  4. JAVA Snoop:
    This tool can be used to intercept the methods, alter data and also test the security of JAVA applications on your computer.
In the following sections, we will discuss the critical vulnerabilities faced by thick client application.
  1. Sensitive data storage on files and registries:
    During the installation and execution of thick client applications, these apps tend to write/modify sensitive details in the files and registries. The sensitive data stored by these apps usually include username, passwords, database credentials, license details, cryptographic keys, and configuration details like IP address, port, etc…
    The attacker can get access to these sensitive details and might compromise the application. In order to assess the application for sensitive data storage, we need to analyze the files and registries used by the application. Using a sysinternal tool called “Process Monitor”, we can identify the files and registries used by a particular thick client application.
    Process Monitor:
    Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, registry and process/thread activity. This tool by default starts monitoring all processes. By setting up proper filters, it can be set to only capture the data related to a particular process.
    Registry Monitoring:
    Set the Process Monitor tool to intercept the registry activity as shown below:
    Analyze the registries accessed by the application to check for sensitive details like keys, encrypted passwords, etc…
    File Monitoring:
    Set the Process Monitor tool to intercept the file access activity, as shown below:
    Analyze the files accessed by the application to check for sensitive details like configuration details, log writing, caching files in folders, etc…
    Listed below are a few sample exploits that a thick client application may face:
    Sample Exploits 1:
    A thick client tool (licensed version of a tool)after license registration on ‘A’ machine stores the license validation key and expiry date in encrypted format as a value in the registry. Whenever the tool is opened, a function in the tool validates against this registry value and provides access to the GUI of the tool.
    Exploit: An attacker may export the registry key from ‘A’ machine and import this registry key into the ‘B’ machine to use the professional tool thereby bypassing the license registration process.
    Sample Exploit 2:
    During installation, a two tier thick client application stores a configuration file locally on the machine containing the database IP, port, username and password locally.
    Exploit: An attacker might get access to this configuration file containing the database connectivity details. He might then directly connect to and compromise the database.
    Sample Exploit 3:
    A thick client application writing/storing application logs containing sensitive details like user accounts, trading details, last login date and time, etc… on the user machine.
    Exploit: An attacker can get access to this machine and steal the user specific details written on to the log files.
  1. Response Modification
    We are all aware about capturing requests and tampering the parameters for the testing of vulnerabilities in web based applications. In the case of thick clients, major processing/validations are carried at the client side. As a result both the request as well as response modifications play a key role in testing the thick client for vulnerabilities.
    Sample Exploit 1:
    Consider a thick client applications that displays the GUI(modules/sub-modules) based on the response parameters received from the server after authentication.
    For example,when an Admin logs in, the response sent by the application is as follows:
Response —– …….U.s.e.r=A.D.M.I.N…..A.c.c.o.u.n.t.N.o=1111
When a low privileged user logs in, the response sent by the application is as follows:
Response —– …….U.s.e.r=C.U.S.T.…..A.c.c.o.u.n.t._.N.o=2111
Exploit: In this case, the attacker or the lower privileged user will intercept the response and modify the User and Account_No parameter to that of the Admin and get access to the administrator module.
Sample Exploit 2:
As we discussed above,the major validations are carried out at the client side, a faulty implementation of authentication process has been observed in various two tier apps and is described below.
When a user enters the user name and password in the application, the application sends a SQL query to the database containing the username to retrieve the user credentials.
The SQL query is as follows:
Select MD5Hash_Password
From User_Table
Where User_Name=’Admin1′;
The response received from the database is as follows:
Response —- … MD5Hash_Password= 3f7caa3d471688b704b73e9a77b1107f
It can be observed that only the username is sent to the database, and the database sends the valid password back in the response. This password is compared locally at the client side with the password entered by the user on the login page.
Exploit: The attacker can enter a correct username (say Cust1) and a wrong password on the login page. The application will send a SQL query to the database with the username entered, and retrieve the correct password. The attacker will then intercept the response, and steal the hashed password(Cust1 in this case).
  1. Memory Analysis using WinHex Tool:
    All applications, be it web based or thick client applications, temporarily store data into the memory (Random Access Memory) for further processing. An application might store sensitive data like user credentials or encryption keys into the memory and store them until they get written by other data. An attacker may run a memory reading tool like WinHex in the machine to analyze the entire memory content used by the application.
    The screenshot below shows the memory dump of Google Talk application.
Other vulnerabilities that can be tested for in thick client apps are as follows:
  • SQL Injection
  • Session Management
  • Authentication
  • Authorization
  • Input validations
  • Password management