Tuesday, 29 April 2014

SQL Injection Prevention & Detection Techniques


  • Database Design Best Practices
  • Defensive Coding Best Practices
  • Penetration Testing
  • Static Analysis of Code
  • Safe Development Libraries
  • Proxy Filters

  • Anomaly Based Intrusion Detection
  • Instruction Set Randomization
  • Dynamic Tainting
  • Model-based Checkers

Wednesday, 23 April 2014

Types of SQL Injection Attacks

1.Tautologies
2.Union Query
3.Piggy-backed Queries
4.Inference
5.Illegal/Logically Incorrect Queries
6.Stored Procedures

7.Alternate Encodings

Type: Tautologies
This type of attack injects SQL tokens to the conditional query statement to be evaluated always true
Example:-
"SELECT * FROM employee WHERE userid =  '112' and password ='aaa' OR '1 '='1”

As the tautology statement (1=1) has been added to the query statement so it is always true

Type: Union Queries
The result of Union Query injection attacks will be a new dataset returned by the database, containing the union of the first (developer intended) and the second (attacker-intended)

Example:-
"SELECT Name, Phone FROM Users WHERE Id= 1 UNION ALL SELECT creditCardNumber, 1 FROM Credit CardTable”

This will join the result of the original query with all the credit card

Type: Piggy-backed Queries
In this attack type, an attacker tries to inject additional queries into the original query.
In this case, attackers are not trying to modify the original intended query; instead, they are trying to include new and distinct queries that “piggy-back” on the original query.

Example:-
SELECT accounts FROM users WHERE login=‘doe’ AND pass=“0; DROP database webApp

Type: Inference
By this type of attack, intruders change the behavior of a database or application

Blind 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.
Information is inferred from the behavior of the page by asking the server true/-false questions. If the injected statement evaluates to true, the site continues to function normally. If the statement valuates to false, although there is no descriptive error message, the page differs significantly from the normally-functioning page.

Timing attacks:- This type of blind SQL injection relies on the database pausing for a specified amount of time, then returning the results, indicating successful SQL query executing.
A timing attack allows an attacker to gain information from a database by observing timing delays in the response of the database. Attackers structure their injected query in the form of an if/then statement, whose branch predicate corresponds to an unknown about the contents of the database. Along one of the branches, the attacker uses a SQL construct that pause the execution for a known amount of time (e.g. the WAITFOR keyword). By measuring the response time of the database, the attacker can infer which branch was taken in his injection and therefore the answer to the injected question

Type: Illegal/Logically Incorrect Queries
This type is used to trigger syntax errors (which would be used to identify injectable parameters), type conversion errors (to deduce the data types of certain columns or extract data from them) or logical errors (which often reveal names of the tables and columns that caused the error), in order for the attacker to gather information about the type and structure of the back end database of a given Web application.
Example:-
" SELECT accounts FROM users WHERE login= AND pass=‘’ AND pin= convert (int,(select top 1 name from sysobjects where xtype=u))”

