SQL Injection January 23, 2013



Similar documents
Webapps Vulnerability Report

SQL Injection. The ability to inject SQL commands into the database engine through an existing application

External Vulnerability Assessment. -Technical Summary- ABC ORGANIZATION

Security Assessment of Waratek AppSecurity for Java. Executive Summary

A SQL Injection : Internal Investigation of Injection, Detection and Prevention of SQL Injection Attacks

Web Application Security

EC-Council CAST CENTER FOR ADVANCED SECURITY TRAINING. CAST 619 Advanced SQLi Attacks and Countermeasures. Make The Difference CAST.

SECURING APACHE : THE BASICS - III

SQL INJECTION ATTACKS By Zelinski Radu, Technical University of Moldova

White Paper. Blindfolded SQL Injection

Practical Identification of SQL Injection Vulnerabilities

Thick Client Application Security

SQL Injection Attack Lab

Web Application Guidelines

SQL Injection. By Artem Kazanstev, ITSO and Alex Beutel, Student

INTRUSION PROTECTION AGAINST SQL INJECTION ATTACKS USING REVERSE PROXY

Testing Web Applications for SQL Injection Sam Shober

The Top Web Application Attacks: Are you vulnerable?

Enhanced Model of SQL Injection Detecting and Prevention

ADO and SQL Server Security

Blindfolded SQL Injection. Written By: Ofer Maor Amichai Shulman

The purpose of this report is to educate our prospective clients about capabilities of Hackers Locked.

ICTN Enterprise Database Security Issues and Solutions

SQL Injection Attack Lab Using Collabtive

Advanced Web Technology 10) XSS, CSRF and SQL Injection 2

Integrated Network Vulnerability Scanning & Penetration Testing SAINTcorporation.com

External Network & Web Application Assessment. For The XXX Group LLC October 2012

SQL injection: Not only AND 1=1. The OWASP Foundation. Bernardo Damele A. G. Penetration Tester Portcullis Computer Security Ltd

Guarding Against SQL Server Attacks: Hacking, cracking, and protection techniques.

1. What is SQL Injection?

Where every interaction matters.

ETHICAL HACKING APPLICATIO WIRELESS110 00NETWORK APPLICATION MOBILE MOBILE0001

Columbia University Web Security Standards and Practices. Objective and Scope

Maintaining Stored Procedures in Database Application

SQL Injection 2.0: Bigger, Badder, Faster and More Dangerous Than Ever. Dana Tamir, Product Marketing Manager, Imperva

Advanced Web Security, Lab

University of Wisconsin Platteville SE411. Senior Seminar. Web System Attacks. Maxwell Friederichs. April 18, 2013

Creating Stronger, Safer, Web Facing Code. JPL IT Security Mary Rivera June 17, 2011

FINAL DoIT v.4 PAYMENT CARD INDUSTRY DATA SECURITY STANDARDS APPLICATION DEVELOPMENT AND MAINTENANCE PROCEDURES

VIDEO intypedia007en LESSON 7: WEB APPLICATION SECURITY - INTRODUCTION TO SQL INJECTION TECHNIQUES. AUTHOR: Chema Alonso

SQL Injection Vulnerabilities in Desktop Applications

Application Security Testing. Erez Metula (CISSP), Founder Application Security Expert

Cross Site Scripting Prevention

Advanced PostgreSQL SQL Injection and Filter Bypass Techniques

Web Applications Security: SQL Injection Attack

Application security testing: Protecting your application and data

WHITE PAPER. FortiWeb and the OWASP Top 10 Mitigating the most dangerous application security threats

SQL INJECTION MONITORING SECURITY VULNERABILITIES IN WEB APPLICATIONS

SQL Injection. Slides thanks to Prof. Shmatikov at UT Austin

How I hacked PacketStorm ( )

Serious Threat. Targets for Attack. Characterization of Attack. SQL Injection 4/9/2010 COMP On August 17, 2009, the United States Justice

