SQL Injec*on Preven*on. May 3rd 2012



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

1. What is SQL Injection?

SQL Injection Attack Lab

SQL Injection January 23, 2013

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

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

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

1. Building Testing Environment

SQL Injection Attack Lab Using Collabtive

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

SECURING APACHE : THE BASICS - III

Sophos Enterprise Console Auditing user guide. Product version: 5.2

Real SQL Programming 1

CPE111 COMPUTER EXPLORATION

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

Online shopping store

SQL Injection. Sajjad Pourali CERT of Ferdowsi University of Mashhad

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

Advanced Web Security, Lab

SQL Injection for newbie

Database Driven Websites Using PHP with Informix

Web Application Security

SQL Injection Attacks. Prof. Jim Whitehead CMPS 183: Spring 2006 May 17, 2006

USING FILERELICATIONPRO TO REPLICATE SQL SERVER

Application note: Connecting the to a Database

Maintaining Stored Procedures in Database Application

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

CSCI110 Exercise 4: Database - MySQL

How I hacked PacketStorm ( )

Security and Control Issues within Relational Databases

Defending Against Web App A0acks Using ModSecurity. Jason Wood Principal Security Consultant Secure Ideas

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

A Brief Introduction to MySQL

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

With so many web applications, universities have a huge attack surface often without the IT security budgets or influence to back it up.

MatriXay Database Vulnerability Scanner V3.0

Web application security: Testing for vulnerabilities

Detecting (and even preventing) SQL Injection Using the Percona Toolkit and Noinject!

Video Administration Backup and Restore Procedures

Backup and Restore MySQL Databases

Version of this tutorial: 1.06a (this tutorial will going to evolve with versions of NWNX4)

PHP Tutorial From beginner to master

HOW TO CONNECT TO CAC DATABASE SERVER USING MySQL

Advanced Tornado TWENTYONE Advanced Tornado Accessing MySQL from Python LAB

WordPress Security Scan Configuration

PHP Authentication Schemes

Webapps Vulnerability Report

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

Web Application Guidelines

A table is a collection of related data entries and it consists of columns and rows.

Nixu SNS Security White Paper May 2007 Version 1.2

Understanding Sql Injection

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

Enhanced Model of SQL Injection Detecting and Prevention

Aradial Installation Guide

Web Development using PHP (WD_PHP) Duration 1.5 months

Novell Identity Manager

Accessing External Databases from Mobile Applications

Chancery SMS Database Split

Connecting to a Database Using PHP. Prof. Jim Whitehead CMPS 183, Spring 2006 May 15, 2006

OpenPro ERP Software Installation Guide Talbert Ave Suite 200 Fountain Valley, CA USA Phone Fax

MySQL Quick Start Guide

SQL Injection Vulnerabilities in Desktop Applications

USING MYWEBSQL FIGURE 1: FIRST AUTHENTICATION LAYER (ENTER YOUR REGULAR SIMMONS USERNAME AND PASSWORD)

Automated vulnerability scanning and exploitation

How To Let A Lecturer Know If Someone Is At A Lecture Or If They Are At A Guesthouse

Enterprise Application Security Workshop Series

SQL Injection Attack Lab

Advanced PostgreSQL SQL Injection and Filter Bypass Techniques

Perceptive Intelligent Capture Solution Configration Manager

The SkySQL Administration Console

ASL IT SECURITY BEGINNERS WEB HACKING AND EXPLOITATION

Big Bad Moodle Guide By Mike Tupker Version 1

TESTING TOOLS COMP220/285 University of Liverpool slide 1

External Vulnerability Assessment. -Technical Summary- ABC ORGANIZATION

Using the SQL TAS v4

Mercury Users Guide Version 1.3 February 14, 2006

Microsoft SQL Server Scheduling

CHAPTER 5 INTELLIGENT TECHNIQUES TO PREVENT SQL INJECTION ATTACKS

Installing Drupal on Your Local Computer

SQL Injection. Blossom Hands-on exercises for computer forensics and security

Railo Installation on CentOS Linux 6 Best Practices

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

Nikolay Zaynelov Annual LUG-БГ Meeting nikolay.zaynelov.com

LAMP [Linux. Apache. MySQL. PHP] Industrial Implementations Module Description

versasrs HelpDesk quality of service

Database Communica/on in Visual Studio/C# using ASP.NET Web Forms. Hans- PeBer Halvorsen, M.Sc.

MySQL Security for Security Audits

LAMP : THE PROMINENT OPEN SOURCE WEB PLATFORM FOR QUERY EXECUTION AND RESOURCE OPTIMIZATION. R. Mohanty Mumbai, India

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

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

Facebook Twitter YouTube Google Plus Website

Installation Tutorial Script: The Real Estate Script. 1. Please login to download script. On PHP Classifieds Script web site.

Click Studios. Passwordstate. Installation Instructions

A basic create statement for a simple student table would look like the following.

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

.NET Family of Products Installation Guide

Transcription:

SQL Injec*on Preven*on May 3rd 2012

