C HAPTER 8 SQL Injection Slides adapted from "Foundations of Security: What Every Programmer Needs To Know" by Neil Daswani, Christoph Kern, and Anita.

Slides:



Advertisements
Similar presentations
Module XIV SQL Injection
Advertisements

Creating Stronger, Safer, Web Facing Code JPL IT Security Mary Rivera June 17, 2011.
Understand Database Security Concepts
How Did I Steal Your Database Mostafa
NECESSARY BACKGROUND ON MEMORY EXPLOITS AND WEB APPLICATION VULNERABILITIES 1.
Introduction The concept of “SQL Injection”
SQL Hacking I NTRODUCTION Data theft is becoming a major threat. Criminals have identified where the gold is. In the last year many databases from.
SQL Injection Attacks Prof. Jim Whitehead CMPS 183: Spring 2006 May 17, 2006.
LCT2506 Internet 2 Further SQL Stored Procedures.
CMSC 414 Computer and Network Security Lecture 18 Jonathan Katz.
Dec 13 th CS555 presentation1 Yiwen Wang --“Securing the DB may be the single biggest action an organization can take to protect its assets” David C. Knox.
SQL Injection Attacks CS 183 : Hypermedia and the Web UC Santa Cruz.
Injection Attacks by Example SQL Injection and XSS Adam Forsythe Thomas Hollingsworth.
1 SQL injection: attacks and defenses Dan Boneh CS 142 Winter 2009.
Presenter Deddie Tjahjono.  Introduction  Website Application Layer  Why Web Application Security  Web Apps Security Scanner  About  Feature  How.
Web Application Vulnerabilities Checklist. EC-Council Parameter Checklist  URL request  URL encoding  Query string  Header  Cookie  Form field 
Check That Input Preventing SQL Injection Attacks By Andrew Morton For CS 410.
Web Security Programming I Building Security in from the Start Except where otherwise noted all portions of this work are Copyright (c) 2007 Google and.
+ Websites Vulnerabilities. + Content Expand of The Internet Use of the Internet Examples Importance of the Internet How to find Security Vulnerabilities.
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
SQL INJECTION COUNTERMEASURES &
Hamdi Yesilyurt, MA Student in MSDF & PhD-Public Affaris SQL Riji Jacob MS Student in Computer Science.
(CPSC620) Sanjay Tibile Vinay Deore. Agenda  Database and SQL  What is SQL Injection?  Types  Example of attack  Prevention  References.
CSCI 6962: Server-side Design and Programming Secure Web Programming.
Web Application Access to Databases. Logistics Test 2: May 1 st (24 hours) Extra office hours: Friday 2:30 – 4:00 pm Tuesday May 5 th – you can review.
AMNESIA: Analysis and Monitoring for NEutralizing SQL- Injection Attacks Published by Wiliam Halfond and Alessandro Orso Presented by El Shibani Omar CS691.
Lecture slides prepared for “Computer Security: Principles and Practice”, 3/e, by William Stallings and Lawrie Brown, Chapter 5 “Database and Cloud Security”.
Lecture 16 Page 1 CS 236 Online SQL Injection Attacks Many web servers have backing databases –Much of their information stored in a database Web pages.
Preventing Web Application Injections with Complementary Character Coding Raymond Mui Phyllis Frankl Polytechnic Institute of NYU Presented at ESORICS.
Attacking Applications: SQL Injection & Buffer Overflows.
Programming using C# Joins SQL Injection Stored Procedures
Top Five Web Application Vulnerabilities Vebjørn Moen Selmersenteret/NoWires.org Norsk Kryptoseminar Trondheim
CANDID : Preventing SQL Injection Attacks Using Dynamic Candidate Evaluations V. N. Venkatakrishnan Assistant Professor, Computer Science University of.
Effective Security in ASP.Net Applications Jatin Sharma: Summer 2005.
Attacking Data Stores Brad Stancel CSCE 813 Presentation 11/12/2012.
Analysis of SQL injection prevention using a filtering proxy server By: David Rowe Supervisor: Barry Irwin.
Accessing Your MySQL Database from the Web with PHP (Ch 11) 1.
Injection CSC 482/582: Computer SecuritySlide #1.
Sumanth M Ganesh B CPSC 620.  SQL Injection attacks allow a malicious individual to execute arbitrary SQL code on your server  The attack could involve.
Aniket Joshi Justin Thomas. Agenda Introduction to SQL Injection SQL Injection Attack SQL Injection Prevention Summary.
Building Secure Web Applications With ASP.Net MVC.
By Sean Rose and Erik Hazzard.  SQL Injection is a technique that exploits security weaknesses of the database layer of an application in order to gain.
SQL – Injections Intro. Prajen Bhadel College of Information Technology & Engeneering Kathmandu tinkune Sixth semister.
Web Security Lesson Summary ●Overview of Web and security vulnerabilities ●Cross Site Scripting ●Cross Site Request Forgery ●SQL Injection.
Database Security Cmpe 226 Fall 2015 By Akanksha Jain Jerry Mengyuan Zheng.
CS 142 Lecture Notes: Injection AttacksSlide 1 Unsafe Server Code advisorName = params[:form][:advisor] students = Student.find_by_sql( "SELECT students.*
SQL Injection Anthony Brown March 4, 2008 IntroductionQuestionsBackgroundTechniquesPreventionDemoConclusions.
Secure Authentication. SQL Injection Many web developers are unaware of how SQL queries can be tampered with SQL queries are able to circumvent access.
INFO 344 Web Tools And Development CK Wang University of Washington Spring 2014.
SQL Injection Attacks An overview by Sameer Siddiqui.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
ADVANCED SQL.  The SQL ORDER BY Keyword  The ORDER BY keyword is used to sort the result-set by one or more columns.  The ORDER BY keyword sorts the.
SQL Injection By: Ayman Mohamed Abdel Rahim Ali Ehab Mohamed Hassan Ibrahim Bahaa Eldin Mohamed Abdel Sabour Tamer Mohamed Kamal Eldin Jihad Ahmad Adel.
SQL Injection Attacks S Vinay Kumar, 07012D0506. Outline SQL Injection ? Classification of Attacks Attack Techniques Prevention Techniques Conclusion.
M M Waseem Iqbal.  Cause: Unverified/unsanitized user input  Effect: the application runs unintended SQL code.  Attack is particularly effective if.
Introduction SQL Injection is a very old security attack. It first came into existence in the early 1990's ex: ”Hackers” movie hero does SQL Injection.
Cosc 5/4765 Database security. Database Databases have moved from internal use only to externally accessible. –Organizations store vast quantities of.
Database and Cloud Security
SQL Injection.
Database System Implementation CSE 507
Group 18: Chris Hood Brett Poche
CSC 482/582: Computer Security
SQL Injection.
SE604: Software Testing and QA Secure SW Development for QA Lecture#3
SQL INJECTION ATTACKS.
SQL Injection Attacks Many web servers have backing databases
Pengantar Keamanan Informasi
PHP: Security issues FdSc Module 109 Server side scripting and
Chapter 13 Security Methods Part 3.
Lecture 2 - SQL Injection
Presentation transcript:

C HAPTER 8 SQL Injection Slides adapted from "Foundations of Security: What Every Programmer Needs To Know" by Neil Daswani, Christoph Kern, and Anita Kesavan (ISBN ; Except as otherwise noted, the content of this presentation is licensed under the Creative Commons 3.0 License.

Agenda Command injection vulnerability - untrusted input inserted into query or command  Attack string alters intended semantics of command  Ex: SQL Injection - unsanitized data used in query to back-end database (DB) SQL Injection Examples & Solutions  Type 1: compromises user data  Type 2: modifies critical data  Whitelisting over Blacklisting  Escaping  Prepared Statements and Bind Variables

SQL Injection Impact in the Real World CardSystems, credit card payment processing Ruined by SQL Injection attack in June ,000 credit card #s stolen from its DB #s stored unencrypted, 40 million exposed Awareness Increasing: # of reported SQL injection vulnerabilities tripled from 2004 to 2005

8.1. Attack Scenario (1) Ex: Pizza Site Reviewing Orders  Form requesting month # to view orders for  HTTP request:

8.1. Attack Scenario (2) App constructs SQL query from parameter: Type 1 Attack: inputs month='0 OR 1=1' ! Goes to encoded URL: (space -> %20, = -> %3D ) sql_query = "SELECT pizza, toppings, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " " + "AND order_month=" + request.getParamenter("month"); SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=10 Normal SQL Query

WHERE condition is always true!  OR precedes AND  Type 1 Attack: Gains access to other users’ private data! 8.1. Attack Scenario (3) Malicious Query SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 OR 1=1 All User Data Compromised

8.1. Attack Scenario (4) More damaging attack: attacker sets month= Attacker is able to  Combine 2 queries  1 st query: empty table (where fails)  2 nd query: credit card #s of all users 0 AND 1=0 UNION SELECT cardholder, number, exp_month, exp_year FROM creditcards

8.1. Attack Scenario (4) Even worse, attacker sets Then DB executes  Type 2 Attack: Removes creditcards from schema!  Future orders fail: DoS! Problematic Statements:  Modifiers: INSERT INTO admin_users VALUES ('hacker',...)  Administrative: shut down DB, control OS… month=0; DROP TABLE creditcards; SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0; DROP TABLE creditcards;

8.1. Attack Scenario (5) Injecting String Parameters: Topping Search Attacker sets: topping=brzfg%'; DROP table creditcards; -- Query evaluates as:  SELECT: empty table  -- comments out end  Credit card info dropped sql_query = "SELECT pizza, toppings, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " " + "AND topping LIKE '%" + request.getParamenter("topping") + "%' "; SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND topping LIKE '%brzfg%'; DROP table creditcards; --%'

8.1. Attack Scenario (6) Source:

8.2. Solutions Variety of Techniques: Defense-in-depth Whitelisting over Blacklisting Input Validation & Escaping Use Prepared Statements & Bind Variables Mitigate Impact

Why Blacklisting Does Not Work Eliminating quotes enough (blacklist them)? kill_quotes (Java) removes single quotes: sql_query = "SELECT pizza, toppings, quantity, order_day " + "FROM orders " + "WHERE userid=" + session.getCurrentUserId() + " " + "AND topping LIKE 'kill_quotes(request.getParamenter("topping")) + "%'"; String kill_quotes(String str) { StringBuffer result = new StringBuffer(str.length()); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != '\'') result.append(str.charAt(i)); } return result.toString(); }