Put a Firewall in Your JVM Securing Java Applications!

SQL Injection Attacks: Detection in a Web Application Environment

Agenda. SQL Injection Impact in the Real World Attack Scenario (1) CHAPTER 8 SQL Injection

Passing PCI Compliance How to Address the Application Security Mandates

Check list for web developers

An Introduction to SQL Injection Attacks for Oracle Developers. January 2004 INTEGRIGY. Mission Critical Applications Mission Critical Security

Implementation of Web Application Security Solution using Open Source Gaurav Gupta 1, B. K. Murthy 2, P. N. Barwal 3

Secure Web Application Coding Team Introductory Meeting December 1, :00 2:00PM Bits & Pieces Room, Sansom West Room 306 Agenda

1. Building Testing Environment

Threat Modeling/ Security Testing. Tarun Banga, Adobe 1. Agenda

Security Test s i t ng Eileen Donlon CMSC 737 Spring 2008

CSCI110 Exercise 4: Database - MySQL

Application Design and Development

5 Simple Steps to Secure Database Development

Magento Security and Vulnerabilities. Roman Stepanov

Understanding Sql Injection

AUTHENTICATION... 2 Step 1:Set up your LDAP server... 2 Step 2: Set up your username... 4 WRITEBACK REPORT... 8 Step 1: Table structures...

ABC LTD EXTERNAL WEBSITE AND INFRASTRUCTURE IT HEALTH CHECK (ITHC) / PENETRATION TEST

Cracking the Perimeter via Web Application Hacking. Zach Grace, CISSP, CEH January 17, Mega Conference

SQL Injection for newbie

Kentico CMS security facts

Start Secure. Stay Secure. Blind SQL Injection. Are your web applications vulnerable? By Kevin Spett

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

BUILDING SECURITY IN. Analyzing Mobile Single Sign-On Implementations

FINAL DoIT v.8 APPLICATION SECURITY PROCEDURE

White Paper BMC Remedy Action Request System Security

Security Awareness For Website Administrators. State of Illinois Central Management Services Security and Compliance Solutions

Secure Web Development Teaching Modules 1. Threat Assessment

Still Aren't Doing. Frank Kim

Enterprise Application Security Workshop Series

HTTPParameter Pollution. ChrysostomosDaniel

Exposed Database( SQL Server) Error messages Delicious food for Hackers

Securing Your Web Application against security vulnerabilities. Ong Khai Wei, IT Specialist, Development Tools (Rational) IBM Software Group

Attacking MongoDB. Firstov Mihail

What? Me, Worry? I've Already Been Hacked. Haven't You?

Token Sequencing Approach to Prevent SQL Injection Attacks

IBM Managed Security Services Vulnerability Scanning:

Introduction to Web Application Security. Microsoft CSO Roundtable Houston, TX. September 13 th, 2006

Penetration Testing: Advanced Oracle Exploitation Page 1

Web Development using PHP (WD_PHP) Duration 1.5 months

1. Introduction. 2. Web Application. 3. Components. 4. Common Vulnerabilities. 5. Improving security in Web applications

Last update: February 23, 2004

Transcription:

Web-based Attack: SQL Injection SQL Injection January 23, 2013 Authored By: Stephanie Reetz, SOC Analyst Contents Introduction Introduction...1 Web applications are everywhere on the Internet. Almost Overview...2 everything you do online is done through a web application whether you know it or not. They come in the Attack Scenario...3 form of web-based email, forums, bulletin boards, bill Blind SQL Injection...4 payment, recruitment systems, health benefit and payroll systems. It is important to understand that these types of Mitigation...4 websites are all database driven. Databases are an essential Conclusion...7 element of web applications because they are able to store user preferences, personal identifiable information, and References...8 other sensitive user information Web applications interact with databases to dynamically build customized content for each user. The web application communicates with the database using Structured Query Language (SQL). SQL is a programming language for managing databases that allows you to read and manipulate data in MySQL, SQL Multi- State Information Sharing and Server, Access, Oracle, DB2, and other database systems. Analysis Center The relationship between the web application and the 31 Tech Valley Drive database is commonly abused by attackers through SQL East Greenbush NY, 12061 injection. SQL injection is a type of injection attack in Email: info@msisac.org which SQL commands are supplied in user-input variables, such as a web form entry field, in an attempt to trick the William F. Pelgrin, Chair web application into executing the attacker's code on the Thomas F. Duffy, Executive D irector database. Page 1