About Me Tom Webb webbtc@mailbox.sc.edu 803-777- 1701 12 Years in IT Over 6 years at USC Irhowto.wordpress.com computer- forensics.sans.org/blog

Who should AOend this Talk DBA s Web Programmers

What We are going to Cover Brief Discussion of what is SQL Injec*on SQL Applica*on Side Language Side (PHP,ASP) OS Side

What we are NOT going to cover Hacking techniques using SQL Injec*on Tons of presenta*ons on how to do this

What is SQL Injec*on? SQL injec*on is an a.ack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execu*on h.p://msdn.microso@.com/en- us/library/ ms161953.aspx

Where SQL Injec*on Takes place? Any place you take input from a user and its passed to the database.

Simple Select Statement Tbl_users ID Name Email Phone Address passwd 1 Bob bob@aol.com 77101 12 main st 1234 2 Jim jim@aol.com 7-0001 32 sun st pass select email from tbl_user where name = bob ; bob@aol.com

SQL injec*on ID Name Email Phone Address passwd 1 Bob bob@aol.com 77101 12 main st 1234 2 Jim jim@aol.com 7-0001 32 sun st pass select email from tbl_user where name = bob and union select name, passwd from tbl_user; - - ; Bob,1234 Jim,pass

Escala*ng the Vulnerability on any Plaeorm Get data from the any Table/Database the user rights allowed Write Files to the Server. (Backdoors) Union select nc l p 3333 e /bin/bash,, into output file /etc/cron.hourly/backup.sh Read file on the server UNION SELECT LOAD_FILE('/etc/passwd'),, Execute commands on the server

Preven*on SQL Applica*on Side SQL User Database Rights Limit right to just select for specific users Stored Procedures Language Side (PHP,ASP) OS Side Limit rights of the service/user running App Armor (Ubuntu) or SELinux (CentOS)

Preven*on (2) DO NOT STORE SENSTIVIE DATA! If you need to, don t sore on system accessible from the Internet.

PROTECTION WITHIN SQL

