Cyber
RIPHAH INSTITUTE OF SYSTEMS ENGINEERING (RISE)
Attack
SQL INJECTION
__________________________________________________________________________________
Contents
Introduction........................................................................................................... 3
What is SQL Injection?........................................................................................... 4
What are SQL Injection attacks?.........................................................................4
Whats vulnerable?............................................................................................. 4
Whats not vulnerable?....................................................................................... 4
Working of SQL Injection........................................................................................ 5
Common Techniques of SQL Injection....................................................................5
Technique1......................................................................................................... 5
Technique 2........................................................................................................ 6
Technique 3........................................................................................................ 7
Technique 4........................................................................................................ 9
Types of SQL Injection attacks............................................................................. 10
First Order attacks............................................................................................ 10
Second Order attacks....................................................................................... 10
Methods of SQL Injection..................................................................................... 12
Normal SQL Injection........................................................................................ 12
Blind SQL Injection............................................................................................ 12
Categories of SQL Injection Attacks.....................................................................14
SQL Manipulation.............................................................................................. 14
Code Injection................................................................................................... 15
Function Call Injection...................................................................................... 16
Buffer Overflows............................................................................................... 18
Detection Of Vulnerability.................................................................................... 19
Preventing SQL Injection Attacks.........................................................................21
2. Function Security.................................................................................... 22
Case Studies........................................................................................................ 26
Case study 1: Barracuda Networks Breached (ACUNETIX, 2011).....................26
Method that used to SQL injection was Blind SQL Injection...........................26
Damage Suffered........................................................................................... 26
Case Study 2: SQL injection vulnerabilities of .bd domain web applications
(Delwar Alam, 2015)......................................................................................... 27
Conclusion........................................................................................................... 28
References........................................................................................................... 29
Bibliography......................................................................................................... 29
__________________________________________________________________________________
1
SQL INJECTION
__________________________________________________________________________________
__________________________________________________________________________________
2
SQL INJECTION
__________________________________________________________________________________
Introduction
The World Wide Web has experienced remarkable growth in recent years.
Businesses, individuals, and governments have found that web applications can
offer effective, efficient and reliable solutions to the challenges of
communicating and conducting commerce in the Twenty-first century. However,
the security of Web applications has become increasingly important in the last
decade. With more and more Web-based applications deal with sensitive
financial and medical data, it is crucial to protect these applications from hacker
attacks. A security assessment by the Application Defense Center, which
included more than 250 Web applications from e-commerce, online banking,
enterprise collaboration, and supply chain management sites, concluded that
that at least 92% of Web applications are vulnerable to some form of attack
(Shelly Rohilla, 2013).
Shell injection.
File inclusion.
XML injection.
SQL Injection
XPath injection.
LDAP injection.
SMTP injection.
__________________________________________________________________________________
3
SQL INJECTION
__________________________________________________________________________________
When attacker enters the data into the form, that data is directly used to build a
dynamic SQL query to retrieve the data from database. Such malicious code
injection is called as an SQL Injection attack.
1. Form Injection.
2. URL Injection.
Whats vulnerable?
A web application is vulnerable to SQL injection for only one reason end user
string input is not properly validated and is passed to a dynamic SQL statement.
The string input is usually passed directly to the SQL statement. However, the
user input may be stored in the database and later passed to a dynamic SQL
statement. Because of the stateless nature of many web applications, it is
common to write data to the database between web pages. This indirect type of
__________________________________________________________________________________
4
SQL INJECTION
__________________________________________________________________________________
SQL Statements using bind variables are generally immune to SQL Injection
attacks as the Oracle database will use the value of the bind variable exclusively
and not interpret the contents of the variable in any way. SQL and Java DB
connectivity allow for bind variables. Bind variables should be extensively used
for both security and performance reasons.
__________________________________________________________________________________
5
SQL INJECTION
__________________________________________________________________________________
Technique1
Consider the login form which accepts the username and password from the
user.
The values supplied in the field Username and Password are directly used to
build the SQL Query like:
__________________________________________________________________________________
6
SQL INJECTION
__________________________________________________________________________________
This will work with no problem. But suppose the user supplied some poorly
devised string of code then that will allow the attacker to by-pass the
authentication and access the information from the database. i.e. if user supplied
username= OR 1=1then the query will be passed as:
It Works as follows:
OR : Continues the SQL query so that the process should equal to what
come before OR what come after.
The data we're filling is used the WHERE clause. And because the application is
not really thinking about the query - merely constructing a string - our use of OR
has turned a single-component WHERE clause into a two-component one, and
the 1=1 clause is guaranteed to be true no matter what the first clause is. The
query means that Select everything from the table customers if the name
equals nothing Or 1=1. Ignore anything that follows on this line.
Seeing as 1 will always equal 1, the server has received a true statement and is
fooled into allowing an attacker more access than they should have. The code
that refers to the password input field is never run by the server and therefore
does not apply.
Technique 2
__________________________________________________________________________________
7
SQL INJECTION
__________________________________________________________________________________
When the user clicks on the submit button to start the login process, the SQL
query causes ASP to spit the following error to the browser:
This error message now tells the unauthorized user the name of one field from
the database that application is trying to validate the login credentials against:
users. username. Using the name of this field, attacker can now use SQL Server's
LIKE clause to login with the following credentials:
The query grabs the userName field of the first row whose userName field starts
with a.
Technique 3
To create a new user record, the attacker must have the information about the
table name and column names it that table. For that the user might use the
following technique. First the user supply an input at username field like:
__________________________________________________________________________________
8
SQL INJECTION
__________________________________________________________________________________
So the attacker now knows the table name and column name of the first column
in the query. They can continue through the columns by introducing each field
into a 'group by' clause, as follows:
So the attacker now knows that the query is referencing only the 'users' table,
and is using the columns 'id, username, password, privs', in that order.
It would be useful if he could determine the types of each column. This can be
achieved using a 'type conversion' error message, like this:
__________________________________________________________________________________
9
SQL INJECTION
__________________________________________________________________________________
This takes advantage of the fact that SQL server attempts to apply the 'sum'
clause before determining whether the number of fields in the two row sets is
equal. Attempting to calculate the 'sum' of a textual field results in this message:
Which tells us that the 'username' field has type 'varchar'. If, on the other hand,
we attempt to calculate the sum () of a numeric type, we get an error message
telling us that the number of fields in the two row sets don't match:
We can use this technique to approximately determine the type of any column of
any table in the database.
This allows the attacker to create a well - formed 'insert' query, like this:
Username: '; insert into users values (666, 'attacker', 'foobar', 0xffff )--
Technique 4
Dropping a table from database.
Several databases use semicolon (;) to delimit a query. The use of a semi-colon
allows multiple queries to be submitted as one batch and executed sequentially.
The attacker might use this to inject the database. For example,
Then the query would execute in two parts. Firstly, it would select the userName
field for all rows in the users table. Secondly, it would delete the users table, so
that when we went to login next time, we would see the following error:
__________________________________________________________________________________
10
SQL INJECTION
__________________________________________________________________________________
__________________________________________________________________________________
11
SQL INJECTION
__________________________________________________________________________________
First order attacks are those attacks when the attacker receives the desired
result immediately, either by direct response from the application they are
interacting with or through some other response mechanism, such as E-mail.
For example, suppose a form ask the email id of the user. If the user provided the
correct email id with no extra code then the query will run properly. But suppose
if the user enter a LIKE clause with the email id then the database will return
the matching criteria to the user immediately.
FROM members
Here, the database will return information of any user where the name starts
with Bob. As, the attacker is getting the result immediately, this type of attacks
are called first order attacks.
A Second order attack can be classified as the process in which the malicious
code is injected into a web-based application and not immediately executed, but
is stored by application (e.g. temporarily cached, logged, stored in database) and
then later retrieved, rendered or executed by the victim. (Ollmann.)
This type of attacks often occurs because once data is in the database; it is often
thought of as being clean and is not checked again. However, the data is
frequently used in queries where it can still cause harm.
__________________________________________________________________________________
12
SQL INJECTION
__________________________________________________________________________________
Consider an application that permits the users to set up some favourite search
criteria. When the user defines the search parameters, the application escapes
out all the apostrophes so that a first-order attack cannot occur when the data
for the favourite is inserted into the database. However, when the user comes to
perform the search, the data is taken from the database and used to form a
second query which then performs the actual search. It is this second query
which is the victim of the attack.
For example, if the user types the following as the search criteria:
The application takes this input and escapes out apostrophe so that the final SQL
statement might look like this:
Which is entered into the database without problems. However, when the user
selects their favourite search, the data is retrieved to the application, which
forms a new SQL command and executes that.
The second query to the database, when fully expanded, now looks like this:
It will return no results for the expected query, but the company has just lost all
of their orders. These types of attacks are known as second order attacks.
__________________________________________________________________________________
13
SQL INJECTION
__________________________________________________________________________________
By appending a union select statement to the parameter, the attacker can test to
see if he can gain access to the database: For example,
http://example/article.asp?
ID=2+union+all+select+name+from+sysobjects
The SQL server then may return the database error similar to this:
This tells the attacker that he must now guess the correct number of columns for
his SQL statement to work.
Blind SQL injection is identical to normal SQL Injection except that when an
attacker attempts to exploit an application, rather than getting a useful error
message, they get a generic page specified by the developer instead. This
makes exploiting a potential SQL Injection attack more difficult but not
impossible. An attacker can still steal data by asking a series of True and False
questions through SQL statements.
http://example/article.asp?ID=2+and+1=1
http://example/article.asp?ID=2
http://example/article.asp?ID=2+and+1=0
Would then cause the web site to return a friendly error or no page at all. This is
because the SQL statement "and 1=0" is always false.
Once the attacker discovers that a site is susceptible to Blind SQL Injection, he
can exploit this vulnerability more easily, in some cases, than by using normal
SQL Injection.
__________________________________________________________________________________
15
SQL INJECTION
__________________________________________________________________________________
1. SQL Manipulation
2. Code Injection
4. Buffer Overflows
SQL Manipulation
The most common type of SQL Injection attack is SQL manipulation. The attacker
attempts to modify the existing SQL statement by adding elements to the
WHERE clause or extending the SQL statement with set operators like UNION,
INTERSECT, or MINUS. There are other possible variations, but these are the most
significant examples.
The classic SQL manipulation is during the login authentication. A simplistic web
application may check user authentication by executing the following query and
checking to see if any rows were returned
Based on operator precedence, the WHERE clause is true for every row and the
attacker has gained access to the application.
__________________________________________________________________________________
16
SQL INJECTION
__________________________________________________________________________________
The set operator UNION is frequently used in SQL injection attacks. The goal is to
manipulate a SQL statement into returning rows from another table. A web form
may execute the following query to return a list of available products:
UNION
The list returned to the web form will include all the selected products, but also
all the database users in the application.
Code Injection
In PL/SQL and Java, Oracle does not support multiple SQL statements per
database request. Thus, the following common injection attack will not work
against an Oracle database via a PL/SQL or Java application. This statement will
result in an error:
__________________________________________________________________________________
17
SQL INJECTION
__________________________________________________________________________________
However, some programming languages or APIs may allow for multiple SQL
statements to be executed.
PL/SQL and Java applications can dynamically execute anonymous PL/SQL blocks,
which are vulnerable to code injection. The following is an example of a PL/SQL
block executed in a web application
The above example PL/SQL block executes an application stored procedure that
encrypts and saves the users password. An attacker will attempt to manipulate
the PL/SQL block to execute as
Using the standard Oracle functions, an attacker can send information from the
database to a remote computer or execute other attacks from the database
server. Many native Oracle applications leverage database packages which can
__________________________________________________________________________________
18
SQL INJECTION
__________________________________________________________________________________
The issue with function call injection is that any dynamically generated SQL
statement is vulnerable. Even the simplest SQL statements can be effectively
exploited.
The following example demonstrates even the most simple of SQL statements
can be vulnerable. Application developers will sometimes use database functions
instead of native code (e.g., Java) to perform common tasks. There is no direct
equivalent of the TRANSLATE database function in Java, so the programmer
decided to use a SQL statement.
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ','0123456789') FROM
dual;
This SQL statement is not vulnerable to other types of injection attacks, but is
easily manipulated through a function injection attack. The attacker attempts to
manipulate the SQL statement to execute as:
The changed SQL statement will request a page from a web server. The attacker
could manipulate the string and URL to include other functions in order to
retrieve useful information from the database server and send it to the web
server in the URL. Since the Oracle database server is most likely behind a
firewall, it could also be used to attack other servers on the internal network.
__________________________________________________________________________________
19
SQL INJECTION
__________________________________________________________________________________
Executing the above SQL statement, the attacker is able to create new
application users.
Buffer Overflows
tz_offset
to_timestamp_tz
bfilename, from_tz
numtoyminterval
Numtodsinterval.
In addition, most application and web servers do not gracefully handle the loss of
a database connection due to a buffer overflow. Usually, the web process will
hang until the connection to the client is terminated, thus making this a very
effective DOS attack.
__________________________________________________________________________________
20
SQL INJECTION
__________________________________________________________________________________
Detection Of Vulnerability
To detect whether your application is vulnerable to SQL injection attacks, follow the given
steps:
Step 2 : Mouse over the links of the Web site with your cursor while paying attention to
the bottom status bar. You will notice the URLs that the links point to. Try to find a URL with
parameters in it (Ex. http://www.site.com/articleid.asp?id=42). Most SQL injection problems
are present when the file extensions are .asp or .cfm. When trying to test a site for SQL
injection vulnerabilities, look for these files specifically. And if you dont see any URLs in
the status bar, then just click on links, and watch the address bar until you find a URL that has
parameters.
Step 3 : Once a URL with parameters has been found, click the link, and go to that page.
In the address bar, you should now see the URL that was seen in the status bar, one having
parameter values.
Step 4 : Here is where the actual testing for hacker protection takes place. There are 2
methods for testing script for SQL injection. Be sure to test each parameter value one at a
time with both methods.
Method 1: Go to the address bar, click your cursor, and highlight a parameter value (Ex.
Highlight the word value in name=value), and replace it with a single quote ().
Method 2: Go to the address bar, click your cursor, and put a single quote () in the middle of
the value. It should now look like name=value
Step 5 : Click the GO button to send your request to the Web Server.
Step 6 : Analyse the response from the Web server for any error messages. Most database
error messages will look similar like:
__________________________________________________________________________________
21
SQL INJECTION
__________________________________________________________________________________
Example Error 1: Microsoft OLE DB Provider for SQL Server error '80040e14'Unclosed
quotation mark before the character string '51 ORDER BY
some_name'./some_directory/some_file.asp, line 5
Step 7 : Sometimes the error message is not obvious and is hidden in the source of the
page. To look for it, you must view the HTML source of the page and search for the error. To
do this in Internet Explorer, click the View menu, and select the Sourceoption. This will
cause Notepad to open with the HTML source of the page. In Notepad, click the Edit menu,
and select Find. A dialog box will appear that will ask you to 'Find What. Type the phrase
Microsoft OLEDB (ODBC), in the text box and then click Find Next.
__________________________________________________________________________________
22
SQL INJECTION
__________________________________________________________________________________
SQL Injection attacks can be easily defeated with simple programming changes,
however, developers must be disciplined enough to apply the following methods
to every web accessible procedure and function. Every dynamic SQL statement
must be protected. A single unprotected SQL statement can result in comprising
of the application, data or database server.
Following are some techniques that can be used to prevent SQL Injection attacks:
The most powerful protection against SQL injection attacks is the use of bind
variables. Using bind variables will also improve application performance.
Application coding standards should require the use of bind variables in all SQL
statements. No SQL statement should be created by concatenating together
strings and passed parameters.
Bind variables should be used for every SQL statement regardless of when or
where the SQL statement is executed. This is Oracles internal coding standard
and should also be your organizations standard. A very complex SQL injection
attack could possibly exploit an application by storing an attack string in the
database, which would be later executed by a dynamic SQL statement.
__________________________________________________________________________________
23
SQL INJECTION
__________________________________________________________________________________
Many web applications use hidden fields and other techniques, which also must
be validated. If a bind variable is not being used, special database characters
must be removed or escaped.
For Oracle databases, the only character at issue is a single quote. The simplest
method is to escape all single quotes Oracle interprets consecutive single
quotes as a literal single quote.
The use of bind variables and escaping of single quotes should not be done for
the same string. A bind variable will store the exact input string in the database
and escaping any single quotes will result in double quotes being stored in the
database.
2. Function Security
All functions that are not absolutely necessary to the application should be restricted.
Try to limit the open-ended input wherever possible, by using select boxes
instead of Text boxes. Application must apply client side validation for all inputs.
For validation only the option in the select box should be taken up and any other
option should be rejected.
Verify the data type using ISNUMERIC or equivalent function before passing it
into a SQL statement. For string data replace single quotes with two single
quotes using the replace function or equivalent.
__________________________________________________________________________________
24
SQL INJECTION
__________________________________________________________________________________
Use stored procedures avoid direct access to the table. Stored procedures that
are not being used may be deleted such as: master_xp_cmdshell, xp_sendmail,
xp_startmail, sp_makewebtask.
6. Never build dynamic SQL statement directly from the user input and never
concatenate user input, with SQL statements, which is not validated.
7. Filter out characters like slash, backslash, extended characters like NULL,
carry return, new line in all strings from user input and parameters from URL.
8. Privileges of the user account used in the application for executing SQL
statements on the database must be defined.
Charact
Meaning
er
Query Delimiter.
;
1. How to get data from the database using ODBC error message?
We can use information from error message produced by the MS SQL Server to
get almost any data we want. Take the following page for example :
http://duck/index.asp?id=10
We will try to UNION the integer '10' with another string from the database:
http://duck/index.asp?id=10
__________________________________________________________________________________
25
SQL INJECTION
__________________________________________________________________________________
This should return the first table name in the database. When we UNION this
string value to an integer 10, MS SQL Server will try to convert a string
(nvarchar) to an integer. This will produce an error, since we cannot convert
nvarchar to int. The server will display the following error:
The error message is nice enough to tell us the value that cannot be converted
into an integer. In this case, we have obtained the first table name in the
database, which is table1".
To get the next table name, we can use the following query:
http://duck/index.asp?id=10 UNION
Output:
__________________________________________________________________________________
26
SQL INJECTION
__________________________________________________________________________________
Now that we have the first column name, we can use NOT IN () to get the next
column name:
Output:
Now that we have identified some important tables, and their column, we can
use the same technique to gather any information we want from the database.
Now, let's get the first login_name from the "admin_login" table:
http://duck/index.asp?id=10
Output:
We now know there is an admin user with the login name of "neo". Finally, to get
the password of "neo" from the database:
http://duck/index.asp?id=10
Output:
__________________________________________________________________________________
27
SQL INJECTION
__________________________________________________________________________________
__________________________________________________________________________________
28
SQL INJECTION
__________________________________________________________________________________
Case Studies
On April 11th 2011, at nine in the evening, Barracuda Networks posted on their
blog that their network had been hacked. Thousands of their confidential
customer and employee records were stolen. In an ironic twist of fate, the
company that advocates security through its own Web Application Firewall were
victims to the most common and oldest type of attack against web servers the
infamous Blind SQL Injection.
Web Application Firewalls like the one that Barracuda Networks manufactures are
designed to stop this type of attack from occurring in the first place, however
they clearly are not the silver bullet against hackers. On their blog, Barracuda
Networks admitted that they made several mistakes, the biggest of which was to
unintentionally turn off their own firewall for a few hours. This was a golden
window of opportunity which hackers pounced on and immediately exploited.
Damage Suffered
The passwords were extracted from the main MySQL database itself and contain
users who have system-level privileges some which were tied down to particular
__________________________________________________________________________________
29
SQL INJECTION
__________________________________________________________________________________
servers and some which grant access to all servers on the network. This
database contains 23 users.
The users were extracted from another database and contain user names,
passwords and email addresses of Barracuda employees, possibly those who had
access to the web help-desk system.
The .bd domain have 600 web applications. Among them 400 web applications
are found and 60 web applications are vulnerable to SQL injection. The data that
they could retrieved from these testing include: user name password, bank
account number, database super admin login, ATM booth pin number, users
address, phone number and many other sensitive information.
340 web applications of the dataset are vulnerable to various query splitting
techniques of get based SQL injection. 65% of the websites are vulnerable to
single quote () splitting. And other 10% and 15% could be exploited by double
quote () and single quote single bracket.
In the data-set we have found 60 web applications vulnerable to post based SQL
injection. In the post based dataset the onlt splitting vulnerabilities found are
single quote and double quote. One key reason for web application vulnerability
is the language and the platform of the development.
__________________________________________________________________________________
30
SQL INJECTION
__________________________________________________________________________________
Conclusion
Remember always patch and update holes because exploits are found commonly
and the attacker is not going to wait.
__________________________________________________________________________________
31
SQL INJECTION
__________________________________________________________________________________
References
ACUNETIX. (2011, 5 5). Barracuda Networks Victims of SQL Injection. Retrieved
from ACUNETIX: http://www.acunetix.com/blog/news/barracuda-networks-
breached/
Delwar Alam, T. F. (2015). Exploring the SQL injection vulnerabilities of .bd
domain web applications. 2015 Fourth International Conference on Cyber
Security, Cyber Warfare and Digital Forensic (CyberSec) (2015), 73-77.
Ollmann., G. (n.d.). Second Order Code Injection Attacks. Retrieved from Next
Generation Security Software Ltd.:
http://www.nextgenss.com/papers/SecondOrderCodeInjection.pdf
Santamarta, R. (2016, december 20). INSIGHTS, NEWS & DISCOVERIES.
Retrieved from IOActive: http://blog.ioactive.com/2016/12/in-flight-
hacking-system.html
Shelly Rohilla, P. K. (2013). Database Security by Preventing SQL Injection
Attacks in Stored Procedures . International Journal of Advanced Research
in Computer Science and Software Engineering , 915.
Bibliography
http://ece.wpi.edu/~dchasaki/Exercise_2.html
https://www.securesolutions.no/why-its-easy-being-a-hacker/
http://blog.ioactive.com/2016/12/in-flight-hacking-system.html
https://en.wikipedia.org/wiki/SQL_injection
http://www.acunetix.com/websitesecurity/sql-injection/
https://www.owasp.org/index.php/SQL_Injection
http://www.unixwiz.net/techtips/sql-injection.html
http://searchsoftwarequality.techtarget.com/definition/SQL-
injection
https://www.netsparker.com/web-vulnerability-
scanner/vulnerability-security-checks-index/sql-injection/
http://www.programmerinterview.com/index.php/database-
sql/sql-injection-example/
__________________________________________________________________________________
32
SQL INJECTION
__________________________________________________________________________________
__________________________________________________________________________________
33