SQL injection was one of the primary attack vectors responsible for many of 2011 s high profile compromises including Sony Pictures, HBGary, and PBS. It was also responsible for the more recent Adobe data breach in which names, email addresses, and password hashes were stolen from one of their customer databases. SQL injection is a dangerous vulnerability that is easily detected and inexpensive to fix. This method of attack has been employed by hackers for over ten years yet it is still the most common attack vector in data breaches today. Overview SQL injection ( Improper Neutralization of Special Elements Used in an SQL Command ) is at the top of the most recent CWE/SANS Top 25 Most Dangerous Software Errors list and must be taken seriously. [1] SQL injection occurs when untrusted user-supplied data is entered into a web application and that data is then used to dynamically create a SQL query to be executed by the database server. Web applications generally use server-side scripting languages, such as ASP, JSP, PHP, and CGI, to construct string queries which are passed to the database as a single SQL statement. PHP and ASP applications tend to connect to database servers using older Application Programming Interfaces (API) that are by nature more readily exploited while J2EE and ASP.NET applications are not as likely to be so easily exploited. If a web application is vulnerable to SQL injection, then an attacker has the ability to influence the SQL that is used to communicate with the database. The implications of this are considerable. Databases often contain sensitive information; therefore, an attacker could compromise confidentiality by viewing tables. An attacker may also jeopardize integrity by changing or deleting database records using SQL injection. In other words, an attacker could modify the queries to disclose, destroy, corrupt, or otherwise change the underlying data. It may even be possible to login to a web application as another user with no knowledge of the password if non-validated SQL commands are used to verify usernames and passwords. If a user's level of authorization is stored in the database it may also be changed through SQL injection allowing them more permissions then they should possess. If SQL queries are used for authentication and authorization, an attacker could alter the logic of those queries and bypass the security controls set up by the admin. Web applications may also be vulnerable to second order SQL injection. A second order SQL injection attack occurs when user-supplied data is first stored in the database, then later retrieved and used as part of a vulnerable SQL query. This type of SQL injection vulnerability is more difficult to locate and exploit. Exploitation does not end when the database is compromised, in some cases an attacker may be able to escalate their privileges on the database server allowing them to execute operating system commands. Page 2