Prepared Statement (Parameterized Queries) Parameterized queries force the developer to first define all the SQL code, and then pass in each parameter to the query later. This coding style allows the database to dis*nguish between code and data, regardless of what user input is supplied. (hop://owasp.org/index.php/ SQL_Injec*on_Preven*on_Cheat_Sheet)

Prepared Statement (2) MySQL 'Select * from table where name is? Oracle PL/SQL 'SELECT * FROM table where name=:1 ' MSSQL "SELECT * FROM table WHERE name =?

MySQL Prepared Statement prepare id from 'select Id from table where name=?' ; set @myname :='mycomputer'; execute id @myname; DEALLOCATE PREPARE id;

MySQL Procedure DROP PROCEDURE IF EXISTS `table`.`get_id`; DELIMITER $$ CREATE PROCEDURE `IR`.`get_id`(IN input VARCHAR(20), OUT id VARCHAR(5)) READS SQL DATA BEGIN SET @input=input; prepare id from 'select Id from table where name=?' ; execute id USING @input; DEALLOCATE PREPARE id; END$$

MySQL Procedure (2) mysql>call get_id('mycomputer', @out); +- - - - - - - + @out +- - - - - - + 1 +- - - - - - +

MYSQL Stored Procedure Troubleshoo*ng Print output using select to troubleshoot Select @variable; Set GLOBAL general_log= ON ; Set GLOBAL log_output = table ; Select * from mysql.general_log limit 50; Don t forget to turn this off!

DECLARE username varchar2(32); password varchar2(32); result integer; BEGIN Oracle PL/SQL Execute immediate 'SELECT count(*) FROM users where username=:1 and password=:2' into result using username,password; END; (Clarke, 2009, Ch. 8)

MSSQL CREATE PROCEDURE SP_ProductSearch @prodname varchar(400) = NULL AS DECLARE @sql nvarchar(4000) SELECT @sql = ' SELET ProductID, ProductName, Category, Price ' + ' FROM Product Where ' IF @prodname IS NOT NULL SELECT @sql = @sql + ' ProductName LIKE @prodname' EXEC sp_executesql @sql, N'@prodname varchar(400)',@prodname (palizine.plynt.com)

Implementa*on Strategy Highest Protec*on level. Best for client side code. Most likely this will be implemented for new applica*ons. Pro Logic built into the database. Client side independent.

PREPARED STATEMENTS WITH OTHER LANGUAGES

PHP $con = new mysqli( localhost, username, password, db ); $sql = SELECT * FROM users WHERE username=? AND password=? ; $cmd = $con- >prepare($sql); // Add parameters to SQL query $cmd- >bind_param( ss, $username, $password); // bind parameters as strings $cmd- >execute(); (Clarke, 2009, Ch. 8)

PHP PDO Package $sql = SELECT * FROM users WHERE username=:username AND + password=:password ; $stmt = $dbh- >prepare($sql); // bind values and data types $stmt- >bindparam(':username', $username, PDO::PARAM_STR, 12); $stmt- >bindparam(':password', $password, PDO::PARAM_STR, 12); $stmt- >execute(); (Clarke, 2009, Ch. 8)

.net String query = "SELECT account_balance FROM user_data WHERE user_name =?"; try { OleDbCommand command = new OleDbCommand(query, connec*on); command.parameters.add(new OleDbParameter("customerName", CustomerName Name.Text)); OleDbDataReader reader = command.executereader(); } catch (OleDbExcep*on se) { // error handling } (hops://www.owasp.org/index.php/ SQL_Injec*on_Preven*on_Cheat_Sheet)

Implementa*on Strategy Highest Protec*on level. Most likely this will be implemented by replacing the dynamic sql queries with prepared statements. Pro Easier to implement then SQL server.

ESCAPING USER INPUT

Oracle Escape Codec ORACLE_CODEC = new OracleCodec(); String query = "SELECT user_id FROM user_data WHERE user_name = '" + ESAPI.encoder().encodeForSQL( ORACLE_CODEC, req.getparameter("userid")) + "' and user_password = + ESAPI.encoder().encodeForSQL( ORACLE_CODEC, req.getparameter("pwd")) +"'"; (hops://www.owasp.org/index.php/ SQL_Injec*on_Preven*on_Cheat_Sheet)

ASP.net Valida*on <td> <input type=text runat=server id=txtname> <asp:regularexpressionvalidator runat=server ControlToValidate="txtName" ErrorMessage="ID must be 6-10 leoers." Valida*onExpression="[a- za- Z]{6,10}" /> </td> (hop://msdn.microso.com/en- us/library/ms972961.aspx)

PHP MySQL (w3schools.com) // Stripslashes if (get_magic_quotes_gpc()) { $value = stripslashes($value); } if (!is_numeric($value)) { $value = "'". mysql_real_escape_string($va lue). "' ; } return $value; // Make a safe SQL $user = check_input($_post['user']); $pwd = check_input($_post['pwd']); $sql = "SELECT * FROM users WHERE user=$user AND password=$pwd"; mysql_query($sql); mysql_close($con);

PHP Valida*on $username = $_POST['username']; if (!preg_match( /^[a- za- Z]{8,12}$/D, $username) { // handle failed valida*on } (Clarke, 2009, Ch. 8)

Implementa*on Strategy Medium Protec*on level. Can be bypassed, best to whitelist input. Should be included along with prepared statements. Pro Can be added to legacy code quickly (Band- Aid).

APPLICATION HARDENING

Disable Error Messages Asp.net web.config IIS <configura*on> <system.web> <customerrors mode="remoteonly"> <compila*on debug="false"> Double click on website from IIS snap- in select custom error tab

PHP Disable Error Messages (2) Edit php.ini Apache set display_errors=off html_errors = Off HOpd.conf ErrorDocument 500 "Sorry, our script crashed. Oh dear" (hop://hopd.apache.org/docs/2.0/custom- error.html)

Limit DB Users Access Only allow user access to what it needs. If you only do select on one table give just select rights. Create a unique user per web applica*on/ database

Limit DB Users Access(2) MySQL Grant select (ID,name) on DB.Table to user @ % ; Grant execute ON Procedure `table`.`procedure` to user @ % ; MSSQL GRANT SELECT ON OBJECT::DB.Table TO user; GRANT EXECUTE ON OBJECT::Db.Table TO user;

Limit DB Users Access(2) ORACLE grant select, on table to user; grant execute on Procedure to user;

Blocking External Access Apache.config <Directory /var/www/phpmyadmin/> Order deny,allow Deny from all Allow from 129.252.41.0/24 Allow from 127.0.0.1 </Directory> IIS hop://support.microso.com/kb/324066

Hardening Guide hops://benchmarks.cisecurity.org/en- us/? route=downloads.mul*form Great Informa*on, but could break your applica*on. BACKUP YOUR CONFIGURATIONS BEFORE USING THEM!!!!

Implementa*on Strategy All these configura*on se ng should be applied. Pro Easy to implement without changing code.

PATCHING!!!!!

What to Patch Services (Oracle,MySQL,Apache,IIS,ect ) Content Management Systems (Joomula!) Languages (PHP,Perl.) Web Applica*ons (PHPmyadmin, webmin, Calendar apps, Forums, Wordpress) Subscribe to RSS, email lists, forums that have patch no*fica*ons.

ADDITIONAL PROTECTION

Rule Based Applica*on Protec*ons Mod_Security Apache module that has rules to block aoacks URL SCAN IIS module that has rules to block aoacks GreenSQL MySQL and Postgres SQL Proxy

Implementa*on Strategy Defense in Depth Band- Aid approach if you are not allowed to change anything on a server, but keep it running.

References Clarke, Jus*n (2009). SQL Injec*on AOacks and Defense. Burlington, MA. Syngress Publishing hop://www.w3schools.com/php/ func_mysql_real_escape_string.asp Kumar, Santosh (2006). Are stored procedures safe against SQL injec*on?. Retrieved: April 2012. Web Site hop:// palizine.plynt.com/issues/2006jun/injec*on- stored- procedures/