What is an SQL Injection Attack?


 

SQL injection is a code injection technique that exploits a 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 an instance of a more general class of vulnerabilities that can occur whenever one programming or scripting language is embedded inside another. 

So, what specifically is SQL injection? It is the susceptability that results when you offer an hacker the power to control the Structured Query Language (SQL) queries that an application gives to a back-end database. When you are capable to influence what’s transferred to the database, the attacker can take advantage of the format and features of SQL itself, along with the ability and versatility of assisting storage system operation and OS functionality accessible to the storage system. SQL injection isn’t a susceptability that specifically influences Web products; any code that takes input via an untrusted origin thereafter uses that input to make dynamic SQL statements is usually vulnerable (e. g., “fat client” programs in a client/server architecture).  SQL injection seems to have quite possibly been around ever since SQL repository were being very first related to Web products.  SQL injection is undoubtedly an attack by which SQL program code is put or appended in to application/ user input variables that can be subsequently transferred to a back-end SQL server for parsing and execution. Any procedure that constructs SQL statements could very well perhaps become sensitive and vulnerable, as the varied nature of SQL and the techniques available for building it supply a wealth of coding possibilities. The primary way of SQL injection involves direct insertion of program code in parameters which can be concatenated with SQL codes and executed. A significantly less direct attack injects malevolent program code within strings that can be meant just for backup in a table or as meta-data. After the stored strings are eventually concatenated into a dynamic SQL request, the harmful program code is completed.  When a Web software ceases to suitably clean the parameters which might be transferred towards dynamically generated SQL statements (even though applying parameterization techniques) it is also possible for any attacker to enhance the engineering of back-end SQL transactions. When an attacker is capable of modify an SQL declaration, typically the declaration will probably carryout with the identical rights as the program end user; while using the SQL server to execute instructions which interact with the operating-system, the process definitely will work with the same permissions for the reason that element that carried out the command (e. g., database server, application server, or Web server), which happens to be quite often extremely privileged.

Forms of vulnerability

The Attacking vector splits in four main sub-classes, considering the technical aspects of the attack’s deployment, as follows:
  • Classic SQLIA 
  • Inference SQL Injection
  • DBMS specific SQLIA
  • Compounded SQLIA
Some security researches propose that, Classic SQLIA is outdated, though there are many Web Applications, which are still not hardened against these simple implementations of SQL Injection.

Inference SQLIA is still a threat, because of its dynamic and flexible deployment as an attacking scenario.

The DBMS specific SQLIA should be considered as supportive no matter there is an attempt of utilization of Classic or Inference SQLIA.

Compounded SQLIA is a new term derived from the research on SQL Injection Attacking Vector in combination with other different Web Application attacks as:
  • SQL Injection + Insufficient authentication
  • SQL Injection + DDos attacks
  • SQL Injection + DNS Hijacking
  • SQL Injection + XSS

Incorrectly filtered escape characters

This form of SQL injection occurs when user input is not filtered for escape characters and is then passed into an SQL statement. This results in the potential manipulation of the statements performed on the database by the end-user of the application.

The following line of code illustrates this vulnerability

statement = "SELECT * FROM `users` WHERE `name` = '" + userName + "';"

This SQL code is designed to pull up the records of the specified username from its table of users. However, if the “userName” variable is crafted in a specific way by a malicious user, the SQL statement may do more than the code author intended. For example, setting the “userName” variable as

' or '1'='1 

Or using comments to even block the rest of the query (there are three types of SQL comments):

' or '1'='1' -- '' or '1'='1' ({ '' or '1'='1' /* ' 

renders one of the following SQL statements by the parent language:

SELECT * FROM `users` WHERE `name` = '' OR '1'='1'; 
SELECT * FROM `users` WHERE `name` = '' OR '1'='1' -- ';

If this code were to be used in an authentication procedure then this example could be used to force the selection of a valid username because the evaluation of ‘1’=’1′ is always true.

The following value of “userName” in the statement below would cause the deletion of the “users” table as well as the selection of all data from the “userinfo” table (in essence revealing the information of every user), using an API that allows multiple statements:

a';DROP TABLE `users`; SELECT * FROM `userinfo` WHERE 't' = 't 

This input renders the final SQL statement as follows:

SELECT * FROM `users` WHERE `name` = 'a';DROP TABLE `users`; SELECT * FROM `userinfo` WHERE 't' = 't'; 

While most SQL server implementations allow multiple statements to be executed with one call in this way, some SQL APIs such as PHP‘s mysql_query(); function do not allow this for security reasons. This prevents attackers from injecting entirely separate queries, but doesn’t stop them from modifying queries.

Incorrect type handling

This form of SQL injection occurs when a user supplied field is not strongly typed or is not checked for type constraints. This could take place when a numeric field is to be used in a SQL statement, but the programmer makes no checks to validate that the user supplied input is numeric. For example:
statement := "SELECT * FROM `userinfo` WHERE `id` = " + a_variable + ";"

It is clear from this statement that the author intended a_variable to be a number correlating to the “id” field. However, if it is in fact a string then the end-user may manipulate the statement as they choose, thereby bypassing the need for escape characters. For example, setting a_variable to

1;DROP TABLE `users` 

