Upcoming SlideShare
Loading in...5







Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

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

Sql Sql Document Transcript

  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 SQLI Prevent Parser for the prevention of SQL Injection Attacks. This Parser Framework of SQL Injection Attack determines the structure of queries and compares whether the queries are Neha Patwari1, Parvati Bhurani 2 functionally equivalent or not. This parser has been used on a sample webAbstract application and the results have come out to be positive majors to prevent SQLWith the changing demographics of Injection Attacks.globalization, the emergence andprevalence of web application have I Introductionacquired a central and pivotal role in thedomains of technology and There has been a rapid advancement inadvancements. It thus becomes information technology as a result of theimperative to probe deeply into the widespread use of the internet since thearchitecture, significance and different past few years. The common man todayfacets of usages. Web applications uses the internet with a number ofenclose the functioning between a user purposes such as to be used in the fieldand the services provided by the server, of education, for money transactionswhich contains a database as its and other countless activities. Thoughbackend. The user can access the there is also an inherent risk in therequired information through sending a frequent use of the internet as found inrequest in the form of text to the web transferring some money from one bankserver, which is interpreted by the server account to another or in the confidentialside script to construct an SQL. The database of the companies. The securequery is sent to the database which websites stores the highly sensitiveresponds in order to generate an HTML information along with non-critical datapage that is sent back to the user. Since in their database systems in such a waythe functioning of web application is a that the Owner of the information is abledynamic and complicated matter, certain to access it quickly while attackers of thethreats to the database security have unauthorized users are blocked in theirbeen registered. One such alarming attempts to have access to thethreat is the prevalence of SQL Injection information.Attack. Hence a dynamic algorithm isgiven in this paper for preventing SQL Hence we have to understand theInjection Attacks which is based on architecture of web application; a webcontext free grammars and compiler application accepts requests from usersparsing techniques. The paper attempts in order to gather information from ato present the notation of a database. It is assumed by database
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 application and a user in order to have a better understanding of SQL injection.that the input is correct and thus uses itto access the database by creating an II Overview of SQL injectionSQL. These web applications becomevirtually prone to SQL injection attacks A web application is one through whichsince these do not check the validity of a user can access the services providedthe user queries before submitting them by the web server while working on ato gather the data. For example, client machine, which contains aattackers pretending as genuine user database for example an online email id.utilize maliciously created input text The user enters a login name andwhich contains SQL instructions in order password to access the email account.to produce SQL queries on the web As he presses the submit button a URLapplication back-end. In case web is created and is sent to the web server.application processes the query, the The server side of the script interpretsaccepted malicious query may breach the user input due to which a dynamicsecurity net of the underscored SQL query is created. It is submitted todatabase. As a consequence of the the database and HTML pages arequery there occurs an improper generated in response to the queryfunctioning of the database parser which which is sent back to the user. Aresults in the release of the sensitive particular section of the database queryinformation [1]. code is submitted by the maliciousIn order to have access to the sensitive attackers to the server, while respondinginformation from the database a general with the corresponding result somebreak-in strategy is to first create a sensitive information is disclosed by thequery which will corrupt the functioning server. This is categorized as SQLof the database parser, and forward the injection attack. A SQL injection attackapplication of this query to the targeted contains injection of a SQL query to thedatabase. This type of approach in order application through the input data fromto have access to the private information the client. If successful SQL injectionis known as SQL injection. Now SQL can read and modify the data in theinjection has become a common database (Insert/Update/Delete), itoccurrence due to the easy access of means that an SQL injection attackthe database via the internet. It is takes place. When the intended effect ofequally necessary to have a deep an SQL query is modified by an attackerunderstanding of the types of on inserting new SQL keywords ofcommunication which occurs during a operators into the query, following areparticular session in between a web the qualities of SQL injection attacks:
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 the database. i.e., if user inputs username= ’OR 1=1- -then the query willi) Threat Modelling ii) Attack Intent iii) be forwarded as :Assets SELECT * FROM login WHERE nameIII. Working of SQL Injection = ‘ ’OR 1=1–’AND password = ‘ ’;The concept driving a SQL injection is It will work as specified below:simple above all attacks like these can The input data is being used in thebe executed and mastered with ease. WHERE clause. Since the application isTo exploit the SQL injection weakness not actually concerned about the querythe basic requirement for the attacker is simply tailoring a string, user hasto identify the working of the web converted a single-component WHEREapplication. A malicious SQL command clause into a two-component clause,can be inserted carefully into the content and this makes it certain that the 1 = 1of the criteria empowering the attacker clause will be true notwithstanding theto trick the web application so that a fact that what the first clause is. Themalicious query can be forwarded to the query emphasize that "Select everythingdatabase. from the table login if the name equalse.g. the LOGIN FORM which accepts "nothing" Or 1=1, ignores anything afterthe username and password from the the comment.login. The input in the field (“name” and ’ : Is used to close the user input field.“Password”) is directly used to create OR : The SQL query will be continued tothe SQL Query like: get the process as equal to whatSELECT * FROM login WHERE name proceeds before OR what follows.= ‘name’ AND password = ‘password’; 1=1 : A statement which is all time true.Now, let the user input the correct name – : Discards the rest of the lines in order=“Administrator” and Password=“admin”. to stop further processing.The query will become: Noticing that 1 will always equal 1, theSELECT * FROM login WHERE name server has been virtually duped as the= ‘Adminstrator’ AND password = statement received is true and this‘admin’; empowers the attacker to have additional access. The code whichThis will function without any problem. In relates to the password input field is notcase the user supplied some vulnerable run by the server and therefore does notstring of code then that will empower the use it [2].attacker to by-pass the authenticationand create an SQL Injection so that he IV. Types of SQL Injection Attacksfinds out the relevant information from
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 response mechanism for example E- mail.Divergent types of advanced andpowerful techniques have been All type of attacks which is mentioneddeveloped by attackers over the past below, if performed directly in text fieldseveral years which empower attackers and provides important information orto exploit SQL injection vulnerabilities. data, from the response then such typeThese techniques are much advanced of attack is called First Order Attack orthan the generic SQL injection attacks Direct injection.examples and derive the benefits fromsophisticated SQL designs. These In the case of direct injection the SQLthreats must be taken into account while query will use each argument submittedworking on the development of SQL as such without any modification. Forinjection attack problems. example attempt to take parameter’sAn SQL Injection Attacks proneness can legitimate value and appending a spacebe exploited by the attacker once he has along with the word “OR” with it. In casedetected the input source, for this if an error is generated by this, a directpurpose the attacker can utilize various injection is possible.types of techniques. As per the type andextent of the proneness the attack can First order is basically performed bylead to crashing the database, collecting SELECT query which is used inthe relevant information regarding the application for retrieving information.tables in the database. Given below is asynopsis of the main techniques of Tautologies Queriesperforming SQL injection attacks.An isolated attack is not a general Attack Intent: Bypassing authentication,phenomenon instead a combination of retrieving data, identifying inject ableattacks either simultaneously or parameters.sequentially used as per the desired Description: The normal aim of thistarget of the attacker. type of attack is to inject code that may be in one or more conditionalFirst Order Attacks statements due to which the statements are always evaluated as to be true. TheIn some attacks the desired result is results of this type of attack take placeimmediately received by the attacker. due to the way in which the applicationThis may be due to the direct response uses the outcome of the query. Theby the application with which they are most common purpose is to skipinteracting or may be via some other authentication route and extract data. An attacker exploits an injectable area
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 Query (i) given below is generated after entering valid name ‘adminstrator1_ad’and valid passwordunder this type of injection which is ‘admin1_ad’by genuine user.utilized in a query’s WHERE conditional. Query = "select * fromThe transformation of the conditional login_table_llwhereinto a tautology results in returning all name=‘adminstrator1_ad’andthe rows in the database table being password=‘admin1_ad’";————–(i)targeted by the query. For the attack tobe fruitful the code must either display If an attacker writes: ’or 1=1–’in theall of the returned records or must name field (the input entered for theperform some action so that at least one other fields are impertinent) leaving therecord is returned. password field empty, the structure of the SQL query will be changed.Ex: Let there be an input form with the Query (ii) given below is generated withfields “name” and “password”. Using this SQL injection by the attacker.user can login in web application. The Query = “select * fromlogin_table_llgiven below PHP code for the where name=‘’or 1=1 –’andapplication server, created by a web password=‘’——————(ii)application developer has inherent The complete WHERE clause isweakness for SQL injection attack: transformed into a tautology by the code1. $connection=mysql_connect(); injected in the conditional(’OR 1=1–).2. mysql_select_ db(“sample”); The conditional is used by the database3. $user=$HTT_GET_VARS[‘name’]; as the basis in order to evaluate each4. row and to decide which is to be$pass=$HTTP_GET_VARS[‘password’]; returned to the application. As the5. $query="select * from login_table_ll conditional being a tautology, the querywhere name=‘$ u_user1_name ’and evaluation is true for each row in thepassword =‘$p_pass1_name’"; table and so all of them are returned [3].6. $result=mysql_query($query);7.if (mysql_num_rows($result)==1) echo Illegal/Logically Incorrect Queries“Authorized” else echo “authorizationfailed”; Attack Intent: Retrieving data,User data created in the form of a web identifying inject able parameters,are assigned to variables performing database finger-printing.“u_user1’_name’ and “p_pass1_name” Description: This category of attackand then utilized to produce the SQL allows to collect the relevant informationstatement. as per the type and structure of the back-end database of a Web application.
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 A parentheses must be added to the bad value part of the injection, and one to the WHERE clause. In few cases twoThe main aim of this attack is to gather or more parentheses may be required.information for further Here’s the code:attacks and is treated as a preliminary mySQL= " SELECT Last_ name1_l,step. These attacks pinpoint a weakness First_name1_f, Title_ t1_t, Notes_n1_ndue to which the application servers FROMEmployee_ Table1_eWHEREreturns the default error page which City_ name1_c = (‘ “& strCity &” ’) "often contains over description. The When an attacker inserts " ’ " then thevulnerable or inject able parameters can query is built as:be revealed to the attacker due to the "SELECT Last_name1_l, First_name1_f,simple fact that error messages are Title_t1_t, Notes_n1_n FROMbeing generated. Employee_Table1_eWHEREThe additional error information which City_name1_c =(‘ ’ ’)"was fundamentally aimed at assisting Then the error generated is :the programmer to repair or correct their Error Type:application further empowers the Microsoft OLE DB Provider for ODBCattacker to access information related to Driver [Microsoft][SQL Server ]Unclosedthe schema of the back-end database. Parentheses mark before the CharacterDuring working on this type of attack, he String " ’ " From the error generated, thetries to inject statements which can attacker knows that here parentheses isresult in syntax error, type conversion or used.could create logical error into the Hence, attacker tries to inject the value ’)database. The injectable parameters (‘UNION SELECT another field FROMcan be detected by using the syntax another table), thus this query will beerrors. The deduction of the data types forwarded to the server.of certain columns or the seperation of SELECT Last_name1_l, First_name1_f,the data can be done by using the type Title_t1_t, Note_n1_n FROMerrors. The names of the tables and Employee_table1_e WHEREcolumns causing the errors can often be City_name1_c = (‘ ’) (‘UNION SELECTrevealed by logical errors. another field from another Table ’) ;Example: In case the syntax error Through the errors generated, theconsists of a parentheses in the cited attacker gets to know a lot of useful datastring (for example SQL Server through various steps.message used in the illustration given Hence by the use of error messagesbelow) or a message is generated which attacker gets information [4].clearly mentions about missingparentheses. Union Queries
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 Predicting that there is no login1_area equal to “ ”, a null set is returned by theAttack Intent: Bypassing Authentication, first original query, while the data fromextracting data. the “Debit_Card1_d” table is returnedDescription: In such attacks the weaker from the second query. For accountparameters are exploited by the attacker “100” the column “cardNo1_c” would bewith a view to transform the data set returned by the database in this case.returned for a specific query. The result obtained from these queriesThis technique allows the attacker to combines and returns them to theform the application, giving back data application [3].from a table not from the one whichintended by the developer but from Second Order Attacksanother unintended table. In this type of attack when the maliciousThe attacker performs it by introducing a code is injected into the web basedstatement in the way:’ UNION SELECT application instead of being immediately< remaining of injected query >. executed it is stored by the webSince the second/injected query is application i.e. it is first stored in thetotally controlled by the attackers, this database to be retrieved, rendered orquery can used by them in order to executed by the victim. This category ofretrieve information from a particular attack happens because of the notiontable. This attack results in the form of a that when the data is contained in thedataset from the database which is the database, it is often supposed to becollective result of the original query and clean and need not be checked again.the injected query. While due to the frequent use of theExample: Referring to the running data in the queries, it is still able harmexample, an attacker could introduce the the web application. This type of attacktext " ’UNION SELECT card_no1_c from happens in case where the filtrationDebit_Card1_d where process is skipped during the process ofaccountNo1_a=100–" into the data insertion in search page. Welogin1_area field, leading to the should apply filtration for specialgeneration of the following query: characters before storing data in databases, which no special charactersSELECT bank_accounts FROM are allowed for inserting in databases. Itusers1 WHERE login1_area = ‘’UNION is inherently performed by INSERTSELECT card_no1_c from basics which are used in application. INSERT keyword is used to addDebit_Card1_d where accountNo1_a information in the database. In case of= 100 – AND pass=‘’; web application this keyword is used for
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 contrast to the other type of attacks instead of modifying the original intended query tries to insert new anduser registrations, bulletin boards distinct query that “piggy-back” on theinclusion, adding items to shopping carts, original query. This results in multipleetc. While trying to INSERT injection it SQL queries to the database. Thecould result in the flooding of the rows in initiating query (intended query) isthe database having single quotes and executed as normal while the remainingSQL keywords. As per the at queries are injected queries, and beingtentativeness of the administrator it can executed along with the initiating query.be evaluated that what is to be done The attack of this category is highly fatal.with the information. For example the In case an attacker succeeds in thisuser is on a site on which user attack he can virtually insert any sort ofregistration of some kind is allowed. SQL command in the additional queriesA format is provided in which the user and is able to execute them along withhas to enter name, address, phone the initiating query. This kind of attacknumber, etc. As the information is vulnerability is often due to thesubmitted in the format a page is possession of a database configurationgenerated where this information is via which multiple statements can bedisplayed along with an option to edit inserted in a single string.the information. This is what is requiredby the user. Thus after the process of Example: If the attacker inputs “ ’; dropinsertion the required data can be table login ;” into the password field, themodified and updated. Thus in case application generates the query:some malicious data is inserted in the SELECT * FROM login WHEREdatabase by the attacker, the data can name=‘admin’ AND password= ‘ ’;be updated as per the desire of the drop table login ;attacker. As the first query having query delimiter (“;”) is completed the second query isPiggybacked Query attack is example of executed by the database. The effect ofSecond Order Attack [5]. the execution of the second query would be to drop table login which may lead toPiggybacked Queries the destruction of the valuable data [6].Attack Intent: Inserting or updating data, V. Prevention Methodologyperforming denial of service.Description: In this category of attack, The methodology which has been usedattacker tries to inject queries in the to prevent the SQL injection attacks isoriginal query. These kinds of attacks in the merging of SQLIPreventParser with the application therefore protecting
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 WHERE clause into a tautology of code injected in the conditional statement(’against any attacks. Firstly SQLI OR 1=1 –). The conditional used byPrevent Parser has been built which is database to evaluate each row andused to determines the structure of the decide the rows to return to thequery. Then limitations of the method application. Since conditional is aare identified. Finally, the solution to tautology, query evaluates each row inovercome the problems has been the table as true and returns all of themproposed making the system fully to application. The problem is reckonedefficient. by taking into consideration its cause:Approach The detailed information of the program is that the substrings are taken fromThe developer built a data structure for user input and the substrings arethe parsed representation of the restrained syntactically. The concept isstatement, which is called a parser. For to restrict queries in which the inputparsing, we require the grammar substring modifies the syntacticlanguage of statement. In this method, structure of the remaining query. Suchby parsing two statements and queries are called SQL injection attackscomparing their parser functionality, it in the perspective of database back-leads to conclusion that the two queries ends.are equal. When sql is injectedsuccessfully in database query, the The user’s intake is visualized by usingparser of the intended SQL query and meta-character displayed as ‘(|’ and ‘|)’.the resulting SQL query is generated It allegorizes the commencement andafter mismatch of attacker’s input. ending of each input string. This meta character follow the string throughThe SQL Query is: assignments, concatenations, etc., thusSELECT * FROM login WHERE login as a query is ready to be transferred toname=‘ ’ AND password=‘ ’; database, it contains matching pair ofWeb applications have SQL injection markers identifying the substrings fromvulnerabilities because inputs are not input. We should refuse to introducesanitized which they use to construct input substrings from modification of thestructured output. syntactic structure of the remaining of the query. For this grammar for queriesIf an attacker passes name = ’ OR 1=1– as per the standard grammar for SQLas the login name, all login name in the queries is build up. In the grammar, thedatabase will be returned and displayed, only productions in which ‘(|’ and ‘|)’reason being transformation of entire occur have the following form:
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 1. If the attacker is somehow able to detect the delimiter used, it wouldNon terminal ::= ‘(|’ symbol ‘|)’ require only a slight modification ofWhere symbol is either a terminal or the query to break this protection.non-terminal 2. The attacker may simply use a brute force attack to simply try outFor query to be in the language of this all possible combinations (togrammar, the substrings surrounded by guess the correct delimiter‘(|’ and ‘|)’ must be syntactic. A parser combination).generator is used to build a parser forgrammar and each query is attempted to VII. Solutionbe parsed. In case the query is parsedsuccessfully, it meets the syntactic Original solution where we use staticconstraints and is legitimate. Conversely, delimiter upgraded to circumventit fails the syntactic constraints and may potential security leaks. Hencebe a SQL injection attack. implementation by dynamically changing the delimiter combination for everyAfter SQL Prevent Parser is built using variable field and not using the samethe grammar of the output language and delimiter blend for two consecutiveplan of action is specified that permitted variable fields or in same field insyntactic forms, it remains on the web application. As a result of thisserver and intercepts generated queries. modification to the original algorithm, theEach input needs to be propagated in attacker will have to correctly guess theform of some query, notwithstanding the exact sequence of delimiters used toinput’s source, gets amplified with the bypass the parser’s security system.meta-characters ‘(|’ and ’|)’ Then query Since the delimiter blend will be cycledis generated by the application, which randomly this will not be easily possible.SQLIPreventParser attempts to parse. If By this proposed method static delimitera query parses successfully, SQLI has been made dynamic. This solutionPrevent Parser sends it to the database makes the parser more secure thanwithout the meta-character. Otherwise, before.the query is block out. Figure 3.3 shows the basic structure of work where the user input is interpreted VI. Limitation by the web application. In the web application it has been used the conceptThis solution can be overcome in either of dynamic delimiter so that the attackerof two ways: is unable to guess the sequence of the
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 query at the Parser) are functionally equivalent or not. Incase both the queries are functionally equivalent thendelimiter; here even the user has no it reaches the database then response isidea about the sequence of the delimiter. taken from the database, which is generated as an HTML Page and isHence in the given application the send to the user [1].limitation of the static delimiter has beeneliminated. VII. ResultFigure 3.3: Work Architecture. This paper presents the first overview of SQL injection attacks in web application. According to the presented paper an effective technique has been developed for preventing SQL injection attacks. The implementation on web application and parser on java CC [7] proved effective under testing. Here have been diligent efforts in applying parser on web application and produces output. The result of evaluation and test proves that the proposed method is an effective technique to prevent SQL Injection Attacks. In this work it has been managed to prevent SQL injection attacks through:If the user puts any input by using thedelimiter for example x|)’ OR ’(| 1 = 1 , • Tautologies Queriesthen it will be checked at the application • Union Queriesitself and the error is reported here itself. • Illegal/Logically Incorrect QueriesNow from application query is sent to • Piggybacked Queriesthe parser. •SQLIPreventParser has been built for SQL constraintsThe Parser determines the structure of Following are the two goals for futureSQL query and input variable. Parser works:compares that both queries ( means 1. The parser is to be morequery at the application and the generalized for maximum number of SQL commands.
  • Jun. 30 IJASCSE Vol 1 Issue 1 2012 2. The technique can be applied to prevent cross-site scripting.VIII. References[1] Zhendong Su. The essence ofcommand injection attacks in webapplications. pages 372–382. ACMPress, 2006.[2] Chris Anley. Advanced sql injectionin sql server applications. In AnNGSSoftware Insight Security Research(NISR) Publication, 2002. [3] J.ViegasWilliam G.J.Holfond. Aclassification of sql injection attacks andcountermeasures. In IEEE, 2009.[4] SQL Injection, Are Your WebApplications Vulnerable?http://www.securitydocs.com/library/2656/.[5] SQL Injection Attack and Defense.http://www.securitydocs.com/library/3587/.[6] D.K. Bhattacharyya Debasish Das,Utpal Sharma. An appraoch todetectionof sql injection attack based ondynamic query matching. In InternationalJournal of Computer Application(0975-8887) volume 1-No.25,2010., 2010. [7]JAVACFAQ.http://www.engr.mun.ca/~theo/ JavaCC-FAQ/javacc-faq-moz.htm.