Pitfalls of Blacklisting Filter quotes, semicolons, whitespace, and…?  Could always miss a dangerous character  Blacklisting not comprehensive solution  Ex: kill_quotes() can’t prevent attacks against numeric parameters May conflict with functional requirements How to store O’Brien in DB if quotes blacklisted?

Whitelisting-Based Input Validation Whitelisting – only allow input within well-defined set of safe values  set implicitly defined through regular expressions  RegExp – pattern to match strings against Ex: month parameter: non-negative integer  RegExp: ^[0-9]*$ - 0 or more digits, safe subset  The ^, $ match beginning and end of string  [0-9] matches a digit, * specifies 0 or more

Escaping Could escape quotes instead of blacklisting Ex: insert user o'connor, password terminator  escape(o'connor) = o''connor Like kill_quotes, only works for string inputs Numeric parameters could still be vulnerable sql = "INSERT INTO USERS(uname,passwd) " + "VALUES (" + escape(uname)+ "," + escape(password) +")"; INSERT INTO USERS(uname,passwd) VALUES ('o''connor','terminator');

Second-Order SQL Injection (1) Second-Order SQL Injection: data stored in database is later used to conduct SQL injection  Common if string escaping is applied inconsistently  Ex: o'connor updates passwd to SkYn3t  Username not escaped, b/c originally escaped before entering DB, now inside our trust zone:  Query fails b/c ' after o ends command prematurely new_passwd = request.getParameter("new_passwd"); uname = session.getUsername(); sql = "UPDATE USERS SET passwd='"+ escape(new_passwd) + "' WHERE uname='" + uname + "'"; UPDATE USERS SET passwd='SkYn3t' WHERE uname='o'connor'