will drop (delete) the “users” table from the database, since the SQL would be rendered as follows:

SELECT * FROM `userinfo` WHERE `id`=1;DROP TABLE `users`; 

Blind SQL injection


Blind SQL Injection is used when a web application is vulnerable to an SQL injection but the results of the injection are not visible to the attacker. The page with the vulnerability may not be one that displays data but will display differently depending on the results of a logical statement injected into the legitimate SQL statement called for that page. This type of attack can become time-intensive because a new statement must be crafted for each bit recovered. There are several tools that can automate these attacks once the location of the vulnerability and the target information has been established.

Conditional responses


One type of blind SQL injection forces the database to evaluate a logical statement on an ordinary application screen.

SELECT `booktitle` FROM `booklist` WHERE `bookId` = 'OOk14cd' AND '1'='1';

will result in a normal page while

SELECT `booktitle` FROM `booklist` WHERE `bookId` = 'OOk14cd' AND '1'='2'; 

will likely give a different result if the page is vulnerable to a SQL injection. An injection like this may suggest to the attacker that a blind SQL injection is possible, leaving the attacker to devise statements that evaluate to true or false depending on the contents of another column or table outside of the SELECT statement’s column list.

SELECT 1/0 FROM `users` WHERE `username`='ooo'; 

How to Stop SQL Injection


Parameterized statementsWith most development platforms, parameterized statements can be used that work with parameters (sometimes called placeholders or bind variables) instead of embedding user input in the statement. In many cases, the SQL statement is fixed, and each parameter is a scalar, not a table. The user input is then assigned (bound) to a parameter. This is an example using Java and the JDBC API:

java.sql.PreparedStatement prep = connection.prepareStatement( 
 "SELECT * FROM `users` WHERE USERNAME = ? AND PASSWORD = ?");
prep.setString(1, username);
prep.setString(2, password);
prep.executeQuery();

Enforcement at the Database Level

The H2 Database Engine supports the ability to enforce query parameterization.  However, one drawback is that query by example may not be possible or practical because it is difficult to implement query by example using parameterized queries.

Enforcement at the Coding Level

Using object-relational mapping libraries avoids the need to write SQL code. The ORM library in effect will generate parameterized SQL statements from object-oriented code.

Escaping

A straightforward, though error-prone, way to gsprevent injections is to escape characters that have a special meaning in SQL. This technique is called HTML sanitization The manual for an SQL DBMS explains which characters have a special meaning, which allows creating a comprehensive blacklist of characters that need translation. For instance, every occurrence of a single quote (') in a parameter must be replaced by two single quotes ('') to form a valid SQL string literal. For example, in PHP it is usual to escape parameters using the function mysql_real_escape_string(); before sending the SQL query:

$query = sprintf("SELECT * FROM `Users` WHERE UserName='%s' AND Password='%s'", mysql_real_escape_string($Username), mysql_real_escape_string($Password));mysql_query($query); 

Routinely passing escaped strings to SQL is error prone because it is easy to forget to escape a given string. Creating a transparent layer to secure the input can reduce this error-proneness, if not entirely eliminate it.

Conducting the Forensic Analysis of  a SQL Injection Attack


I read several blogs, white papers and articles on this subject and they all come to the same conclusion that the best way to start the analysis is through viewing the database cache.  So the question becomes how do you get to that data?  There are probably several ways but based on my research there is a tool they can assist you in this called “Hypnosis.”  

An SQL Server maintains several database caches that record previously executed statements.  These caches can contain evidence of successfully executed database attacks including those launched from SQL injection attack tools, worms or even by interactively logged on users.  Hypnosis is the first cache-based incident response utility that interrogates the “always-on” caching feature of SQL Server to help confirm or discount a successful database attack.

According to the website; Hypnosis uses a RegEX based rule file named “CacheRules.txt” which can be populated with attack signatures for use during cache interrogation.  The default CacheRules file contains attack signatures for Pangolin a widely used SQL injection tool within the industry.  The CacheRules file can be extended to include signatures from any other tools or generic attacks for use during interrogation.  The file extension format is captured in the header of the CacheRules file. Hypnosis can also be used to add ad-hoc signatures that match generated IDS\IPS\WAF devices for verification if an attack was successfully tunneled to and executed by the database server.

I am sure there are other ways to conduct the analysis of this type of attack as I am not an expert in databases.  I would love to hear comments on other ways to approach this.




 
Advertisements

2 thoughts on “What is an SQL Injection Attack?

  1. Hi Mark

    Great article.

    As a Sysadmin, I sometimes rebuild websites that have been compromised and then have to patch things up so they don’t get compromised again.
    I am amazed how many sites are put together ( by people claiming to be developers ) with no thought for sanitizing user input.

    My suggestion to anyone who is concerned that they may be vulnerable to SQL injection attacks, is that once the site is considered to be secure enough to go live, run an automated tool to attempt to compromise the site.
    If it is successful it is likely to completely wreck the site but it is better to find the exploits than to wait for the bad guy to find them.

    I use the free tools at http://labs.securitycompass.com/exploit-me/ ( I am not affiliated with them ). Passing these tests doesn’t necessarily mean the site is secure but failing the tests sure means it isn’t.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s