Type: Stored Procedure
This type of attack using stored procedures
Example:-
" CREATE PROCEDURE DBO.isAuthenticated
@userName varchar2, @pass varchar2, @pin int AS
EXEC("SELECT accounts FROM users WHERE login= ' “ +@userName+ “ ‘and pass=’ “+@password+” ‘and pin=”+@pin);  GO

SELECT accounts FROM users WHERE login='doe' AND pass = ' '; SHUTDOWN; -- AND pin=

Type: Alternate Encodings
This attack type is used in conjunction with other attacks. In other words, alternate encodings do not provide any unique way to attack an application; they are simply an enabling technique that allows attackers to evade detection and prevention techniques and exploit vulnerabilities that might not otherwise be exploitable

SELECT * FROM userTable WHERE” +  “login=‘” + login + “' AND pin=” + pin;

Input pin as “0; declare @a char(20)  select  @a=0x73687574646f776e exec(@a)”

SELECT * FROM userTable WHERE login=‘user' AND pin= 0;declare @a char(20) select @a=0x73687574646f776e exec(@a)”


SQL Query Injection

What is SQL Injection?
The ability to inject SQL commands into the database engine through an existing application (i.e. Client supplied data passed to an application without appropriate validation) Processed as commands by the database


       Ho w does SQL Injection work?
       Common vulnerable login query

 SELECT * FROM users     WHERE login = 'victor'     AND password = '123'
        (If it returns something then login!)

       ASP/MS SQL Server login syntax
the codes for implementing the same.

Var sql = "SELECT * FROM users
WHERE  login = '" + formusr "' 
 
AND password = '" + formpwd + "'"; 
formusr ' or 1=1 – –
formpwd = anything


 Final query would look like this:
SELECT * FROM users WHERE username' or 1=1– – AND password = 'anything'

Intents
Attacks can also be characterized based on the goal, or intent, of the attacker. Therefore, each of the attack type definitions that we provide in Section 4 includes a list of one or more of the attack intents defined in this section.
1) Identifying injectable parameters: The attacker wants to probe a Web application to discover which parameters and user-input fields are vulnerable to SQLIA.
2) Performing database finger-printing: The attacker wants to discover the type and version of database that a Web application is using. Certain types of databases respond differently to different queries and attacks, and this information can be used to “fingerprint” the database. Knowing the type and version of the database used by a Web application allows an attacker to craft database specific attacks.
3) Determining database schema: To correctly extract data from a database, the attacker often needs to know database schema information, such as table names, column names, and column data types. Attacks with this intent are created to collect or infer this kind of information.
4) Extracting data: These types of attacks employ techniques that will extract data values from the database. Depending on the type of the Web application, this information could be sensitive and highly desirable to the attacker. Attacks with this intent are the most common type of SQLIA.
5) Adding or modifying data: The goal of these attacks is to add or change information in a database.
6) Performing denial of service: These attacks are performed to shut down the database of a Web application, thus denying service to other users. Attacks involving locking or dropping database tables also fall under this category.
7) Evading detection: This category refers to certain attack techniques that are employed to avoid auditing and detection by system protection mechanisms.
8) Bypassing authentication: The goal of these types of attacks is to allow the attacker to bypass database and application authentication mechanisms. Bypassing such mechanisms could allow the attacker to assume the rights and privileges associated with another application user.
9) Executing remote commands: These types of attacks attempt to execute arbitrary commands on the database. These commands can be stored procedures or functions available to database users.
10) Performing privilege escalation: These attacks take advantage of implementation errors or logical flaws in the database in order to escalate the privileges of the attacker. As opposed to bypassing authentication attacks, these attacks focus on exploiting the database user privileges.

       Sources of SQL Injection
       1)Injection through user input: In this case, attackers inject SQL commands by providing suitably crafted user input. A Web application can read user input in several ways based on the environment in which the application is deployed. In most SQLIAs that target Web applications, user input typically comes from form submissions that are sent to the Web application via HTTP GET or POST requests [14]. Web  applications are generally able to access the user input contained in these requests as they would access any other variable in the environment.
      2)Injection through cookies: Cookies are files that contain state information generated byWeb applications and stored on the client machine. When a client returns to a Web application, cookies can be used to restore the client’s state information. Since the client has control over the storage of the cookie, a  malicious client could tamper with the cookie’s contents. If a Web application uses the cookie’s contents to build SQL queries, an attacker could easily submit an attack by embedding it in the cookie [8].
      3)Injection through server variables: Server variables are a collection of variables that contain HTTP, network headers, and environmental variables. Web applications use these server variables in a variety of ways, such as logging usage statistics and identifying browsing trends. If these variables are logged to a database without sanitization, this could create an SQL injection vulnerability [30]. Because attackers can forge the values that are placed in HTTP and network headers, they can exploit this vulnerability by placing an SQLIA directly into the headers. When the query to log the server variable is issued to the database, the attack in the forged header is then triggered.
       4)Second-order injection: In second-order injections, attackers seed malicious inputs into a system or database to indirectly trigger an SQLIA when that input is used at a later time. The objective of this kind of attack differs significantly from a regular (i.e., firstorder) injection attack. Second-order injections are not trying to cause the attack to occur when the malicious input initially reaches the database. Instead, attackers rely on knowledge of where the input will be subsequently used and craft their attack so that it occurs during that usage. To clarify, we present a classic example of a second order injection attack (taken from [1]). In the example, a user registers on a website using a seeded user name, such as “admin’ -- ”. The application properly escapes the single quote in the input before storing it in the database, preventing its potentially malicious effect. At this point, the user modifies his or her password, an operation that typically involves (1) checking that the user knows the current password and (2) changing the password if the check is successful. To do this, the Web application might construct an SQL command as follows:

 queryString="UPDATE users SET password=" + newPassword +"’ WHERE userName=’" + userName + "’ AND password=’" + oldPassword + "

        newPassword and oldPassword are the new and old passwords, respectively, and userName is the name of the user currently logged-in (i.e., ‘‘admin’--’’). Therefore, the query string that is sent to the database is (assume that newPassword and oldPas-sword are “newpwd” and“oldpwd”):
         UPDATE users SET password=’newpwd
         WHERE userName=admin--’ AND password=’oldpwd’

         Because “--” is the SQL comment operator, everything after it is ignored by the database. Therefore, the result  of this query is that the database changes the password of the administrator (“admin”) to an attacker-specified value.
       Second-order injections can be especially difficult to detect and prevent because the point of injection is different from the point where the attack actually manifests itself. A developer may properly escape, type-check, and filter input that comes from the user and assume it is safe. Later on, when that data is used in a different context, or to build a different type of query, the previously sanitized input may result in an injection attack.