Second-Order SQL Injection (2) Even Worse: What if user set uname=admin'-- !?  Attacker changes admin ’s password to cracked  Has full access to admin account  Username avoids collision with real admin  -- comments out trailing quote All parameters dangerous: escape(uname) UPDATE USERS SET passwd='cracked' WHERE uname='admin' --'

Prepared Statements & Bind Variables Metachars (e.g. quotes) provide distinction between data & control in queries  most attacks: data interpreted as control  alters the semantics of a query Bind Variables: ? placeholders guaranteed to be data (not control) Prepared Statements allow creation of static queries with bind variables  Preserves the structure of intended query  Parameters not involved in query parsing/compiling

Java Prepared Statements PreparedStatement ps = db.prepareStatement("SELECT pizza, toppings, quantity, order_day " + "FROM orders WHERE userid=? AND order_month=?"); ps.setInt(1, session.getCurrentUserId()); ps.setInt(2, Integer.parseInt(request.getParamenter("month"))); ResultSet res = ps.executeQuery(); Bind Variable: Data Placeholder Query parsed without parameters Bind variables are typed: input must be of expected type (e.g. int, string)

PHP Prepared Statements No explicit typing of parameters like in Java Apply consistently: adding $year parameter directly to query still creates SQL injection threat Have separate module for DB access  Do prepared statements here  Gateway to DB for rest of code $ps = $db->prepare( 'SELECT pizza, toppings, quantity, order_day '. 'FROM orders WHERE userid=? AND order_month=?'); $ps->execute(array($current_user_id, $month));