Attack Scenario Consider a simple SQL injection vulnerability. The following code builds a SQL query by concatenating a string entered by the user with hard coded strings: string query = "SELECT * FROM items WHERE owner = '" + username + "' AND itemname = '" + ItemName.Text + "'"; The intent of this query is to search for all items that match an item name entered by a user. In the example above, username is the currently authenticated user and ItemName.Text is the input supplied by the user. Suppose a normal user with the username smith enters benefit in the web form. That value is extracted from the form and appended to the query as part of the SELECT condition. The executed query will then look similar to the following: SELECT * FROM items WHERE owner = 'smith' AND itemname = 'benefit' However, because the query is constructed dynamically by concatenating a constant base query string and a user-supplied string, the query only behaves correctly if itemname does not contain a single quote (') character. If an attacker with the username smith enters the string: anything' OR 'a'='a The resulting query will be: SELECT * FROM items WHERE owner = 'smith' AND itemname = 'anything' OR 'a' = 'a' The addition of the OR 'a'='a' condition causes the WHERE clause to always evaluate to true. The query then becomes logically equivalent to the less selective query: SELECT * FROM items The simplified query allows the attacker to see all entries stored in the items table, eliminating the constraint that the query only returns items owned by the authenticated user. In this case the attacker has the ability to read information he should not be able to access. Now assume that the attacker enters the following: anything'; drop table items-- In this case, the following query is built by the script: SELECT * FROM items WHERE owner = 'smith' AND itemname = 'anything'; drop table items--' Page 3

The semicolon (;) denotes the end of one query and the start of another. Many database servers allow multiple SQL statements separated by semicolons to be executed together. This allows an attacker to execute arbitrary commands against databases that permit multiple statements to be executed with one call. The double hyphen (--) indicates that the rest of the current line is a comment and should be ignored. If the modified code is syntactically correct, it will be executed by the server. When the database server processes these two queries, it will first select all records in items that match the value anything belonging to the user smith. Then the database server will drop, or remove, the entire items table. Blind SQL Injection Another form of SQL injection is referred to as blind SQL injection. Normally, if the attacker were to inject SQL code that caused the web application to create an invalid SQL query, then the attacker should receive a syntax error message from the database server. However, the specific error code from the database should not be shared with the end user of an application. It may disclose information about the design of the database that could help an attacker. In an attempt to prevent SQL injection exploitation, some developers return a generic page rather than the error messages or other information from the database. This makes exploiting a potential SQL injection vulnerability more difficult, but not impossible. An attacker will know whether or not a query was valid based on the page returned. If the application is vulnerable and the query is valid, a certain page will be returned. However, if the query is invalid, a different page might be returned. Therefore, an attacker can still get information from the database by asking a series of true and false questions through injected SQL statements. The same page should be returned regardless of if an invalid SQL query was executed. Mitigation The three main defense strategies against SQL injection are parameterized queries, stored procedures, and input validation. The first option is the use of parameterized queries. They require that all SQL code is first defined and then parameters are passed to the query. They are easier to write than dynamic queries and help prevent SQL injection by differentiating between the SQL code and the user-supplied data. This prevents an attacker from changing the design of a query by injecting his own SQL code. For example, if an attacker were to enter anything' OR '1' = '1 a parameterized query would search the database for an item that matched the string anything' OR '1' = '1 instead of inserting OR '1' = '1 into the query. The second defense strategy, comparable to the first, is the use of stored procedures which prevent SQL injection as long as they do not include any unsafe dynamic SQL generation. Again, the SQL code must be defined first and then the parameters are passed. The difference between parameterized Page 4

queries and stored procedures is that the SQL code for a stored procedure is defined and stored in the database itself, then called from the application. Applications can call and execute the stored procedures using the call SQL statement. The syntax and capabilities of stored procedures varies by the type of database. The following code will create a stored procedure that will execute the original query without dangerously concatenating user input with SQL code. CREATE PROCEDURE SearchItems AS @username varchar(50), @useritem varchar(50) BEGIN SELECT * FROM items WHERE owner = @username AND itemname = @useritem; END GO The query structure is already defined on the server before the query is executed and the conditions of the query are passed as parameters, therefore, the user-supplied input will not be mistaken as part of the SQL query. Like with parameterized queries, if an attacker were to submit the string anything' OR '1' = '1, it will be treated as user input, not SQL code. In other words, the query will look for an item with this name instead of executing unexpected SQL code. It is important to note that stored procedures do not prevent SQL injection in and of themselves. If a SQL query is built within a stored procedure by concatenating parameter values, like in the original vulnerable query example, it runs the same risk of SQL injection. An advantage to using this approach is that all database user accounts can be restricted to only access the stored procedures and therefore will not have the authority to run dynamic queries. Without the ability to run dynamic queries, SQL injection vulnerabilities are less likely to be present. The third approach is to escape all user-supplied input before adding it to a query. When usersupplied input is escaped, special characters are replaced with characters the database should not confuse with SQL code written by the developer. The specific functions used for escaping usersupplied input vary by server-side scripting language. For example, in PHP the addslashes() function can be used to insert backslashes before the single quote ('), double quote ("), and backslash (\) char- Page 5

acters as well as before the NULL byte. Note that addslashes() should not be used on strings that have already been escaped with magic_quotes_gpc (enabled by default until removed in PHP 5.4). It is also highly recommended to use database specific escape functions such as mysqli_real_escape_string() for MySQL. Each database management system supports one or more character escaping schemes specific to certain kinds of queries. If all user-supplied input is escaped using the proper escaping scheme for the database, it will not be confused with SQL code written by the developer. This will eliminate some possible SQL injection vulnerabilities, but a determined attacker will be able to find a way to inject SQL code. This technique is not as robust as the others, but may be considered if rewriting dynamic queries as parameterized queries or stored procedures might break a legacy application or have a significant negative impact on performance. Some supplemental protection against SQL injection is offered by using a whitelist for input validation. Input validation can be used to detect unauthorized input before it is processed by the application. A whitelist approach to input validation involves defining exactly what input is authorized. All other input is considered unauthorized. A very rigid validation pattern using regular expressions should be created for well structured fields such as phone numbers, dates, social security numbers, credit card numbers, email addresses, etc. If the data the user enters does not match the pattern it should not be processed. If the input field has a fixed set of options, such as a drop down list or radio buttons, then the input from that field must exactly match one of those values. The most challenging fields to validate are free text fields, such as forum entries. However, even these fields can be validated to some degree. Unexpected and unnecessary characters should be removed and a maximum size should be defined for the input field. All input fields should be validated using a whitelist. Another measure that can be employed to supplement a main defense strategy is the principal of least privilege for database accounts. In order to limit the damage done by a successful SQL injection attack, administrator access rights should never be assigned to application accounts. Any given user should have access to only the bare minimum set of resources required to perform business tasks. This includes user rights and resource permissions such as CPU and memory limits, network, and file system permissions. Access should only be given to the specific tables an account requires to function properly. If stored procedures are used, then application accounts should only be allowed to execute the stored procedures that they use and they should not have direct access to database tables. It is important to restrict permissions so that if an attacker is able to successfully inject malicious code, the application s database user account will not have the authority to execute the command. The database management system itself should also have minimal privileges on the operating system. Many of these systems run with root or system level access by default and should be changed to more limited permissions. This will make it more difficult for an attacker to gain system level access through SQL injection. Page 6

Conclusion It is important to know how to identify and remediate SQL injection vulnerabilities because the vast majority of data breaches are due to poorly coded web applications. Any code that constructs SQL statements should be reviewed for SQL injection vulnerabilities since a database server will execute all queries that are syntactically valid. Also, keep in mind that even data that has been parameterized can be manipulated by a skillful and persistent attacker. Therefore, web applications should be built with security in mind and regularly tested for SQL injection vulnerabilities. More information about SQL injection and how to prevent it, including specific examples for a variety of scripting languages, as well as guidelines to review code and test for SQL injection vulnerabilities can be found at the Open Web Application Security Project (OWASP). See references below. [2] Page 7

References [1] "2011 CWE/SANS Top 25 Most Dangerous Software Errors." mitre.org. Ed. Steve Christey. The MITRE Corporation, 2011. Web. 8 Nov. 2012. <http://cwe.mitre.org/top25/index.html#cwe- 89>. [2] The Open Web Application Security Project (OWASP): "SQL Injection." owasp.org. The Open Web Application Security Project, 8 July 2012. Web. 7 Nov. 2012. <https://www.owasp.org/index.php/sql_injection>. "SQL Injection Prevention Cheat Sheet." owasp.org. The Open Web Application Security Project, 8 July 2012. Web. 8 Nov. 2012. <https://www.owasp.org/index.php/sql_injection_prevention_cheat_sheet>. "Blind SQL Injection." owasp.org. The Open Web Application Security Project, 8 July 2012. Web. 10 Nov. 2012. <https://www.owasp.org/index.php/blind_sql_injection>. Page 8