SQL Stored Procedures Stored procedure: sequence of SQL statements executing on specified inputs Ex: Vulnerable use: Instead use bind variables w/ stored procedure: CREATE PROCEDURE VARCHAR(25) AS UPDATE USERS SET passwd=new_passwd WHERE uname=username $ps = $db->prepare("change_password ?, ?"); $ps->execute(array($uname, $new_passwd)); $db->exec("change_password '"+$uname+"','"+new_passwd+"'");

Mitigating the Impact of SQL Injection Attacks Prevent Schema & Information Leaks Limit Privileges (Defense-in-Depth) Encrypt Sensitive Data stored in Database Harden DB Server and Host O/S Apply Input Validation

Prevent Schema & Information Leaks Knowing database schema makes attacker’s job easier Blind SQL Injection: attacker attempts to interrogate system to figure out schema Prevent leakages of schema information Don’t display detailed error messages and stack traces to external users

Limiting Privileges Apply Principle of Least Privilege! Limit  Read access, tables/views user can query  Commands (are updates/inserts ok?) No more privileges than typical user needs Ex: could prevent attacker from executing INSERT and DROP statements  But could still be able do SELECT attacks and compromise user data  Not a complete fix, but less damage

Encrypting Sensitive Data Encrypt data stored in the database  second line of defense  w/o key, attacker can’t read sensitive info Key management precautions: don’t store key in DB, attacker just SQL injects again to get it Some databases allow automatic encryption, but these still return plaintext queries!

Hardening DB Server and Host O/S Dangerous functions could be on by default Ex: Microsoft SQL Server  Allows users to open inbound/outbound sockets  Attacker could steal data, upload binaries, port scan victim’s network Disable unused services and accounts on OS (Ex: No need for web server on DB host)

Applying Input Validation Validation of query parameters not enough Validate all input early at entry point into code Reject overly long input (could prevent unknown buffer overflow exploit in SQL parser) Redundancy helps protect systems  E.g. if programmer forgets to apply validation for query input  Two lines of defense

Summary SQL injection attacks are important security threat that can  Compromise sensitive user data  Alter or damage critical data  Give an attacker unwanted access to DB Key Idea: Use diverse solutions, consistently!  Whitelisting input validation & escaping  Prepared Statements with bind variables